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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(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. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. function EventEmitter() {
  23. this._events = this._events || {};
  24. this._maxListeners = this._maxListeners || undefined;
  25. }
  26. module.exports = EventEmitter;
  27. // Backwards-compat with node 0.10.x
  28. EventEmitter.EventEmitter = EventEmitter;
  29. EventEmitter.prototype._events = undefined;
  30. EventEmitter.prototype._maxListeners = undefined;
  31. // By default EventEmitters will print a warning if more than 10 listeners are
  32. // added to it. This is a useful default which helps finding memory leaks.
  33. EventEmitter.defaultMaxListeners = 10;
  34. // Obviously not all Emitters should be limited to 10. This function allows
  35. // that to be increased. Set to zero for unlimited.
  36. EventEmitter.prototype.setMaxListeners = function(n) {
  37. if (!isNumber(n) || n < 0 || isNaN(n))
  38. throw TypeError('n must be a positive number');
  39. this._maxListeners = n;
  40. return this;
  41. };
  42. EventEmitter.prototype.emit = function(type) {
  43. var er, handler, len, args, i, listeners;
  44. if (!this._events)
  45. this._events = {};
  46. // If there is no 'error' event listener then throw.
  47. if (type === 'error') {
  48. if (!this._events.error ||
  49. (isObject(this._events.error) && !this._events.error.length)) {
  50. er = arguments[1];
  51. if (er instanceof Error) {
  52. throw er; // Unhandled 'error' event
  53. }
  54. throw TypeError('Uncaught, unspecified "error" event.');
  55. }
  56. }
  57. handler = this._events[type];
  58. if (isUndefined(handler))
  59. return false;
  60. if (isFunction(handler)) {
  61. switch (arguments.length) {
  62. // fast cases
  63. case 1:
  64. handler.call(this);
  65. break;
  66. case 2:
  67. handler.call(this, arguments[1]);
  68. break;
  69. case 3:
  70. handler.call(this, arguments[1], arguments[2]);
  71. break;
  72. // slower
  73. default:
  74. len = arguments.length;
  75. args = new Array(len - 1);
  76. for (i = 1; i < len; i++)
  77. args[i - 1] = arguments[i];
  78. handler.apply(this, args);
  79. }
  80. } else if (isObject(handler)) {
  81. len = arguments.length;
  82. args = new Array(len - 1);
  83. for (i = 1; i < len; i++)
  84. args[i - 1] = arguments[i];
  85. listeners = handler.slice();
  86. len = listeners.length;
  87. for (i = 0; i < len; i++)
  88. listeners[i].apply(this, args);
  89. }
  90. return true;
  91. };
  92. EventEmitter.prototype.addListener = function(type, listener) {
  93. var m;
  94. if (!isFunction(listener))
  95. throw TypeError('listener must be a function');
  96. if (!this._events)
  97. this._events = {};
  98. // To avoid recursion in the case that type === "newListener"! Before
  99. // adding it to the listeners, first emit "newListener".
  100. if (this._events.newListener)
  101. this.emit('newListener', type,
  102. isFunction(listener.listener) ?
  103. listener.listener : listener);
  104. if (!this._events[type])
  105. // Optimize the case of one listener. Don't need the extra array object.
  106. this._events[type] = listener;
  107. else if (isObject(this._events[type]))
  108. // If we've already got an array, just append.
  109. this._events[type].push(listener);
  110. else
  111. // Adding the second element, need to change to array.
  112. this._events[type] = [this._events[type], listener];
  113. // Check for listener leak
  114. if (isObject(this._events[type]) && !this._events[type].warned) {
  115. var m;
  116. if (!isUndefined(this._maxListeners)) {
  117. m = this._maxListeners;
  118. } else {
  119. m = EventEmitter.defaultMaxListeners;
  120. }
  121. if (m && m > 0 && this._events[type].length > m) {
  122. this._events[type].warned = true;
  123. console.error('(node) warning: possible EventEmitter memory ' +
  124. 'leak detected. %d listeners added. ' +
  125. 'Use emitter.setMaxListeners() to increase limit.',
  126. this._events[type].length);
  127. if (typeof console.trace === 'function') {
  128. // not supported in IE 10
  129. console.trace();
  130. }
  131. }
  132. }
  133. return this;
  134. };
  135. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  136. EventEmitter.prototype.once = function(type, listener) {
  137. if (!isFunction(listener))
  138. throw TypeError('listener must be a function');
  139. var fired = false;
  140. function g() {
  141. this.removeListener(type, g);
  142. if (!fired) {
  143. fired = true;
  144. listener.apply(this, arguments);
  145. }
  146. }
  147. g.listener = listener;
  148. this.on(type, g);
  149. return this;
  150. };
  151. // emits a 'removeListener' event iff the listener was removed
  152. EventEmitter.prototype.removeListener = function(type, listener) {
  153. var list, position, length, i;
  154. if (!isFunction(listener))
  155. throw TypeError('listener must be a function');
  156. if (!this._events || !this._events[type])
  157. return this;
  158. list = this._events[type];
  159. length = list.length;
  160. position = -1;
  161. if (list === listener ||
  162. (isFunction(list.listener) && list.listener === listener)) {
  163. delete this._events[type];
  164. if (this._events.removeListener)
  165. this.emit('removeListener', type, listener);
  166. } else if (isObject(list)) {
  167. for (i = length; i-- > 0;) {
  168. if (list[i] === listener ||
  169. (list[i].listener && list[i].listener === listener)) {
  170. position = i;
  171. break;
  172. }
  173. }
  174. if (position < 0)
  175. return this;
  176. if (list.length === 1) {
  177. list.length = 0;
  178. delete this._events[type];
  179. } else {
  180. list.splice(position, 1);
  181. }
  182. if (this._events.removeListener)
  183. this.emit('removeListener', type, listener);
  184. }
  185. return this;
  186. };
  187. EventEmitter.prototype.removeAllListeners = function(type) {
  188. var key, listeners;
  189. if (!this._events)
  190. return this;
  191. // not listening for removeListener, no need to emit
  192. if (!this._events.removeListener) {
  193. if (arguments.length === 0)
  194. this._events = {};
  195. else if (this._events[type])
  196. delete this._events[type];
  197. return this;
  198. }
  199. // emit removeListener for all listeners on all events
  200. if (arguments.length === 0) {
  201. for (key in this._events) {
  202. if (key === 'removeListener') continue;
  203. this.removeAllListeners(key);
  204. }
  205. this.removeAllListeners('removeListener');
  206. this._events = {};
  207. return this;
  208. }
  209. listeners = this._events[type];
  210. if (isFunction(listeners)) {
  211. this.removeListener(type, listeners);
  212. } else {
  213. // LIFO order
  214. while (listeners.length)
  215. this.removeListener(type, listeners[listeners.length - 1]);
  216. }
  217. delete this._events[type];
  218. return this;
  219. };
  220. EventEmitter.prototype.listeners = function(type) {
  221. var ret;
  222. if (!this._events || !this._events[type])
  223. ret = [];
  224. else if (isFunction(this._events[type]))
  225. ret = [this._events[type]];
  226. else
  227. ret = this._events[type].slice();
  228. return ret;
  229. };
  230. EventEmitter.listenerCount = function(emitter, type) {
  231. var ret;
  232. if (!emitter._events || !emitter._events[type])
  233. ret = 0;
  234. else if (isFunction(emitter._events[type]))
  235. ret = 1;
  236. else
  237. ret = emitter._events[type].length;
  238. return ret;
  239. };
  240. function isFunction(arg) {
  241. return typeof arg === 'function';
  242. }
  243. function isNumber(arg) {
  244. return typeof arg === 'number';
  245. }
  246. function isObject(arg) {
  247. return typeof arg === 'object' && arg !== null;
  248. }
  249. function isUndefined(arg) {
  250. return arg === void 0;
  251. }
  252. },{}],2:[function(require,module,exports){
  253. // shim for using process in browser
  254. var process = module.exports = {};
  255. var queue = [];
  256. var draining = false;
  257. function drainQueue() {
  258. if (draining) {
  259. return;
  260. }
  261. draining = true;
  262. var currentQueue;
  263. var len = queue.length;
  264. while(len) {
  265. currentQueue = queue;
  266. queue = [];
  267. var i = -1;
  268. while (++i < len) {
  269. currentQueue[i]();
  270. }
  271. len = queue.length;
  272. }
  273. draining = false;
  274. }
  275. process.nextTick = function (fun) {
  276. queue.push(fun);
  277. if (!draining) {
  278. setTimeout(drainQueue, 0);
  279. }
  280. };
  281. process.title = 'browser';
  282. process.browser = true;
  283. process.env = {};
  284. process.argv = [];
  285. process.version = ''; // empty string to avoid regexp issues
  286. process.versions = {};
  287. function noop() {}
  288. process.on = noop;
  289. process.addListener = noop;
  290. process.once = noop;
  291. process.off = noop;
  292. process.removeListener = noop;
  293. process.removeAllListeners = noop;
  294. process.emit = noop;
  295. process.binding = function (name) {
  296. throw new Error('process.binding is not supported');
  297. };
  298. // TODO(shtylman)
  299. process.cwd = function () { return '/' };
  300. process.chdir = function (dir) {
  301. throw new Error('process.chdir is not supported');
  302. };
  303. process.umask = function() { return 0; };
  304. },{}],3:[function(require,module,exports){
  305. /* jshint -W117 */
  306. /* application specific logic */
  307. var APP =
  308. {
  309. init: function () {
  310. this.UI = require("./modules/UI/UI");
  311. this.API = require("./modules/API/API");
  312. this.connectionquality = require("./modules/connectionquality/connectionquality");
  313. this.statistics = require("./modules/statistics/statistics");
  314. this.RTC = require("./modules/RTC/RTC");
  315. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  316. this.xmpp = require("./modules/xmpp/xmpp");
  317. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  318. this.translation = require("./modules/translation/translation");
  319. this.settings = require("./modules/settings/Settings");
  320. this.DTMF = require("./modules/DTMF/DTMF");
  321. this.members = require("./modules/members/MemberList");
  322. }
  323. };
  324. function init() {
  325. APP.RTC.start();
  326. APP.xmpp.start();
  327. APP.statistics.start();
  328. APP.connectionquality.init();
  329. // Set default desktop sharing method
  330. APP.desktopsharing.init();
  331. APP.keyboardshortcut.init();
  332. APP.members.start();
  333. }
  334. $(document).ready(function () {
  335. var URLPRocessor = require("./modules/URLProcessor/URLProcessor");
  336. URLPRocessor.setConfigParametersFromUrl();
  337. APP.init();
  338. APP.translation.init();
  339. if(APP.API.isEnabled())
  340. APP.API.init();
  341. APP.UI.start(init);
  342. });
  343. $(window).bind('beforeunload', function () {
  344. if(APP.API.isEnabled())
  345. APP.API.dispose();
  346. });
  347. module.exports = APP;
  348. },{"./modules/API/API":4,"./modules/DTMF/DTMF":5,"./modules/RTC/RTC":9,"./modules/UI/UI":11,"./modules/URLProcessor/URLProcessor":42,"./modules/connectionquality/connectionquality":43,"./modules/desktopsharing/desktopsharing":44,"./modules/keyboardshortcut/keyboardshortcut":45,"./modules/members/MemberList":46,"./modules/settings/Settings":47,"./modules/statistics/statistics":51,"./modules/translation/translation":52,"./modules/xmpp/xmpp":66}],4:[function(require,module,exports){
  349. /**
  350. * Implements API class that communicates with external api class
  351. * and provides interface to access Jitsi Meet features by external
  352. * applications that embed Jitsi Meet
  353. */
  354. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  355. /**
  356. * List of the available commands.
  357. * @type {{
  358. * displayName: inputDisplayNameHandler,
  359. * muteAudio: toggleAudio,
  360. * muteVideo: toggleVideo,
  361. * filmStrip: toggleFilmStrip
  362. * }}
  363. */
  364. var commands =
  365. {
  366. displayName: APP.UI.inputDisplayNameHandler,
  367. muteAudio: APP.UI.toggleAudio,
  368. muteVideo: APP.UI.toggleVideo,
  369. toggleFilmStrip: APP.UI.toggleFilmStrip,
  370. toggleChat: APP.UI.toggleChat,
  371. toggleContactList: APP.UI.toggleContactList
  372. };
  373. /**
  374. * Maps the supported events and their status
  375. * (true it the event is enabled and false if it is disabled)
  376. * @type {{
  377. * incomingMessage: boolean,
  378. * outgoingMessage: boolean,
  379. * displayNameChange: boolean,
  380. * participantJoined: boolean,
  381. * participantLeft: boolean
  382. * }}
  383. */
  384. var events =
  385. {
  386. incomingMessage: false,
  387. outgoingMessage:false,
  388. displayNameChange: false,
  389. participantJoined: false,
  390. participantLeft: false
  391. };
  392. var displayName = {};
  393. /**
  394. * Processes commands from external applicaiton.
  395. * @param message the object with the command
  396. */
  397. function processCommand(message)
  398. {
  399. if(message.action != "execute")
  400. {
  401. console.error("Unknown action of the message");
  402. return;
  403. }
  404. for(var key in message)
  405. {
  406. if(commands[key])
  407. commands[key].apply(null, message[key]);
  408. }
  409. }
  410. /**
  411. * Processes events objects from external applications
  412. * @param event the event
  413. */
  414. function processEvent(event) {
  415. if(!event.action)
  416. {
  417. console.error("Event with no action is received.");
  418. return;
  419. }
  420. var i = 0;
  421. switch(event.action)
  422. {
  423. case "add":
  424. for(; i < event.events.length; i++)
  425. {
  426. events[event.events[i]] = true;
  427. }
  428. break;
  429. case "remove":
  430. for(; i < event.events.length; i++)
  431. {
  432. events[event.events[i]] = false;
  433. }
  434. break;
  435. default:
  436. console.error("Unknown action for event.");
  437. }
  438. }
  439. /**
  440. * Sends message to the external application.
  441. * @param object
  442. */
  443. function sendMessage(object) {
  444. window.parent.postMessage(JSON.stringify(object), "*");
  445. }
  446. /**
  447. * Processes a message event from the external application
  448. * @param event the message event
  449. */
  450. function processMessage(event)
  451. {
  452. var message;
  453. try {
  454. message = JSON.parse(event.data);
  455. } catch (e) {}
  456. if(!message.type)
  457. return;
  458. switch (message.type)
  459. {
  460. case "command":
  461. processCommand(message);
  462. break;
  463. case "event":
  464. processEvent(message);
  465. break;
  466. default:
  467. console.error("Unknown type of the message");
  468. return;
  469. }
  470. }
  471. function setupListeners() {
  472. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  473. API.triggerEvent("participantJoined", {jid: from});
  474. });
  475. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  476. if (from != myjid)
  477. API.triggerEvent("incomingMessage",
  478. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  479. });
  480. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  481. API.triggerEvent("participantLeft", {jid: jid});
  482. });
  483. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  484. name = displayName[jid];
  485. if(!name || name != newDisplayName) {
  486. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  487. displayName[jid] = newDisplayName;
  488. }
  489. });
  490. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  491. APP.API.triggerEvent("outgoingMessage", {"message": body});
  492. });
  493. }
  494. var API = {
  495. /**
  496. * Check whether the API should be enabled or not.
  497. * @returns {boolean}
  498. */
  499. isEnabled: function () {
  500. var hash = location.hash;
  501. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  502. return true;
  503. return false;
  504. },
  505. /**
  506. * Initializes the APIConnector. Setups message event listeners that will
  507. * receive information from external applications that embed Jitsi Meet.
  508. * It also sends a message to the external application that APIConnector
  509. * is initialized.
  510. */
  511. init: function () {
  512. if (window.addEventListener)
  513. {
  514. window.addEventListener('message',
  515. processMessage, false);
  516. }
  517. else
  518. {
  519. window.attachEvent('onmessage', processMessage);
  520. }
  521. sendMessage({type: "system", loaded: true});
  522. setupListeners();
  523. },
  524. /**
  525. * Checks whether the event is enabled ot not.
  526. * @param name the name of the event.
  527. * @returns {*}
  528. */
  529. isEventEnabled: function (name) {
  530. return events[name];
  531. },
  532. /**
  533. * Sends event object to the external application that has been subscribed
  534. * for that event.
  535. * @param name the name event
  536. * @param object data associated with the event
  537. */
  538. triggerEvent: function (name, object) {
  539. if(this.isEnabled() && this.isEventEnabled(name))
  540. sendMessage({
  541. type: "event", action: "result", event: name, result: object});
  542. },
  543. /**
  544. * Removes the listeners.
  545. */
  546. dispose: function () {
  547. if(window.removeEventListener)
  548. {
  549. window.removeEventListener("message",
  550. processMessage, false);
  551. }
  552. else
  553. {
  554. window.detachEvent('onmessage', processMessage);
  555. }
  556. }
  557. };
  558. module.exports = API;
  559. },{"../../service/xmpp/XMPPEvents":109}],5:[function(require,module,exports){
  560. /* global APP */
  561. /**
  562. * A module for sending DTMF tones.
  563. */
  564. var DTMFSender;
  565. var initDtmfSender = function() {
  566. // TODO: This needs to reset this if the peerconnection changes
  567. // (e.g. the call is re-made)
  568. if (DTMFSender)
  569. return;
  570. var localAudio = APP.RTC.localAudio;
  571. if (localAudio && localAudio.getTracks().length > 0)
  572. {
  573. var peerconnection
  574. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  575. if (peerconnection) {
  576. DTMFSender =
  577. peerconnection.peerconnection
  578. .createDTMFSender(localAudio.getTracks()[0]);
  579. console.log("Initialized DTMFSender");
  580. }
  581. else {
  582. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  583. }
  584. }
  585. else {
  586. console.log("Failed to initialize DTMFSender: no audio track.");
  587. }
  588. };
  589. var DTMF = {
  590. sendTones: function (tones, duration, pause) {
  591. if (!DTMFSender)
  592. initDtmfSender();
  593. if (DTMFSender){
  594. DTMFSender.insertDTMF(tones,
  595. (duration || 200),
  596. (pause || 200));
  597. }
  598. }
  599. };
  600. module.exports = DTMF;
  601. },{}],6:[function(require,module,exports){
  602. /* global Strophe, focusedVideoSrc*/
  603. // cache datachannels to avoid garbage collection
  604. // https://code.google.com/p/chromium/issues/detail?id=405545
  605. var RTCEvents = require("../../service/RTC/RTCEvents");
  606. var _dataChannels = [];
  607. var eventEmitter = null;
  608. var DataChannels =
  609. {
  610. /**
  611. * Callback triggered by PeerConnection when new data channel is opened
  612. * on the bridge.
  613. * @param event the event info object.
  614. */
  615. onDataChannel: function (event)
  616. {
  617. var dataChannel = event.channel;
  618. dataChannel.onopen = function () {
  619. console.info("Data channel opened by the Videobridge!", dataChannel);
  620. // Code sample for sending string and/or binary data
  621. // Sends String message to the bridge
  622. //dataChannel.send("Hello bridge!");
  623. // Sends 12 bytes binary message to the bridge
  624. //dataChannel.send(new ArrayBuffer(12));
  625. // when the data channel becomes available, tell the bridge about video
  626. // selections so that it can do adaptive simulcast,
  627. // we want the notification to trigger even if userJid is undefined,
  628. // or null.
  629. var userJid = APP.UI.getLargeVideoJid();
  630. // we want the notification to trigger even if userJid is undefined,
  631. // or null.
  632. onSelectedEndpointChanged(userJid);
  633. };
  634. dataChannel.onerror = function (error) {
  635. console.error("Data Channel Error:", error, dataChannel);
  636. };
  637. dataChannel.onmessage = function (event) {
  638. var data = event.data;
  639. // JSON
  640. var obj;
  641. try {
  642. obj = JSON.parse(data);
  643. }
  644. catch (e) {
  645. console.error(
  646. "Failed to parse data channel message as JSON: ",
  647. data,
  648. dataChannel);
  649. }
  650. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  651. var colibriClass = obj.colibriClass;
  652. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  653. // Endpoint ID from the Videobridge.
  654. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  655. console.info(
  656. "Data channel new dominant speaker event: ",
  657. dominantSpeakerEndpoint);
  658. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  659. }
  660. else if ("InLastNChangeEvent" === colibriClass)
  661. {
  662. var oldValue = obj.oldValue;
  663. var newValue = obj.newValue;
  664. // Make sure that oldValue and newValue are of type boolean.
  665. var type;
  666. if ((type = typeof oldValue) !== 'boolean') {
  667. if (type === 'string') {
  668. oldValue = (oldValue == "true");
  669. } else {
  670. oldValue = new Boolean(oldValue).valueOf();
  671. }
  672. }
  673. if ((type = typeof newValue) !== 'boolean') {
  674. if (type === 'string') {
  675. newValue = (newValue == "true");
  676. } else {
  677. newValue = new Boolean(newValue).valueOf();
  678. }
  679. }
  680. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  681. }
  682. else if ("LastNEndpointsChangeEvent" === colibriClass)
  683. {
  684. // The new/latest list of last-n endpoint IDs.
  685. var lastNEndpoints = obj.lastNEndpoints;
  686. // The list of endpoint IDs which are entering the list of
  687. // last-n at this time i.e. were not in the old list of last-n
  688. // endpoint IDs.
  689. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  690. var stream = obj.stream;
  691. console.log(
  692. "Data channel new last-n event: ",
  693. lastNEndpoints, endpointsEnteringLastN, obj);
  694. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  695. lastNEndpoints, endpointsEnteringLastN, obj);
  696. }
  697. else
  698. {
  699. console.debug("Data channel JSON-formatted message: ", obj);
  700. }
  701. }
  702. };
  703. dataChannel.onclose = function ()
  704. {
  705. console.info("The Data Channel closed", dataChannel);
  706. var idx = _dataChannels.indexOf(dataChannel);
  707. if (idx > -1)
  708. _dataChannels = _dataChannels.splice(idx, 1);
  709. };
  710. _dataChannels.push(dataChannel);
  711. },
  712. /**
  713. * Binds "ondatachannel" event listener to given PeerConnection instance.
  714. * @param peerConnection WebRTC peer connection instance.
  715. */
  716. init: function (peerConnection, emitter) {
  717. if(!config.openSctp)
  718. return;
  719. peerConnection.ondatachannel = this.onDataChannel;
  720. eventEmitter = emitter;
  721. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  722. // Although it's not a requirement to open separate channels from both bridge
  723. // and peer as single channel can be used for sending and receiving data.
  724. // So either channel opened by the bridge or the one opened here is enough
  725. // for communication with the bridge.
  726. /*var dataChannelOptions =
  727. {
  728. reliable: true
  729. };
  730. var dataChannel
  731. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  732. // Can be used only when is in open state
  733. dataChannel.onopen = function ()
  734. {
  735. dataChannel.send("My channel !!!");
  736. };
  737. dataChannel.onmessage = function (event)
  738. {
  739. var msgData = event.data;
  740. console.info("Got My Data Channel Message:", msgData, dataChannel);
  741. };*/
  742. },
  743. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  744. handlePinnedEndpointEvent: onPinnedEndpointChanged
  745. };
  746. function onSelectedEndpointChanged(userResource)
  747. {
  748. console.log('selected endpoint changed: ', userResource);
  749. if (_dataChannels && _dataChannels.length != 0)
  750. {
  751. _dataChannels.some(function (dataChannel) {
  752. if (dataChannel.readyState == 'open')
  753. {
  754. console.log('sending selected endpoint changed '
  755. + 'notification to the bridge: ', userResource);
  756. dataChannel.send(JSON.stringify({
  757. 'colibriClass': 'SelectedEndpointChangedEvent',
  758. 'selectedEndpoint':
  759. (!userResource || userResource === null)?
  760. null : userResource
  761. }));
  762. return true;
  763. }
  764. });
  765. }
  766. }
  767. function onPinnedEndpointChanged(userResource)
  768. {
  769. console.log('pinned endpoint changed: ', userResource);
  770. if (_dataChannels && _dataChannels.length != 0)
  771. {
  772. _dataChannels.some(function (dataChannel) {
  773. if (dataChannel.readyState == 'open')
  774. {
  775. dataChannel.send(JSON.stringify({
  776. 'colibriClass': 'PinnedEndpointChangedEvent',
  777. 'pinnedEndpoint':
  778. (!userResource || userResource == null)?
  779. null : userResource
  780. }));
  781. return true;
  782. }
  783. });
  784. }
  785. }
  786. module.exports = DataChannels;
  787. },{"../../service/RTC/RTCEvents":100}],7:[function(require,module,exports){
  788. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  789. var RTCEvents = require("../../service/RTC/RTCEvents");
  790. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  791. {
  792. this.stream = stream;
  793. this.eventEmitter = eventEmitter;
  794. this.type = type;
  795. this.videoType = videoType;
  796. this.isGUMStream = true;
  797. if(isGUMStream === false)
  798. this.isGUMStream = isGUMStream;
  799. var self = this;
  800. if(type == "audio")
  801. {
  802. this.getTracks = function () {
  803. return self.stream.getAudioTracks();
  804. };
  805. }
  806. else
  807. {
  808. this.getTracks = function () {
  809. return self.stream.getVideoTracks();
  810. };
  811. }
  812. this.stream.onended = function()
  813. {
  814. self.streamEnded();
  815. };
  816. }
  817. LocalStream.prototype.streamEnded = function () {
  818. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  819. }
  820. LocalStream.prototype.getOriginalStream = function()
  821. {
  822. return this.stream;
  823. }
  824. LocalStream.prototype.isAudioStream = function () {
  825. return this.type === "audio";
  826. };
  827. LocalStream.prototype.setMute = function(mute)
  828. {
  829. if((window.location.protocol != "https:" && this.isGUMStream) ||
  830. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  831. {
  832. var tracks = this.getTracks();
  833. for (var idx = 0; idx < tracks.length; idx++) {
  834. tracks[idx].enabled = mute;
  835. }
  836. this.eventEmitter.emit(
  837. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  838. !mute);
  839. }
  840. else
  841. {
  842. if(mute === false) {
  843. APP.xmpp.removeStream(this.stream);
  844. this.stream.stop();
  845. this.eventEmitter.emit(
  846. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  847. true);
  848. }
  849. else
  850. {
  851. var self = this;
  852. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  853. (this.isAudioStream() ? ["audio"] : ["video"]),
  854. function (stream) {
  855. if(self.isAudioStream())
  856. {
  857. APP.RTC.changeLocalAudio(stream,
  858. function () {
  859. self.eventEmitter.emit(
  860. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  861. true);
  862. });
  863. }
  864. else
  865. {
  866. APP.RTC.changeLocalVideo(stream, false,
  867. function () {
  868. self.eventEmitter.emit(
  869. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  870. true);
  871. });
  872. }
  873. });
  874. }
  875. }
  876. };
  877. LocalStream.prototype.isMuted = function () {
  878. var tracks = [];
  879. if(this.type == "audio")
  880. {
  881. tracks = this.stream.getAudioTracks();
  882. }
  883. else
  884. {
  885. if(this.stream.ended)
  886. return true;
  887. tracks = this.stream.getVideoTracks();
  888. }
  889. for (var idx = 0; idx < tracks.length; idx++) {
  890. if(tracks[idx].enabled)
  891. return false;
  892. }
  893. return true;
  894. }
  895. LocalStream.prototype.getId = function () {
  896. return this.stream.getTracks()[0].id;
  897. }
  898. module.exports = LocalStream;
  899. },{"../../service/RTC/RTCEvents":100,"../../service/RTC/StreamEventTypes.js":102}],8:[function(require,module,exports){
  900. ////These lines should be uncommented when require works in app.js
  901. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  902. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  903. /**
  904. * Creates a MediaStream object for the given data, session id and ssrc.
  905. * It is a wrapper class for the MediaStream.
  906. *
  907. * @param data the data object from which we obtain the stream,
  908. * the peerjid, etc.
  909. * @param sid the session id
  910. * @param ssrc the ssrc corresponding to this MediaStream
  911. *
  912. * @constructor
  913. */
  914. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  915. // XXX(gp) to minimize headaches in the future, we should build our
  916. // abstractions around tracks and not streams. ORTC is track based API.
  917. // Mozilla expects m-lines to represent media tracks.
  918. //
  919. // Practically, what I'm saying is that we should have a MediaTrack class
  920. // and not a MediaStream class.
  921. //
  922. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  923. // a track might have an associated RTX and FEC sources.
  924. this.sid = sid;
  925. this.stream = data.stream;
  926. this.peerjid = data.peerjid;
  927. this.ssrc = ssrc;
  928. this.type = (this.stream.getVideoTracks().length > 0)?
  929. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  930. this.videoType = null;
  931. this.muted = false;
  932. this.eventEmitter = eventEmitter;
  933. }
  934. MediaStream.prototype.getOriginalStream = function()
  935. {
  936. return this.stream;
  937. };
  938. MediaStream.prototype.setMute = function (value)
  939. {
  940. this.stream.muted = value;
  941. this.muted = value;
  942. };
  943. MediaStream.prototype.setVideoType = function (value) {
  944. if(this.videoType === value)
  945. return;
  946. this.videoType = value;
  947. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  948. this.peerjid);
  949. };
  950. module.exports = MediaStream;
  951. },{"../../service/RTC/MediaStreamTypes":98,"../../service/RTC/StreamEventTypes":102}],9:[function(require,module,exports){
  952. var EventEmitter = require("events");
  953. var RTCUtils = require("./RTCUtils.js");
  954. var LocalStream = require("./LocalStream.js");
  955. var DataChannels = require("./DataChannels");
  956. var MediaStream = require("./MediaStream.js");
  957. var DesktopSharingEventTypes
  958. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  959. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  960. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  961. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  962. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  963. var UIEvents = require("../../service/UI/UIEvents");
  964. var eventEmitter = new EventEmitter();
  965. function getMediaStreamUsage()
  966. {
  967. var result = {
  968. audio: true,
  969. video: true
  970. };
  971. /** There are some issues with the desktop sharing
  972. * when this property is enabled.
  973. * WARNING: We must change the implementation to start video/audio if we
  974. * receive from the focus that the peer is not muted.
  975. var isSecureConnection = window.location.protocol == "https:";
  976. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  977. {
  978. result = {
  979. audio: false,
  980. video: false
  981. };
  982. }
  983. **/
  984. return result;
  985. }
  986. var RTC = {
  987. rtcUtils: null,
  988. devices: {
  989. audio: true,
  990. video: true
  991. },
  992. localStreams: [],
  993. remoteStreams: {},
  994. localAudio: null,
  995. localVideo: null,
  996. addStreamListener: function (listener, eventType) {
  997. eventEmitter.on(eventType, listener);
  998. },
  999. addListener: function (type, listener) {
  1000. eventEmitter.on(type, listener);
  1001. },
  1002. removeStreamListener: function (listener, eventType) {
  1003. if(!(eventType instanceof StreamEventTypes))
  1004. throw "Illegal argument";
  1005. eventEmitter.removeListener(eventType, listener);
  1006. },
  1007. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  1008. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  1009. //in firefox we have only one stream object
  1010. if(this.localStreams.length == 0 ||
  1011. this.localStreams[0].getOriginalStream() != stream)
  1012. this.localStreams.push(localStream);
  1013. if(isMuted === true)
  1014. localStream.setMute(false);
  1015. if(type == "audio")
  1016. {
  1017. this.localAudio = localStream;
  1018. }
  1019. else
  1020. {
  1021. this.localVideo = localStream;
  1022. }
  1023. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1024. if(change)
  1025. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1026. eventEmitter.emit(eventType, localStream, isMuted);
  1027. return localStream;
  1028. },
  1029. removeLocalStream: function (stream) {
  1030. for(var i = 0; i < this.localStreams.length; i++)
  1031. {
  1032. if(this.localStreams[i].getOriginalStream() === stream) {
  1033. delete this.localStreams[i];
  1034. return;
  1035. }
  1036. }
  1037. },
  1038. createRemoteStream: function (data, sid, thessrc) {
  1039. var remoteStream = new MediaStream(data, sid, thessrc,
  1040. this.getBrowserType(), eventEmitter);
  1041. var jid = data.peerjid || APP.xmpp.myJid();
  1042. if(!this.remoteStreams[jid]) {
  1043. this.remoteStreams[jid] = {};
  1044. }
  1045. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1046. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1047. return remoteStream;
  1048. },
  1049. getBrowserType: function () {
  1050. return this.rtcUtils.browser;
  1051. },
  1052. getPCConstraints: function () {
  1053. return this.rtcUtils.pc_constraints;
  1054. },
  1055. getUserMediaWithConstraints:function(um, success_callback,
  1056. failure_callback, resolution,
  1057. bandwidth, fps, desktopStream)
  1058. {
  1059. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  1060. failure_callback, resolution, bandwidth, fps, desktopStream);
  1061. },
  1062. attachMediaStream: function (element, stream) {
  1063. this.rtcUtils.attachMediaStream(element, stream);
  1064. },
  1065. getStreamID: function (stream) {
  1066. return this.rtcUtils.getStreamID(stream);
  1067. },
  1068. getVideoSrc: function (element) {
  1069. return this.rtcUtils.getVideoSrc(element);
  1070. },
  1071. setVideoSrc: function (element, src) {
  1072. this.rtcUtils.setVideoSrc(element, src);
  1073. },
  1074. dispose: function() {
  1075. if (this.rtcUtils) {
  1076. this.rtcUtils = null;
  1077. }
  1078. },
  1079. stop: function () {
  1080. this.dispose();
  1081. },
  1082. start: function () {
  1083. var self = this;
  1084. APP.desktopsharing.addListener(
  1085. function (stream, isUsingScreenStream, callback) {
  1086. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1087. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1088. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  1089. for(var i = 0; i < changedStreams.length; i++) {
  1090. var type = changedStreams[i].type;
  1091. if (type != "audio") {
  1092. var peerStreams = self.remoteStreams[jid];
  1093. if(!peerStreams)
  1094. continue;
  1095. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  1096. if(!videoStream)
  1097. continue;
  1098. videoStream.setVideoType(changedStreams[i].type);
  1099. }
  1100. }
  1101. });
  1102. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  1103. DataChannels.init(event.peerconnection, eventEmitter);
  1104. });
  1105. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  1106. DataChannels.handleSelectedEndpointEvent);
  1107. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1108. DataChannels.handlePinnedEndpointEvent);
  1109. this.rtcUtils = new RTCUtils(this);
  1110. this.rtcUtils.obtainAudioAndVideoPermissions(
  1111. null, null, getMediaStreamUsage());
  1112. },
  1113. muteRemoteVideoStream: function (jid, value) {
  1114. var stream;
  1115. if(this.remoteStreams[jid] &&
  1116. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  1117. {
  1118. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1119. }
  1120. if(!stream)
  1121. return true;
  1122. if (value != stream.muted) {
  1123. stream.setMute(value);
  1124. return true;
  1125. }
  1126. return false;
  1127. },
  1128. switchVideoStreams: function (new_stream) {
  1129. this.localVideo.stream = new_stream;
  1130. this.localStreams = [];
  1131. //in firefox we have only one stream object
  1132. if (this.localAudio.getOriginalStream() != new_stream)
  1133. this.localStreams.push(this.localAudio);
  1134. this.localStreams.push(this.localVideo);
  1135. },
  1136. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  1137. var oldStream = this.localVideo.getOriginalStream();
  1138. var type = (isUsingScreenStream? "screen" : "video");
  1139. var localCallback = callback;
  1140. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  1141. {
  1142. localCallback = function() {
  1143. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  1144. callback();
  1145. };
  1146. }
  1147. var videoStream = this.rtcUtils.createStream(stream, true);
  1148. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1149. // Stop the stream to trigger onended event for old stream
  1150. oldStream.stop();
  1151. this.switchVideoStreams(videoStream, oldStream);
  1152. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  1153. },
  1154. changeLocalAudio: function (stream, callback) {
  1155. var oldStream = this.localAudio.getOriginalStream();
  1156. var newStream = this.rtcUtils.createStream(stream);
  1157. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1158. // Stop the stream to trigger onended event for old stream
  1159. oldStream.stop();
  1160. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  1161. },
  1162. isVideoMuted: function (jid) {
  1163. if (jid === APP.xmpp.myJid()) {
  1164. var localVideo = APP.RTC.localVideo;
  1165. return (!localVideo || localVideo.isMuted());
  1166. }
  1167. else
  1168. {
  1169. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1170. return null;
  1171. }
  1172. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1173. }
  1174. },
  1175. /**
  1176. * Checks if video identified by given src is desktop stream.
  1177. * @param videoSrc eg.
  1178. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  1179. * @returns {boolean}
  1180. */
  1181. isVideoSrcDesktop: function (jid) {
  1182. if(!jid)
  1183. return false;
  1184. var isDesktop = false;
  1185. var stream = null;
  1186. if (APP.xmpp.myJid() === jid) {
  1187. // local video
  1188. stream = this.localVideo;
  1189. } else {
  1190. var peerStreams = this.remoteStreams[jid];
  1191. if(!peerStreams)
  1192. return false;
  1193. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  1194. }
  1195. if(stream)
  1196. isDesktop = (stream.videoType === "screen");
  1197. return isDesktop;
  1198. },
  1199. setVideoMute: function(mute, callback, options) {
  1200. if(!this.localVideo)
  1201. return;
  1202. if (mute == APP.RTC.localVideo.isMuted())
  1203. {
  1204. APP.xmpp.sendVideoInfoPresence(mute);
  1205. if(callback)
  1206. callback(mute);
  1207. }
  1208. else
  1209. {
  1210. APP.RTC.localVideo.setMute(!mute);
  1211. APP.xmpp.setVideoMute(
  1212. mute,
  1213. callback,
  1214. options);
  1215. }
  1216. },
  1217. setDeviceAvailability: function (devices) {
  1218. if(!devices)
  1219. return;
  1220. if(devices.audio === true || devices.audio === false)
  1221. this.devices.audio = devices.audio;
  1222. if(devices.video === true || devices.video === false)
  1223. this.devices.video = devices.video;
  1224. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1225. }
  1226. };
  1227. module.exports = RTC;
  1228. },{"../../service/RTC/MediaStreamTypes":98,"../../service/RTC/RTCEvents.js":100,"../../service/RTC/StreamEventTypes.js":102,"../../service/UI/UIEvents":103,"../../service/desktopsharing/DesktopSharingEventTypes":106,"../../service/xmpp/XMPPEvents":109,"./DataChannels":6,"./LocalStream.js":7,"./MediaStream.js":8,"./RTCUtils.js":10,"events":1}],10:[function(require,module,exports){
  1229. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  1230. var Resolutions = require("../../service/RTC/Resolutions");
  1231. var currentResolution = null;
  1232. function getPreviousResolution(resolution) {
  1233. if(!Resolutions[resolution])
  1234. return null;
  1235. var order = Resolutions[resolution].order;
  1236. var res = null;
  1237. var resName = null;
  1238. for(var i in Resolutions)
  1239. {
  1240. var tmp = Resolutions[i];
  1241. if(res == null || (res.order < tmp.order && tmp.order < order))
  1242. {
  1243. resName = i;
  1244. res = tmp;
  1245. }
  1246. }
  1247. return resName;
  1248. }
  1249. function setResolutionConstraints(constraints, resolution, isAndroid)
  1250. {
  1251. if (resolution && !constraints.video || isAndroid) {
  1252. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1253. }
  1254. if(Resolutions[resolution])
  1255. {
  1256. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1257. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1258. }
  1259. else
  1260. {
  1261. if (isAndroid) {
  1262. constraints.video.mandatory.minWidth = 320;
  1263. constraints.video.mandatory.minHeight = 240;
  1264. constraints.video.mandatory.maxFrameRate = 15;
  1265. }
  1266. }
  1267. if (constraints.video.mandatory.minWidth)
  1268. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1269. if (constraints.video.mandatory.minHeight)
  1270. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1271. }
  1272. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1273. {
  1274. var constraints = {audio: false, video: false};
  1275. if (um.indexOf('video') >= 0) {
  1276. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1277. }
  1278. if (um.indexOf('audio') >= 0) {
  1279. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1280. }
  1281. if (um.indexOf('screen') >= 0) {
  1282. constraints.video = {
  1283. mandatory: {
  1284. chromeMediaSource: "screen",
  1285. googLeakyBucket: true,
  1286. maxWidth: window.screen.width,
  1287. maxHeight: window.screen.height,
  1288. maxFrameRate: 3
  1289. },
  1290. optional: []
  1291. };
  1292. }
  1293. if (um.indexOf('desktop') >= 0) {
  1294. constraints.video = {
  1295. mandatory: {
  1296. chromeMediaSource: "desktop",
  1297. chromeMediaSourceId: desktopStream,
  1298. googLeakyBucket: true,
  1299. maxWidth: window.screen.width,
  1300. maxHeight: window.screen.height,
  1301. maxFrameRate: 3
  1302. },
  1303. optional: []
  1304. };
  1305. }
  1306. if (constraints.audio) {
  1307. // if it is good enough for hangouts...
  1308. constraints.audio.optional.push(
  1309. {googEchoCancellation: true},
  1310. {googAutoGainControl: true},
  1311. {googNoiseSupression: true},
  1312. {googHighpassFilter: true},
  1313. {googNoisesuppression2: true},
  1314. {googEchoCancellation2: true},
  1315. {googAutoGainControl2: true}
  1316. );
  1317. }
  1318. if (constraints.video) {
  1319. constraints.video.optional.push(
  1320. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1321. );
  1322. if (um.indexOf('video') >= 0) {
  1323. constraints.video.optional.push(
  1324. {googLeakyBucket: true}
  1325. );
  1326. }
  1327. }
  1328. if (um.indexOf('video') >= 0) {
  1329. setResolutionConstraints(constraints, resolution, isAndroid);
  1330. }
  1331. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1332. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1333. constraints.video.optional.push({bandwidth: bandwidth});
  1334. }
  1335. if (fps) { // for some cameras it might be necessary to request 30fps
  1336. // so they choose 30fps mjpg over 10fps yuy2
  1337. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1338. constraints.video.mandatory.minFrameRate = fps;
  1339. }
  1340. return constraints;
  1341. }
  1342. function RTCUtils(RTCService)
  1343. {
  1344. this.service = RTCService;
  1345. if (navigator.mozGetUserMedia) {
  1346. console.log('This appears to be Firefox');
  1347. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1348. if (version >= 40
  1349. && config.useBundle && config.useRtcpMux) {
  1350. this.peerconnection = mozRTCPeerConnection;
  1351. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1352. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1353. this.pc_constraints = {};
  1354. this.attachMediaStream = function (element, stream) {
  1355. // srcObject is being standardized and FF will eventually
  1356. // support that unprefixed. FF also supports the
  1357. // "element.src = URL.createObjectURL(...)" combo, but that
  1358. // will be deprecated in favour of srcObject.
  1359. //
  1360. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1361. // https://github.com/webrtc/samples/issues/302
  1362. if(!element[0])
  1363. return;
  1364. element[0].mozSrcObject = stream;
  1365. element[0].play();
  1366. };
  1367. this.getStreamID = function (stream) {
  1368. var tracks = stream.getVideoTracks();
  1369. if(!tracks || tracks.length == 0)
  1370. {
  1371. tracks = stream.getAudioTracks();
  1372. }
  1373. return tracks[0].id.replace(/[\{,\}]/g,"");
  1374. };
  1375. this.getVideoSrc = function (element) {
  1376. if(!element)
  1377. return null;
  1378. return element.mozSrcObject;
  1379. };
  1380. this.setVideoSrc = function (element, src) {
  1381. if(element)
  1382. element.mozSrcObject = src;
  1383. };
  1384. RTCSessionDescription = mozRTCSessionDescription;
  1385. RTCIceCandidate = mozRTCIceCandidate;
  1386. } else {
  1387. window.location.href = 'unsupported_browser.html';
  1388. return;
  1389. }
  1390. } else if (navigator.webkitGetUserMedia) {
  1391. console.log('This appears to be Chrome');
  1392. this.peerconnection = webkitRTCPeerConnection;
  1393. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1394. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1395. this.attachMediaStream = function (element, stream) {
  1396. element.attr('src', webkitURL.createObjectURL(stream));
  1397. };
  1398. this.getStreamID = function (stream) {
  1399. // streams from FF endpoints have the characters '{' and '}'
  1400. // that make jQuery choke.
  1401. return stream.id.replace(/[\{,\}]/g,"");
  1402. };
  1403. this.getVideoSrc = function (element) {
  1404. if(!element)
  1405. return null;
  1406. return element.getAttribute("src");
  1407. };
  1408. this.setVideoSrc = function (element, src) {
  1409. if(element)
  1410. element.setAttribute("src", src);
  1411. };
  1412. // DTLS should now be enabled by default but..
  1413. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1414. if (navigator.userAgent.indexOf('Android') != -1) {
  1415. this.pc_constraints = {}; // disable DTLS on Android
  1416. }
  1417. if (!webkitMediaStream.prototype.getVideoTracks) {
  1418. webkitMediaStream.prototype.getVideoTracks = function () {
  1419. return this.videoTracks;
  1420. };
  1421. }
  1422. if (!webkitMediaStream.prototype.getAudioTracks) {
  1423. webkitMediaStream.prototype.getAudioTracks = function () {
  1424. return this.audioTracks;
  1425. };
  1426. }
  1427. }
  1428. else
  1429. {
  1430. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1431. window.location.href = 'unsupported_browser.html';
  1432. return;
  1433. }
  1434. }
  1435. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1436. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1437. desktopStream)
  1438. {
  1439. currentResolution = resolution;
  1440. // Check if we are running on Android device
  1441. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1442. var constraints = getConstraints(
  1443. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1444. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1445. var self = this;
  1446. try {
  1447. this.getUserMedia(constraints,
  1448. function (stream) {
  1449. console.log('onUserMediaSuccess');
  1450. self.setAvailableDevices(um, true);
  1451. success_callback(stream);
  1452. },
  1453. function (error) {
  1454. self.setAvailableDevices(um, false);
  1455. console.warn('Failed to get access to local media. Error ',
  1456. error, constraints);
  1457. if (failure_callback) {
  1458. failure_callback(error);
  1459. }
  1460. });
  1461. } catch (e) {
  1462. console.error('GUM failed: ', e);
  1463. if(failure_callback) {
  1464. failure_callback(e);
  1465. }
  1466. }
  1467. };
  1468. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1469. var devices = {};
  1470. if(um.indexOf("video") != -1)
  1471. {
  1472. devices.video = available;
  1473. }
  1474. if(um.indexOf("audio") != -1)
  1475. {
  1476. devices.audio = available;
  1477. }
  1478. this.service.setDeviceAvailability(devices);
  1479. }
  1480. /**
  1481. * We ask for audio and video combined stream in order to get permissions and
  1482. * not to ask twice.
  1483. */
  1484. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1485. function(devices, callback, usageOptions)
  1486. {
  1487. var self = this;
  1488. // Get AV
  1489. var successCallback = function (stream) {
  1490. if(callback)
  1491. callback(stream, usageOptions);
  1492. else
  1493. self.successCallback(stream, usageOptions);
  1494. };
  1495. if(!devices)
  1496. devices = ['audio', 'video'];
  1497. var newDevices = [];
  1498. if(usageOptions)
  1499. for(var i = 0; i < devices.length; i++)
  1500. {
  1501. var device = devices[i];
  1502. if(usageOptions[device] === true)
  1503. newDevices.push(device);
  1504. }
  1505. else
  1506. newDevices = devices;
  1507. if(newDevices.length === 0)
  1508. {
  1509. successCallback();
  1510. return;
  1511. }
  1512. if (navigator.mozGetUserMedia) {
  1513. // With FF we can't split the stream into audio and video because FF
  1514. // doesn't support media stream constructors. So, we need to get the
  1515. // audio stream separately from the video stream using two distinct GUM
  1516. // calls. Not very user friendly :-( but we don't have many other
  1517. // options neither.
  1518. //
  1519. // Note that we pack those 2 streams in a single object and pass it to
  1520. // the successCallback method.
  1521. self.getUserMediaWithConstraints(
  1522. ['audio'],
  1523. function (audioStream) {
  1524. self.getUserMediaWithConstraints(
  1525. ['video'],
  1526. function (videoStream) {
  1527. return self.successCallback({
  1528. audioStream: audioStream,
  1529. videoStream: videoStream
  1530. });
  1531. },
  1532. function (error) {
  1533. console.error('failed to obtain video stream - stop',
  1534. error);
  1535. return self.successCallback(null);
  1536. },
  1537. config.resolution || '360');
  1538. },
  1539. function (error) {
  1540. console.error('failed to obtain audio stream - stop',
  1541. error);
  1542. return self.successCallback(null);
  1543. }
  1544. );
  1545. } else {
  1546. this.getUserMediaWithConstraints(
  1547. newDevices,
  1548. function (stream) {
  1549. successCallback(stream);
  1550. },
  1551. function (error) {
  1552. self.errorCallback(error);
  1553. },
  1554. config.resolution || '360');
  1555. }
  1556. }
  1557. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1558. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1559. // an object with two properties: audioStream, videoStream.
  1560. if(stream && !navigator.mozGetUserMedia)
  1561. console.log('got', stream, stream.getAudioTracks().length,
  1562. stream.getVideoTracks().length);
  1563. this.handleLocalStream(stream, usageOptions);
  1564. };
  1565. RTCUtils.prototype.errorCallback = function (error) {
  1566. var self = this;
  1567. console.error('failed to obtain audio/video stream - trying audio only', error);
  1568. var resolution = getPreviousResolution(currentResolution);
  1569. if(typeof error == "object" && error.constraintName && error.name
  1570. && (error.name == "ConstraintNotSatisfiedError" ||
  1571. error.name == "OverconstrainedError") &&
  1572. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1573. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1574. && resolution != null)
  1575. {
  1576. self.getUserMediaWithConstraints(['audio', 'video'],
  1577. function (stream) {
  1578. return self.successCallback(stream);
  1579. }, function (error) {
  1580. return self.errorCallback(error);
  1581. }, resolution);
  1582. }
  1583. else
  1584. {
  1585. self.getUserMediaWithConstraints(
  1586. ['audio'],
  1587. function (stream) {
  1588. return self.successCallback(stream);
  1589. },
  1590. function (error) {
  1591. console.error('failed to obtain audio/video stream - stop',
  1592. error);
  1593. return self.successCallback(null);
  1594. }
  1595. );
  1596. }
  1597. }
  1598. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1599. {
  1600. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1601. // an object with two properties: audioStream, videoStream.
  1602. var audioStream, videoStream;
  1603. if(window.webkitMediaStream)
  1604. {
  1605. audioStream = new webkitMediaStream();
  1606. videoStream = new webkitMediaStream();
  1607. if(stream) {
  1608. var audioTracks = stream.getAudioTracks();
  1609. for (var i = 0; i < audioTracks.length; i++) {
  1610. audioStream.addTrack(audioTracks[i]);
  1611. }
  1612. var videoTracks = stream.getVideoTracks();
  1613. for (i = 0; i < videoTracks.length; i++) {
  1614. videoStream.addTrack(videoTracks[i]);
  1615. }
  1616. }
  1617. }
  1618. else
  1619. {//firefox
  1620. audioStream = stream.audioStream;
  1621. videoStream = stream.videoStream;
  1622. }
  1623. var audioMuted = (usageOptions && usageOptions.audio === false),
  1624. videoMuted = (usageOptions && usageOptions.video === false);
  1625. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1626. videoGUM = (!usageOptions || usageOptions.video !== false);
  1627. this.service.createLocalStream(audioStream, "audio", null, null,
  1628. audioMuted, audioGUM);
  1629. this.service.createLocalStream(videoStream, "video", null, null,
  1630. videoMuted, videoGUM);
  1631. };
  1632. RTCUtils.prototype.createStream = function(stream, isVideo)
  1633. {
  1634. var newStream = null;
  1635. if(window.webkitMediaStream)
  1636. {
  1637. newStream = new webkitMediaStream();
  1638. if(newStream)
  1639. {
  1640. var tracks = (isVideo? stream.getVideoTracks() : stream.getAudioTracks());
  1641. for (i = 0; i < tracks.length; i++) {
  1642. newStream.addTrack(tracks[i]);
  1643. }
  1644. }
  1645. }
  1646. else
  1647. newStream = stream;
  1648. return newStream;
  1649. };
  1650. module.exports = RTCUtils;
  1651. },{"../../service/RTC/RTCBrowserType.js":99,"../../service/RTC/Resolutions":101}],11:[function(require,module,exports){
  1652. var UI = {};
  1653. var VideoLayout = require("./videolayout/VideoLayout.js");
  1654. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1655. var Prezi = require("./prezi/Prezi.js");
  1656. var Etherpad = require("./etherpad/Etherpad.js");
  1657. var Chat = require("./side_pannels/chat/Chat.js");
  1658. var Toolbar = require("./toolbars/Toolbar");
  1659. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1660. var BottomToolbar = require("./toolbars/BottomToolbar");
  1661. var ContactList = require("./side_pannels/contactlist/ContactList");
  1662. var Avatar = require("./avatar/Avatar");
  1663. var EventEmitter = require("events");
  1664. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1665. var Settings = require("./../settings/Settings");
  1666. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1667. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1668. UI.messageHandler = require("./util/MessageHandler");
  1669. var messageHandler = UI.messageHandler;
  1670. var Authentication = require("./authentication/Authentication");
  1671. var UIUtil = require("./util/UIUtil");
  1672. var NicknameHandler = require("./util/NicknameHandler");
  1673. var CQEvents = require("../../service/connectionquality/CQEvents");
  1674. var DesktopSharingEventTypes
  1675. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1676. var RTCEvents = require("../../service/RTC/RTCEvents");
  1677. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1678. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1679. var MemberEvents = require("../../service/members/Events");
  1680. var eventEmitter = new EventEmitter();
  1681. var roomName = null;
  1682. function promptDisplayName() {
  1683. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  1684. message += APP.translation.translateString(
  1685. "dialog.displayNameRequired");
  1686. message += '</h2>' +
  1687. '<input name="displayName" type="text" data-i18n=' +
  1688. '"[placeholder]defaultNickname" placeholder="' +
  1689. APP.translation.translateString(
  1690. "defaultNickname", {name: "Jane Pink"}) +
  1691. '" autofocus>';
  1692. var buttonTxt
  1693. = APP.translation.generateTranslationHTML("dialog.Ok");
  1694. var buttons = [];
  1695. buttons.push({title: buttonTxt, value: "ok"});
  1696. messageHandler.openDialog(null, message,
  1697. true,
  1698. buttons,
  1699. function (e, v, m, f) {
  1700. if (v == "ok") {
  1701. var displayName = f.displayName;
  1702. if (displayName) {
  1703. VideoLayout.inputDisplayNameHandler(displayName);
  1704. return true;
  1705. }
  1706. }
  1707. e.preventDefault();
  1708. },
  1709. function () {
  1710. var form = $.prompt.getPrompt();
  1711. var input = form.find("input[name='displayName']");
  1712. var button = form.find("button");
  1713. button.attr("disabled", "disabled");
  1714. input.keyup(function () {
  1715. if(!input.val())
  1716. button.attr("disabled", "disabled");
  1717. else
  1718. button.removeAttr("disabled");
  1719. });
  1720. }
  1721. );
  1722. }
  1723. function notifyForInitialMute()
  1724. {
  1725. messageHandler.notify(null, "notify.mutedTitle", "connected",
  1726. "notify.muted", null, {timeOut: 120000});
  1727. }
  1728. function setupPrezi()
  1729. {
  1730. $("#reloadPresentationLink").click(function()
  1731. {
  1732. Prezi.reloadPresentation();
  1733. });
  1734. }
  1735. function setupChat()
  1736. {
  1737. Chat.init();
  1738. $("#toggle_smileys").click(function() {
  1739. Chat.toggleSmileys();
  1740. });
  1741. }
  1742. function setupToolbars() {
  1743. Toolbar.init(UI);
  1744. Toolbar.setupButtonsFromConfig();
  1745. BottomToolbar.init();
  1746. }
  1747. function streamHandler(stream, isMuted) {
  1748. switch (stream.type)
  1749. {
  1750. case "audio":
  1751. VideoLayout.changeLocalAudio(stream, isMuted);
  1752. break;
  1753. case "video":
  1754. VideoLayout.changeLocalVideo(stream, isMuted);
  1755. break;
  1756. case "stream":
  1757. VideoLayout.changeLocalStream(stream, isMuted);
  1758. break;
  1759. }
  1760. }
  1761. function onXmppConnectionFailed(stropheErrorMsg) {
  1762. var title = APP.translation.generateTranslationHTML(
  1763. "dialog.error");
  1764. var message;
  1765. if (stropheErrorMsg) {
  1766. message = APP.translation.generateTranslationHTML(
  1767. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  1768. } else {
  1769. message = APP.translation.generateTranslationHTML(
  1770. "dialog.connectError");
  1771. }
  1772. messageHandler.openDialog(
  1773. title, message, true, {}, function (e, v, m, f) { return false; });
  1774. }
  1775. function onDisposeConference(unload) {
  1776. Toolbar.showAuthenticateButton(false);
  1777. }
  1778. function onDisplayNameChanged(jid, displayName) {
  1779. ContactList.onDisplayNameChange(jid, displayName);
  1780. SettingsMenu.onDisplayNameChange(jid, displayName);
  1781. VideoLayout.onDisplayNameChanged(jid, displayName);
  1782. }
  1783. function registerListeners() {
  1784. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1785. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1786. APP.RTC.addStreamListener(function (stream) {
  1787. VideoLayout.onRemoteStreamAdded(stream);
  1788. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1789. APP.RTC.addStreamListener(function (jid) {
  1790. VideoLayout.onVideoTypeChanged(jid);
  1791. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1792. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1793. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1794. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1795. });
  1796. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1797. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1798. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1799. endpointsEnteringLastN, stream);
  1800. });
  1801. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1802. function (devices) {
  1803. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1804. })
  1805. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1806. {
  1807. var resourceJid;
  1808. if(jid === APP.statistics.LOCAL_JID)
  1809. {
  1810. resourceJid = AudioLevels.LOCAL_LEVEL;
  1811. if(APP.RTC.localAudio.isMuted())
  1812. {
  1813. audioLevel = 0;
  1814. }
  1815. }
  1816. else
  1817. {
  1818. resourceJid = Strophe.getResourceFromJid(jid);
  1819. }
  1820. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1821. UI.getLargeVideoJid());
  1822. });
  1823. APP.desktopsharing.addListener(function () {
  1824. ToolbarToggler.showDesktopSharingButton();
  1825. }, DesktopSharingEventTypes.INIT);
  1826. APP.desktopsharing.addListener(
  1827. Toolbar.changeDesktopSharingButtonState,
  1828. DesktopSharingEventTypes.SWITCHING_DONE);
  1829. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1830. VideoLayout.updateLocalConnectionStats);
  1831. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1832. VideoLayout.updateConnectionStats);
  1833. APP.connectionquality.addListener(CQEvents.STOP,
  1834. VideoLayout.onStatsStop);
  1835. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  1836. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1837. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1838. messageHandler.openMessageDialog(
  1839. 'dialog.serviceUnavailable',
  1840. 'dialog.gracefulShutdown'
  1841. );
  1842. });
  1843. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1844. var title = APP.translation.generateTranslationHTML(
  1845. "dialog.reservationError");
  1846. var message = APP.translation.generateTranslationHTML(
  1847. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1848. messageHandler.openDialog(
  1849. title,
  1850. message,
  1851. true, {},
  1852. function (event, value, message, formVals)
  1853. {
  1854. return false;
  1855. }
  1856. );
  1857. });
  1858. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1859. messageHandler.openMessageDialog("dialog.sessTerminated",
  1860. "dialog.kickMessage");
  1861. });
  1862. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1863. //FIXME: use Session Terminated from translation, but
  1864. // 'reason' text comes from XMPP packet and is not translated
  1865. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  1866. messageHandler.openDialog(
  1867. title, reason, true, {},
  1868. function (event, value, message, formVals)
  1869. {
  1870. return false;
  1871. }
  1872. );
  1873. });
  1874. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1875. messageHandler.showError("dialog.error",
  1876. "dialog.bridgeUnavailable");
  1877. });
  1878. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1879. Avatar.setUserAvatar(from, id);
  1880. });
  1881. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  1882. for(stream in changedStreams)
  1883. {
  1884. // might need to update the direction if participant just went from sendrecv to recvonly
  1885. if (stream.type === 'video' || stream.type === 'screen') {
  1886. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1887. switch (stream.direction) {
  1888. case 'sendrecv':
  1889. el.show();
  1890. break;
  1891. case 'recvonly':
  1892. el.hide();
  1893. break;
  1894. }
  1895. }
  1896. }
  1897. });
  1898. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1899. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1900. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  1901. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  1902. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1903. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1904. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1905. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1906. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  1907. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  1908. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1909. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1910. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1911. onAuthenticationRequired);
  1912. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1913. function (resource, devices) {
  1914. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1915. });
  1916. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  1917. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  1918. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  1919. onDtmfSupportChanged);
  1920. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  1921. SettingsMenu.setStartMuted(audio, video);
  1922. });
  1923. }
  1924. /**
  1925. * Mutes/unmutes the local video.
  1926. *
  1927. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1928. * @param options an object which specifies optional arguments such as the
  1929. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1930. * specifies whether the method was initiated in response to a user command (in
  1931. * contrast to an automatic decision taken by the application logic)
  1932. */
  1933. function setVideoMute(mute, options) {
  1934. APP.RTC.setVideoMute(mute,
  1935. UI.setVideoMuteButtonsState,
  1936. options);
  1937. }
  1938. function onResize()
  1939. {
  1940. Chat.resizeChat();
  1941. VideoLayout.resizeLargeVideoContainer();
  1942. }
  1943. function bindEvents()
  1944. {
  1945. /**
  1946. * Resizes and repositions videos in full screen mode.
  1947. */
  1948. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1949. onResize);
  1950. $(window).resize(onResize);
  1951. }
  1952. UI.start = function (init) {
  1953. document.title = interfaceConfig.APP_NAME;
  1954. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1955. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1956. {
  1957. $("#videoconference_page").hide();
  1958. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1959. setupWelcomePage();
  1960. return;
  1961. }
  1962. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1963. var leftWatermarkDiv
  1964. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1965. leftWatermarkDiv.css({display: 'block'});
  1966. leftWatermarkDiv.parent().get(0).href
  1967. = interfaceConfig.JITSI_WATERMARK_LINK;
  1968. }
  1969. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1970. var rightWatermarkDiv
  1971. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1972. rightWatermarkDiv.css({display: 'block'});
  1973. rightWatermarkDiv.parent().get(0).href
  1974. = interfaceConfig.BRAND_WATERMARK_LINK;
  1975. rightWatermarkDiv.get(0).style.backgroundImage
  1976. = "url(images/rightwatermark.png)";
  1977. }
  1978. if (interfaceConfig.SHOW_POWERED_BY) {
  1979. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1980. }
  1981. $("#welcome_page").hide();
  1982. $("#videospace").mousemove(function () {
  1983. return ToolbarToggler.showToolbar();
  1984. });
  1985. // Set the defaults for prompt dialogs.
  1986. jQuery.prompt.setDefaults({persistent: false});
  1987. VideoLayout.init(eventEmitter);
  1988. AudioLevels.init();
  1989. NicknameHandler.init(eventEmitter);
  1990. registerListeners();
  1991. bindEvents();
  1992. setupPrezi();
  1993. setupToolbars();
  1994. setupChat();
  1995. document.title = interfaceConfig.APP_NAME;
  1996. $("#downloadlog").click(function (event) {
  1997. dump(event.target);
  1998. });
  1999. if(config.enableWelcomePage && window.location.pathname == "/" &&
  2000. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  2001. {
  2002. $("#videoconference_page").hide();
  2003. var setupWelcomePage = require("./welcome_page/WelcomePage");
  2004. setupWelcomePage();
  2005. return;
  2006. }
  2007. $("#welcome_page").hide();
  2008. // Display notice message at the top of the toolbar
  2009. if (config.noticeMessage) {
  2010. $('#noticeText').text(config.noticeMessage);
  2011. $('#notice').css({display: 'block'});
  2012. }
  2013. document.getElementById('largeVideo').volume = 0;
  2014. if(config.requireDisplayName) {
  2015. var currentSettings = Settings.getSettings();
  2016. if (!currentSettings.displayName) {
  2017. promptDisplayName();
  2018. }
  2019. }
  2020. init();
  2021. toastr.options = {
  2022. "closeButton": true,
  2023. "debug": false,
  2024. "positionClass": "notification-bottom-right",
  2025. "onclick": null,
  2026. "showDuration": "300",
  2027. "hideDuration": "1000",
  2028. "timeOut": "2000",
  2029. "extendedTimeOut": "1000",
  2030. "showEasing": "swing",
  2031. "hideEasing": "linear",
  2032. "showMethod": "fadeIn",
  2033. "hideMethod": "fadeOut",
  2034. "reposition": function() {
  2035. if(PanelToggler.isVisible()) {
  2036. $("#toast-container").addClass("notification-bottom-right-center");
  2037. } else {
  2038. $("#toast-container").removeClass("notification-bottom-right-center");
  2039. }
  2040. },
  2041. "newestOnTop": false
  2042. };
  2043. SettingsMenu.init();
  2044. };
  2045. function chatAddError(errorMessage, originalText)
  2046. {
  2047. return Chat.chatAddError(errorMessage, originalText);
  2048. };
  2049. function chatSetSubject(text)
  2050. {
  2051. return Chat.chatSetSubject(text);
  2052. };
  2053. function updateChatConversation(from, displayName, message, myjid, stamp) {
  2054. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  2055. }
  2056. function onMucJoined(jid, info) {
  2057. Toolbar.updateRoomUrl(window.location.href);
  2058. var meHTML = APP.translation.generateTranslationHTML("me");
  2059. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  2060. var settings = Settings.getSettings();
  2061. // Add myself to the contact list.
  2062. ContactList.addContact(jid, settings.email || settings.uid);
  2063. // Once we've joined the muc show the toolbar
  2064. ToolbarToggler.showToolbar();
  2065. var displayName = !config.displayJids
  2066. ? info.displayName : Strophe.getResourceFromJid(jid);
  2067. if (displayName)
  2068. onDisplayNameChanged('localVideoContainer', displayName);
  2069. VideoLayout.mucJoined();
  2070. }
  2071. function initEtherpad(name) {
  2072. Etherpad.init(name);
  2073. }
  2074. function onMucMemberLeft(jid) {
  2075. console.log('left.muc', jid);
  2076. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  2077. '>.displayname').html();
  2078. messageHandler.notify(displayName,'notify.somebody',
  2079. 'disconnected',
  2080. 'notify.disconnected');
  2081. if(!config.startAudioMuted ||
  2082. config.startAudioMuted > APP.members.size())
  2083. UIUtil.playSoundNotification('userLeft');
  2084. // Need to call this with a slight delay, otherwise the element couldn't be
  2085. // found for some reason.
  2086. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  2087. window.setTimeout(function () {
  2088. var container = document.getElementById(
  2089. 'participant_' + Strophe.getResourceFromJid(jid));
  2090. if (container) {
  2091. ContactList.removeContact(jid);
  2092. VideoLayout.removeConnectionIndicator(jid);
  2093. // hide here, wait for video to close before removing
  2094. $(container).hide();
  2095. VideoLayout.resizeThumbnails();
  2096. }
  2097. }, 10);
  2098. VideoLayout.participantLeft(jid);
  2099. };
  2100. function onLocalRoleChanged(jid, info, pres, isModerator)
  2101. {
  2102. console.info("My role changed, new role: " + info.role);
  2103. onModeratorStatusChanged(isModerator);
  2104. VideoLayout.showModeratorIndicator();
  2105. SettingsMenu.onRoleChanged();
  2106. if (isModerator) {
  2107. Authentication.closeAuthenticationWindow();
  2108. messageHandler.notify(null, "notify.me",
  2109. 'connected', "notify.moderator");
  2110. }
  2111. }
  2112. function onModeratorStatusChanged(isModerator) {
  2113. Toolbar.showSipCallButton(isModerator);
  2114. Toolbar.showRecordingButton(
  2115. isModerator); //&&
  2116. // FIXME:
  2117. // Recording visible if
  2118. // there are at least 2(+ 1 focus) participants
  2119. //Object.keys(connection.emuc.members).length >= 3);
  2120. }
  2121. function onPasswordRequired(callback) {
  2122. // password is required
  2123. Toolbar.lockLockButton();
  2124. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2125. message += APP.translation.translateString(
  2126. "dialog.passwordRequired");
  2127. message += '</h2>' +
  2128. '<input name="lockKey" type="text" data-i18n=' +
  2129. '"[placeholder]dialog.password" placeholder="' +
  2130. APP.translation.translateString("dialog.password") +
  2131. '" autofocus>';
  2132. messageHandler.openTwoButtonDialog(null, null, null, message,
  2133. true,
  2134. "dialog.Ok",
  2135. function (e, v, m, f) {},
  2136. null,
  2137. function (e, v, m, f) {
  2138. if (v) {
  2139. var lockKey = f.lockKey;
  2140. if (lockKey) {
  2141. Toolbar.setSharedKey(lockKey);
  2142. callback(lockKey);
  2143. }
  2144. }
  2145. },
  2146. ':input:first'
  2147. );
  2148. }
  2149. /**
  2150. * The dialpad button is shown iff there is at least one member that supports
  2151. * DTMF (e.g. jigasi).
  2152. */
  2153. function onDtmfSupportChanged(dtmfSupport) {
  2154. //TODO: enable when the UI is ready
  2155. //Toolbar.showDialPadButton(dtmfSupport);
  2156. }
  2157. function onMucMemberJoined(jid, id, displayName) {
  2158. messageHandler.notify(displayName,'notify.somebody',
  2159. 'connected',
  2160. 'notify.connected');
  2161. if(!config.startAudioMuted ||
  2162. config.startAudioMuted > APP.members.size())
  2163. UIUtil.playSoundNotification('userJoined');
  2164. // Add Peer's container
  2165. VideoLayout.ensurePeerContainerExists(jid,id);
  2166. }
  2167. function onMucPresenceStatus(jid, info) {
  2168. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  2169. }
  2170. function onMucRoleChanged(role, displayName) {
  2171. VideoLayout.showModeratorIndicator();
  2172. if (role === 'moderator') {
  2173. var messageKey, messageOptions = {};
  2174. if (!displayName) {
  2175. messageKey = "notify.grantedToUnknown";
  2176. }
  2177. else
  2178. {
  2179. messageKey = "notify.grantedTo";
  2180. messageOptions = {to: displayName};
  2181. }
  2182. messageHandler.notify(
  2183. displayName,'notify.somebody',
  2184. 'connected', messageKey,
  2185. messageOptions);
  2186. }
  2187. }
  2188. function onAuthenticationRequired(intervalCallback) {
  2189. Authentication.openAuthenticationDialog(
  2190. roomName, intervalCallback, function () {
  2191. Toolbar.authenticateClicked();
  2192. });
  2193. };
  2194. function onLastNChanged(oldValue, newValue) {
  2195. if (config.muteLocalVideoIfNotInLastN) {
  2196. setVideoMute(!newValue, { 'byUser': false });
  2197. }
  2198. }
  2199. UI.toggleSmileys = function () {
  2200. Chat.toggleSmileys();
  2201. };
  2202. UI.getSettings = function () {
  2203. return Settings.getSettings();
  2204. };
  2205. UI.toggleFilmStrip = function () {
  2206. return BottomToolbar.toggleFilmStrip();
  2207. };
  2208. UI.toggleChat = function () {
  2209. return BottomToolbar.toggleChat();
  2210. };
  2211. UI.toggleContactList = function () {
  2212. return BottomToolbar.toggleContactList();
  2213. };
  2214. UI.inputDisplayNameHandler = function (value) {
  2215. VideoLayout.inputDisplayNameHandler(value);
  2216. };
  2217. UI.getLargeVideoJid = function()
  2218. {
  2219. return VideoLayout.getLargeVideoJid();
  2220. };
  2221. UI.generateRoomName = function() {
  2222. if(roomName)
  2223. return roomName;
  2224. var roomnode = null;
  2225. var path = window.location.pathname;
  2226. // determinde the room node from the url
  2227. // TODO: just the roomnode or the whole bare jid?
  2228. if (config.getroomnode && typeof config.getroomnode === 'function') {
  2229. // custom function might be responsible for doing the pushstate
  2230. roomnode = config.getroomnode(path);
  2231. } else {
  2232. /* fall back to default strategy
  2233. * this is making assumptions about how the URL->room mapping happens.
  2234. * It currently assumes deployment at root, with a rewrite like the
  2235. * following one (for nginx):
  2236. location ~ ^/([a-zA-Z0-9]+)$ {
  2237. rewrite ^/(.*)$ / break;
  2238. }
  2239. */
  2240. if (path.length > 1) {
  2241. roomnode = path.substr(1).toLowerCase();
  2242. } else {
  2243. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  2244. roomnode = word.toLowerCase();
  2245. window.history.pushState('VideoChat',
  2246. 'Room: ' + word, window.location.pathname + word);
  2247. }
  2248. }
  2249. roomName = roomnode + '@' + config.hosts.muc;
  2250. return roomName;
  2251. };
  2252. UI.connectionIndicatorShowMore = function(jid)
  2253. {
  2254. return VideoLayout.showMore(jid);
  2255. };
  2256. UI.showLoginPopup = function(callback)
  2257. {
  2258. console.log('password is required');
  2259. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2260. message += APP.translation.translateString(
  2261. "dialog.passwordRequired");
  2262. message += '</h2>' +
  2263. '<input name="username" type="text" ' +
  2264. 'placeholder="user@domain.net" autofocus>' +
  2265. '<input name="password" ' +
  2266. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2267. ' placeholder="user password">';
  2268. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  2269. true,
  2270. "dialog.Ok",
  2271. function (e, v, m, f) {
  2272. if (v) {
  2273. if (f.username !== null && f.password != null) {
  2274. callback(f.username, f.password);
  2275. }
  2276. }
  2277. },
  2278. null, null, ':input:first'
  2279. );
  2280. }
  2281. UI.checkForNicknameAndJoin = function () {
  2282. Authentication.closeAuthenticationDialog();
  2283. Authentication.stopInterval();
  2284. var nick = null;
  2285. if (config.useNicks) {
  2286. nick = window.prompt('Your nickname (optional)');
  2287. }
  2288. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  2289. };
  2290. function dump(elem, filename) {
  2291. elem = elem.parentNode;
  2292. elem.download = filename || 'meetlog.json';
  2293. elem.href = 'data:application/json;charset=utf-8,\n';
  2294. var data = APP.xmpp.populateData();
  2295. var metadata = {};
  2296. metadata.time = new Date();
  2297. metadata.url = window.location.href;
  2298. metadata.ua = navigator.userAgent;
  2299. var log = APP.xmpp.getLogger();
  2300. if (log) {
  2301. metadata.xmpp = log;
  2302. }
  2303. data.metadata = metadata;
  2304. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  2305. return false;
  2306. }
  2307. UI.getRoomName = function () {
  2308. return roomName;
  2309. };
  2310. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  2311. if(muteAudio || muteVideo) notifyForInitialMute();
  2312. if(muteAudio) UI.setAudioMuted(true);
  2313. if(muteVideo) UI.setVideoMute(true);
  2314. }
  2315. /**
  2316. * Mutes/unmutes the local video.
  2317. */
  2318. UI.toggleVideo = function () {
  2319. setVideoMute(!APP.RTC.localVideo.isMuted());
  2320. };
  2321. /**
  2322. * Mutes / unmutes audio for the local participant.
  2323. */
  2324. UI.toggleAudio = function() {
  2325. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  2326. };
  2327. /**
  2328. * Sets muted audio state for the local participant.
  2329. */
  2330. UI.setAudioMuted = function (mute, earlyMute) {
  2331. var audioMute = null;
  2332. if(earlyMute)
  2333. audioMute = function (mute, cb) {
  2334. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  2335. };
  2336. else
  2337. audioMute = function (mute, cb) {
  2338. return APP.xmpp.setAudioMute(mute, cb);
  2339. }
  2340. if(!audioMute(mute, function () {
  2341. VideoLayout.showLocalAudioIndicator(mute);
  2342. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  2343. }))
  2344. {
  2345. // We still click the button.
  2346. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  2347. return;
  2348. }
  2349. }
  2350. UI.addListener = function (type, listener) {
  2351. eventEmitter.on(type, listener);
  2352. }
  2353. UI.clickOnVideo = function (videoNumber) {
  2354. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  2355. if (remoteVideos.length > videoNumber) {
  2356. remoteVideos[videoNumber].click();
  2357. }
  2358. }
  2359. //Used by torture
  2360. UI.showToolbar = function () {
  2361. return ToolbarToggler.showToolbar();
  2362. }
  2363. //Used by torture
  2364. UI.dockToolbar = function (isDock) {
  2365. return ToolbarToggler.dockToolbar(isDock);
  2366. }
  2367. UI.setVideoMuteButtonsState = function (mute) {
  2368. var video = $('#video');
  2369. var communicativeClass = "icon-camera";
  2370. var muteClass = "icon-camera icon-camera-disabled";
  2371. if (mute) {
  2372. video.removeClass(communicativeClass);
  2373. video.addClass(muteClass);
  2374. } else {
  2375. video.removeClass(muteClass);
  2376. video.addClass(communicativeClass);
  2377. }
  2378. }
  2379. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  2380. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  2381. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  2382. if(resourceJid === APP.xmpp.myResource())
  2383. SettingsMenu.changeAvatar(thumbUrl);
  2384. }
  2385. UI.setVideoMute = setVideoMute;
  2386. module.exports = UI;
  2387. },{"../../service/RTC/RTCEvents":100,"../../service/RTC/StreamEventTypes":102,"../../service/connectionquality/CQEvents":105,"../../service/desktopsharing/DesktopSharingEventTypes":106,"../../service/members/Events":107,"../../service/xmpp/XMPPEvents":109,"./../settings/Settings":47,"./audio_levels/AudioLevels.js":12,"./authentication/Authentication":14,"./avatar/Avatar":16,"./etherpad/Etherpad.js":17,"./prezi/Prezi.js":18,"./side_pannels/SidePanelToggler":20,"./side_pannels/chat/Chat.js":21,"./side_pannels/contactlist/ContactList":25,"./side_pannels/settings/SettingsMenu":26,"./toolbars/BottomToolbar":27,"./toolbars/Toolbar":28,"./toolbars/ToolbarToggler":29,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":1}],12:[function(require,module,exports){
  2388. var CanvasUtil = require("./CanvasUtils");
  2389. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  2390. function initActiveSpeakerAudioLevels() {
  2391. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  2392. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  2393. // Draw a circle.
  2394. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  2395. // Add a shadow around the circle
  2396. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  2397. ASDrawContext.shadowOffsetX = 0;
  2398. ASDrawContext.shadowOffsetY = 0;
  2399. }
  2400. /**
  2401. * The audio Levels plugin.
  2402. */
  2403. var AudioLevels = (function(my) {
  2404. var audioLevelCanvasCache = {};
  2405. my.LOCAL_LEVEL = 'local';
  2406. my.init = function () {
  2407. initActiveSpeakerAudioLevels();
  2408. }
  2409. /**
  2410. * Updates the audio level canvas for the given peerJid. If the canvas
  2411. * didn't exist we create it.
  2412. */
  2413. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  2414. var resourceJid = null;
  2415. var videoSpanId = null;
  2416. if (!peerJid)
  2417. videoSpanId = 'localVideoContainer';
  2418. else {
  2419. resourceJid = Strophe.getResourceFromJid(peerJid);
  2420. videoSpanId = 'participant_' + resourceJid;
  2421. }
  2422. var videoSpan = document.getElementById(videoSpanId);
  2423. if (!videoSpan) {
  2424. if (resourceJid)
  2425. console.error("No video element for jid", resourceJid);
  2426. else
  2427. console.error("No video element for local video.");
  2428. return;
  2429. }
  2430. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  2431. var videoSpaceWidth = $('#remoteVideos').width();
  2432. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  2433. var thumbnailWidth = thumbnailSize[0];
  2434. var thumbnailHeight = thumbnailSize[1];
  2435. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  2436. audioLevelCanvas = document.createElement('canvas');
  2437. audioLevelCanvas.className = "audiolevel";
  2438. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2439. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2440. resizeAudioLevelCanvas( audioLevelCanvas,
  2441. thumbnailWidth,
  2442. thumbnailHeight);
  2443. videoSpan.appendChild(audioLevelCanvas);
  2444. } else {
  2445. audioLevelCanvas = audioLevelCanvas.get(0);
  2446. resizeAudioLevelCanvas( audioLevelCanvas,
  2447. thumbnailWidth,
  2448. thumbnailHeight);
  2449. }
  2450. };
  2451. /**
  2452. * Updates the audio level UI for the given resourceJid.
  2453. *
  2454. * @param resourceJid the resource jid indicating the video element for
  2455. * which we draw the audio level
  2456. * @param audioLevel the newAudio level to render
  2457. */
  2458. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  2459. drawAudioLevelCanvas(resourceJid, audioLevel);
  2460. var videoSpanId = getVideoSpanId(resourceJid);
  2461. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  2462. if (!audioLevelCanvas)
  2463. return;
  2464. var drawContext = audioLevelCanvas.getContext('2d');
  2465. var canvasCache = audioLevelCanvasCache[resourceJid];
  2466. drawContext.clearRect (0, 0,
  2467. audioLevelCanvas.width, audioLevelCanvas.height);
  2468. drawContext.drawImage(canvasCache, 0, 0);
  2469. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  2470. if(!APP.xmpp.myJid()) {
  2471. return;
  2472. }
  2473. resourceJid = APP.xmpp.myResource();
  2474. }
  2475. if(resourceJid === largeVideoResourceJid) {
  2476. window.requestAnimationFrame(function () {
  2477. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  2478. });
  2479. }
  2480. };
  2481. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2482. if($("#activeSpeaker").css("visibility") == "hidden")
  2483. return;
  2484. ASDrawContext.clearRect(0, 0, 300, 300);
  2485. if(audioLevel == 0)
  2486. return;
  2487. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2488. // Fill the shape.
  2489. ASDrawContext.fill();
  2490. };
  2491. /**
  2492. * Resizes the given audio level canvas to match the given thumbnail size.
  2493. */
  2494. function resizeAudioLevelCanvas(audioLevelCanvas,
  2495. thumbnailWidth,
  2496. thumbnailHeight) {
  2497. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2498. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2499. }
  2500. /**
  2501. * Draws the audio level canvas into the cached canvas object.
  2502. *
  2503. * @param resourceJid the resource jid indicating the video element for
  2504. * which we draw the audio level
  2505. * @param audioLevel the newAudio level to render
  2506. */
  2507. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2508. if (!audioLevelCanvasCache[resourceJid]) {
  2509. var videoSpanId = getVideoSpanId(resourceJid);
  2510. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2511. /*
  2512. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2513. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2514. * error. Since audio levels are frequently updated, the errors have
  2515. * been observed to pile into the console, strain the CPU.
  2516. */
  2517. if (audioLevelCanvasOrig)
  2518. {
  2519. audioLevelCanvasCache[resourceJid]
  2520. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2521. }
  2522. }
  2523. var canvas = audioLevelCanvasCache[resourceJid];
  2524. if (!canvas)
  2525. return;
  2526. var drawContext = canvas.getContext('2d');
  2527. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2528. var shadowLevel = getShadowLevel(audioLevel);
  2529. if (shadowLevel > 0)
  2530. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2531. CanvasUtil.drawRoundRectGlow( drawContext,
  2532. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2533. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2534. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2535. interfaceConfig.CANVAS_RADIUS,
  2536. interfaceConfig.SHADOW_COLOR,
  2537. shadowLevel);
  2538. }
  2539. /**
  2540. * Returns the shadow/glow level for the given audio level.
  2541. *
  2542. * @param audioLevel the audio level from which we determine the shadow
  2543. * level
  2544. */
  2545. function getShadowLevel (audioLevel) {
  2546. var shadowLevel = 0;
  2547. if (audioLevel <= 0.3) {
  2548. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2549. }
  2550. else if (audioLevel <= 0.6) {
  2551. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2552. }
  2553. else {
  2554. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2555. }
  2556. return shadowLevel;
  2557. }
  2558. /**
  2559. * Returns the video span id corresponding to the given resourceJid or local
  2560. * user.
  2561. */
  2562. function getVideoSpanId(resourceJid) {
  2563. var videoSpanId = null;
  2564. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2565. || (APP.xmpp.myResource() && resourceJid
  2566. === APP.xmpp.myResource()))
  2567. videoSpanId = 'localVideoContainer';
  2568. else
  2569. videoSpanId = 'participant_' + resourceJid;
  2570. return videoSpanId;
  2571. }
  2572. /**
  2573. * Indicates that the remote video has been resized.
  2574. */
  2575. $(document).bind('remotevideo.resized', function (event, width, height) {
  2576. var resized = false;
  2577. $('#remoteVideos>span>canvas').each(function() {
  2578. var canvas = $(this).get(0);
  2579. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2580. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2581. resized = true;
  2582. }
  2583. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2584. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2585. resized = true;
  2586. }
  2587. });
  2588. if (resized)
  2589. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2590. audioLevelCanvasCache[resourceJid].width
  2591. = width + interfaceConfig.CANVAS_EXTRA;
  2592. audioLevelCanvasCache[resourceJid].height
  2593. = height + interfaceConfig.CANVAS_EXTRA;
  2594. });
  2595. });
  2596. return my;
  2597. })(AudioLevels || {});
  2598. module.exports = AudioLevels;
  2599. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  2600. /**
  2601. * Utility class for drawing canvas shapes.
  2602. */
  2603. var CanvasUtil = (function(my) {
  2604. /**
  2605. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2606. * of the glow.
  2607. *
  2608. * @param drawContext the context of the canvas to draw to
  2609. * @param x the x coordinate of the round rectangle
  2610. * @param y the y coordinate of the round rectangle
  2611. * @param w the width of the round rectangle
  2612. * @param h the height of the round rectangle
  2613. * @param glowColor the color of the glow
  2614. * @param glowWidth the width of the glow
  2615. */
  2616. my.drawRoundRectGlow
  2617. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2618. // Save the previous state of the context.
  2619. drawContext.save();
  2620. if (w < 2 * r) r = w / 2;
  2621. if (h < 2 * r) r = h / 2;
  2622. // Draw a round rectangle.
  2623. drawContext.beginPath();
  2624. drawContext.moveTo(x+r, y);
  2625. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2626. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2627. drawContext.arcTo(x, y+h, x, y, r);
  2628. drawContext.arcTo(x, y, x+w, y, r);
  2629. drawContext.closePath();
  2630. // Add a shadow around the rectangle
  2631. drawContext.shadowColor = glowColor;
  2632. drawContext.shadowBlur = glowWidth;
  2633. drawContext.shadowOffsetX = 0;
  2634. drawContext.shadowOffsetY = 0;
  2635. // Fill the shape.
  2636. drawContext.fill();
  2637. drawContext.save();
  2638. drawContext.restore();
  2639. // 1) Uncomment this line to use Composite Operation, which is doing the
  2640. // same as the clip function below and is also antialiasing the round
  2641. // border, but is said to be less fast performance wise.
  2642. // drawContext.globalCompositeOperation='destination-out';
  2643. drawContext.beginPath();
  2644. drawContext.moveTo(x+r, y);
  2645. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2646. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2647. drawContext.arcTo(x, y+h, x, y, r);
  2648. drawContext.arcTo(x, y, x+w, y, r);
  2649. drawContext.closePath();
  2650. // 2) Uncomment this line to use Composite Operation, which is doing the
  2651. // same as the clip function below and is also antialiasing the round
  2652. // border, but is said to be less fast performance wise.
  2653. // drawContext.fill();
  2654. // Comment these two lines if choosing to do the same with composite
  2655. // operation above 1 and 2.
  2656. drawContext.clip();
  2657. drawContext.clearRect(0, 0, 277, 200);
  2658. // Restore the previous context state.
  2659. drawContext.restore();
  2660. };
  2661. /**
  2662. * Clones the given canvas.
  2663. *
  2664. * @return the new cloned canvas.
  2665. */
  2666. my.cloneCanvas = function (oldCanvas) {
  2667. /*
  2668. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2669. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2670. * levels are frequently updated, the errors have been observed to pile
  2671. * into the console, strain the CPU.
  2672. */
  2673. if (!oldCanvas)
  2674. return oldCanvas;
  2675. //create a new canvas
  2676. var newCanvas = document.createElement('canvas');
  2677. var context = newCanvas.getContext('2d');
  2678. //set dimensions
  2679. newCanvas.width = oldCanvas.width;
  2680. newCanvas.height = oldCanvas.height;
  2681. //apply the old canvas to the new one
  2682. context.drawImage(oldCanvas, 0, 0);
  2683. //return the new canvas
  2684. return newCanvas;
  2685. };
  2686. return my;
  2687. })(CanvasUtil || {});
  2688. module.exports = CanvasUtil;
  2689. },{}],14:[function(require,module,exports){
  2690. /* global $, APP*/
  2691. var LoginDialog = require('./LoginDialog');
  2692. var Moderator = require('../../xmpp/moderator');
  2693. /* Initial "authentication required" dialog */
  2694. var authDialog = null;
  2695. /* Loop retry ID that wits for other user to create the room */
  2696. var authRetryId = null;
  2697. var authenticationWindow = null;
  2698. var Authentication = {
  2699. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2700. // This is the loop that will wait for the room to be created by
  2701. // someone else. 'auth_required.moderator' will bring us back here.
  2702. authRetryId = window.setTimeout(intervalCallback, 5000);
  2703. // Show prompt only if it's not open
  2704. if (authDialog !== null) {
  2705. return;
  2706. }
  2707. // extract room name from 'room@muc.server.net'
  2708. var room = roomName.substr(0, roomName.indexOf('@'));
  2709. var title
  2710. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  2711. var msg
  2712. = APP.translation.generateTranslationHTML(
  2713. "dialog.WaitForHostMsg", {room: room});
  2714. var buttonTxt
  2715. = APP.translation.generateTranslationHTML("dialog.IamHost");
  2716. var buttons = [];
  2717. buttons.push({title: buttonTxt, value: "authNow"});
  2718. authDialog = APP.UI.messageHandler.openDialog(
  2719. title,
  2720. msg,
  2721. true,
  2722. buttons,
  2723. function (onSubmitEvent, submitValue) {
  2724. // Do not close the dialog yet
  2725. onSubmitEvent.preventDefault();
  2726. // Open login popup
  2727. if (submitValue === 'authNow') {
  2728. callback();
  2729. }
  2730. }
  2731. );
  2732. },
  2733. closeAuthenticationWindow: function () {
  2734. if (authenticationWindow) {
  2735. authenticationWindow.close();
  2736. authenticationWindow = null;
  2737. }
  2738. },
  2739. xmppAuthenticate: function () {
  2740. var loginDialog = LoginDialog.show(
  2741. function (connection, state) {
  2742. if (!state) {
  2743. // User cancelled
  2744. loginDialog.close();
  2745. return;
  2746. } else if (state == APP.xmpp.Status.CONNECTED) {
  2747. loginDialog.close();
  2748. Authentication.stopInterval();
  2749. Authentication.closeAuthenticationDialog();
  2750. // Close the connection as anonymous one will be used
  2751. // to create the conference. Session-id will authorize
  2752. // the request.
  2753. connection.disconnect();
  2754. var roomName = APP.UI.generateRoomName();
  2755. Moderator.allocateConferenceFocus(roomName, function () {
  2756. // If it's not "on the fly" authentication now join
  2757. // the conference room
  2758. if (!APP.xmpp.getMUCJoined()) {
  2759. APP.UI.checkForNicknameAndJoin();
  2760. }
  2761. });
  2762. }
  2763. }, true);
  2764. },
  2765. focusAuthenticationWindow: function () {
  2766. // If auth window exists just bring it to the front
  2767. if (authenticationWindow) {
  2768. authenticationWindow.focus();
  2769. return;
  2770. }
  2771. },
  2772. closeAuthenticationDialog: function () {
  2773. // Close authentication dialog if opened
  2774. if (authDialog) {
  2775. authDialog.close();
  2776. authDialog = null;
  2777. }
  2778. },
  2779. createAuthenticationWindow: function (callback, url) {
  2780. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2781. url, 910, 660,
  2782. // On closed
  2783. function () {
  2784. // Close authentication dialog if opened
  2785. Authentication.closeAuthenticationDialog();
  2786. callback();
  2787. authenticationWindow = null;
  2788. });
  2789. return authenticationWindow;
  2790. },
  2791. stopInterval: function () {
  2792. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2793. if (authRetryId) {
  2794. window.clearTimeout(authRetryId);
  2795. authRetryId = null;
  2796. }
  2797. }
  2798. };
  2799. module.exports = Authentication;
  2800. },{"../../xmpp/moderator":58,"./LoginDialog":15}],15:[function(require,module,exports){
  2801. /* global $, APP, config*/
  2802. var XMPP = require('../../xmpp/xmpp');
  2803. var Moderator = require('../../xmpp/moderator');
  2804. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2805. // anonymous domain is not enabled
  2806. /**
  2807. * Creates new <tt>Dialog</tt> instance.
  2808. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2809. * when we either fail to connect or succeed(check Strophe.Status).
  2810. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2811. * in order to create session-id after the connection is established.
  2812. * @constructor
  2813. */
  2814. function Dialog(callback, obtainSession) {
  2815. var self = this;
  2816. var stop = false;
  2817. var connection = APP.xmpp.createConnection();
  2818. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2819. message += APP.translation.translateString("dialog.passwordRequired");
  2820. message += '</h2>' +
  2821. '<input name="username" type="text" ' +
  2822. 'placeholder="user@domain.net" autofocus>' +
  2823. '<input name="password" ' +
  2824. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2825. ' placeholder="user password">';
  2826. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  2827. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  2828. var states = {
  2829. login: {
  2830. html: message,
  2831. buttons: [
  2832. { title: okButton, value: true},
  2833. { title: cancelButton, value: false}
  2834. ],
  2835. focus: ':input:first',
  2836. submit: function (e, v, m, f) {
  2837. e.preventDefault();
  2838. if (v) {
  2839. var jid = f.username;
  2840. var password = f.password;
  2841. if (jid && password) {
  2842. stop = false;
  2843. connection.reset();
  2844. connDialog.goToState('connecting');
  2845. connection.connect(jid, password, stateHandler);
  2846. }
  2847. } else {
  2848. // User cancelled
  2849. stop = true;
  2850. callback();
  2851. }
  2852. }
  2853. },
  2854. connecting: {
  2855. title: APP.translation.translateString('dialog.connecting'),
  2856. html: '<div id="connectionStatus"></div>',
  2857. buttons: [],
  2858. defaultButton: 0
  2859. },
  2860. finished: {
  2861. title: APP.translation.translateString('dialog.error'),
  2862. html: '<div id="errorMessage"></div>',
  2863. buttons: [
  2864. {
  2865. title: APP.translation.translateString('dialog.retry'),
  2866. value: 'retry'
  2867. },
  2868. {
  2869. title: APP.translation.translateString('dialog.Cancel'),
  2870. value: 'cancel'
  2871. },
  2872. ],
  2873. defaultButton: 0,
  2874. submit: function (e, v, m, f) {
  2875. e.preventDefault();
  2876. if (v === 'retry')
  2877. connDialog.goToState('login');
  2878. else
  2879. callback();
  2880. }
  2881. }
  2882. };
  2883. var connDialog
  2884. = APP.UI.messageHandler.openDialogWithStates(states,
  2885. { persistent: true, closeText: '' }, null);
  2886. var stateHandler = function (status, message) {
  2887. if (stop) {
  2888. return;
  2889. }
  2890. var translateKey = "connection." + XMPP.getStatusString(status);
  2891. var statusStr = APP.translation.translateString(translateKey);
  2892. // Display current state
  2893. var connectionStatus =
  2894. connDialog.getState('connecting').find('#connectionStatus');
  2895. connectionStatus.text(statusStr);
  2896. switch (status) {
  2897. case XMPP.Status.CONNECTED:
  2898. stop = true;
  2899. if (!obtainSession) {
  2900. callback(connection, status);
  2901. return;
  2902. }
  2903. // Obtaining session-id status
  2904. connectionStatus.text(
  2905. APP.translation.translateString(
  2906. 'connection.FETCH_SESSION_ID'));
  2907. // Authenticate with Jicofo and obtain session-id
  2908. var roomName = APP.UI.generateRoomName();
  2909. // Jicofo will return new session-id when connected
  2910. // from authenticated domain
  2911. connection.sendIQ(
  2912. Moderator.createConferenceIq(roomName),
  2913. function (result) {
  2914. connectionStatus.text(
  2915. APP.translation.translateString(
  2916. 'connection.GOT_SESSION_ID'));
  2917. stop = true;
  2918. // Parse session-id
  2919. Moderator.parseSessionId(result);
  2920. callback(connection, status);
  2921. },
  2922. function (error) {
  2923. console.error("Auth on the fly failed", error);
  2924. stop = true;
  2925. var errorMsg =
  2926. APP.translation.translateString(
  2927. 'connection.GET_SESSION_ID_ERROR') +
  2928. $(error).find('>error').attr('code');
  2929. self.displayError(errorMsg);
  2930. connection.disconnect();
  2931. });
  2932. break;
  2933. case XMPP.Status.AUTHFAIL:
  2934. case XMPP.Status.CONNFAIL:
  2935. case XMPP.Status.DISCONNECTED:
  2936. stop = true;
  2937. callback(connection, status);
  2938. var errorMessage = statusStr;
  2939. if (message)
  2940. {
  2941. errorMessage += ': ' + message;
  2942. }
  2943. self.displayError(errorMessage);
  2944. break;
  2945. default:
  2946. break;
  2947. }
  2948. };
  2949. /**
  2950. * Displays error message in 'finished' state which allows either to cancel
  2951. * or retry.
  2952. * @param message the final message to be displayed.
  2953. */
  2954. this.displayError = function (message) {
  2955. var finishedState = connDialog.getState('finished');
  2956. var errorMessageElem = finishedState.find('#errorMessage');
  2957. errorMessageElem.text(message);
  2958. connDialog.goToState('finished');
  2959. };
  2960. /**
  2961. * Closes LoginDialog.
  2962. */
  2963. this.close = function () {
  2964. stop = true;
  2965. connDialog.close();
  2966. };
  2967. }
  2968. var LoginDialog = {
  2969. /**
  2970. * Displays login prompt used to establish new XMPP connection. Given
  2971. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2972. * called when we connect successfully(status === CONNECTED) or when we fail
  2973. * to do so. On connection failure program can call Dialog.close() method in
  2974. * order to cancel or do nothing to let the user retry.
  2975. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2976. * called when we either fail to connect or succeed(check
  2977. * Strophe.Status).
  2978. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2979. * Jicofo in order to create session-id after the connection is
  2980. * established.
  2981. * @returns {Dialog}
  2982. */
  2983. show: function (callback, obtainSession) {
  2984. return new Dialog(callback, obtainSession);
  2985. }
  2986. };
  2987. module.exports = LoginDialog;
  2988. },{"../../xmpp/moderator":58,"../../xmpp/xmpp":66}],16:[function(require,module,exports){
  2989. var Settings = require("../../settings/Settings");
  2990. var users = {};
  2991. var Avatar = {
  2992. /**
  2993. * Sets the user's avatar in the settings menu(if local user), contact list
  2994. * and thumbnail
  2995. * @param jid jid of the user
  2996. * @param id email or userID to be used as a hash
  2997. */
  2998. setUserAvatar: function (jid, id) {
  2999. if (id) {
  3000. if (users[jid] === id) {
  3001. return;
  3002. }
  3003. users[jid] = id;
  3004. }
  3005. var thumbUrl = this.getGravatarUrl(users[jid] || jid, 100);
  3006. var contactListUrl = this.getGravatarUrl(users[jid] || jid);
  3007. var resourceJid = Strophe.getResourceFromJid(jid);
  3008. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  3009. },
  3010. getGravatarUrl: function (id, size) {
  3011. if(id === APP.xmpp.myJid() || !id) {
  3012. id = Settings.getSettings().uid;
  3013. }
  3014. return 'https://www.gravatar.com/avatar/' +
  3015. MD5.hexdigest(id.trim().toLowerCase()) +
  3016. "?d=wavatar&size=" + (size || "30");
  3017. }
  3018. };
  3019. module.exports = Avatar;
  3020. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  3021. /* global $, config,
  3022. setLargeVideoVisible, Util */
  3023. var VideoLayout = require("../videolayout/VideoLayout");
  3024. var Prezi = require("../prezi/Prezi");
  3025. var UIUtil = require("../util/UIUtil");
  3026. var etherpadName = null;
  3027. var etherpadIFrame = null;
  3028. var domain = null;
  3029. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  3030. /**
  3031. * Resizes the etherpad.
  3032. */
  3033. function resize() {
  3034. if ($('#etherpad>iframe').length) {
  3035. var remoteVideos = $('#remoteVideos');
  3036. var availableHeight
  3037. = window.innerHeight - remoteVideos.outerHeight();
  3038. var availableWidth = UIUtil.getAvailableVideoWidth();
  3039. $('#etherpad>iframe').width(availableWidth);
  3040. $('#etherpad>iframe').height(availableHeight);
  3041. }
  3042. }
  3043. /**
  3044. * Creates the Etherpad button and adds it to the toolbar.
  3045. */
  3046. function enableEtherpadButton() {
  3047. if (!$('#etherpadButton').is(":visible"))
  3048. $('#etherpadButton').css({display: 'inline-block'});
  3049. }
  3050. /**
  3051. * Creates the IFrame for the etherpad.
  3052. */
  3053. function createIFrame() {
  3054. etherpadIFrame = document.createElement('iframe');
  3055. etherpadIFrame.src = domain + etherpadName + options;
  3056. etherpadIFrame.frameBorder = 0;
  3057. etherpadIFrame.scrolling = "no";
  3058. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  3059. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  3060. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  3061. document.getElementById('etherpad').appendChild(etherpadIFrame);
  3062. etherpadIFrame.onload = function() {
  3063. document.domain = document.domain;
  3064. bubbleIframeMouseMove(etherpadIFrame);
  3065. setTimeout(function() {
  3066. // the iframes inside of the etherpad are
  3067. // not yet loaded when the etherpad iframe is loaded
  3068. var outer = etherpadIFrame.
  3069. contentDocument.getElementsByName("ace_outer")[0];
  3070. bubbleIframeMouseMove(outer);
  3071. var inner = outer.
  3072. contentDocument.getElementsByName("ace_inner")[0];
  3073. bubbleIframeMouseMove(inner);
  3074. }, 2000);
  3075. };
  3076. }
  3077. function bubbleIframeMouseMove(iframe){
  3078. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  3079. iframe.contentWindow.onmousemove = function(e){
  3080. if(existingOnMouseMove) existingOnMouseMove(e);
  3081. var evt = document.createEvent("MouseEvents");
  3082. var boundingClientRect = iframe.getBoundingClientRect();
  3083. evt.initMouseEvent(
  3084. "mousemove",
  3085. true, // bubbles
  3086. false, // not cancelable
  3087. window,
  3088. e.detail,
  3089. e.screenX,
  3090. e.screenY,
  3091. e.clientX + boundingClientRect.left,
  3092. e.clientY + boundingClientRect.top,
  3093. e.ctrlKey,
  3094. e.altKey,
  3095. e.shiftKey,
  3096. e.metaKey,
  3097. e.button,
  3098. null // no related element
  3099. );
  3100. iframe.dispatchEvent(evt);
  3101. };
  3102. }
  3103. /**
  3104. * On video selected event.
  3105. */
  3106. $(document).bind('video.selected', function (event, isPresentation) {
  3107. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  3108. Etherpad.toggleEtherpad(isPresentation);
  3109. });
  3110. var Etherpad = {
  3111. /**
  3112. * Initializes the etherpad.
  3113. */
  3114. init: function (name) {
  3115. if (config.etherpad_base && !etherpadName && name) {
  3116. domain = config.etherpad_base;
  3117. etherpadName = name;
  3118. enableEtherpadButton();
  3119. /**
  3120. * Resizes the etherpad, when the window is resized.
  3121. */
  3122. $(window).resize(function () {
  3123. resize();
  3124. });
  3125. }
  3126. },
  3127. /**
  3128. * Opens/hides the Etherpad.
  3129. */
  3130. toggleEtherpad: function (isPresentation) {
  3131. if (!etherpadIFrame)
  3132. createIFrame();
  3133. var largeVideo = null;
  3134. if (Prezi.isPresentationVisible())
  3135. largeVideo = $('#presentation>iframe');
  3136. else
  3137. largeVideo = $('#largeVideo');
  3138. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  3139. $('#activeSpeaker').css('visibility', 'hidden');
  3140. largeVideo.fadeOut(300, function () {
  3141. if (Prezi.isPresentationVisible()) {
  3142. largeVideo.css({opacity: '0'});
  3143. } else {
  3144. VideoLayout.setLargeVideoVisible(false);
  3145. }
  3146. });
  3147. $('#etherpad>iframe').fadeIn(300, function () {
  3148. document.body.style.background = '#eeeeee';
  3149. $('#etherpad>iframe').css({visibility: 'visible'});
  3150. $('#etherpad').css({zIndex: 2});
  3151. });
  3152. }
  3153. else if ($('#etherpad>iframe')) {
  3154. $('#etherpad>iframe').fadeOut(300, function () {
  3155. $('#etherpad>iframe').css({visibility: 'hidden'});
  3156. $('#etherpad').css({zIndex: 0});
  3157. document.body.style.background = 'black';
  3158. });
  3159. if (!isPresentation) {
  3160. $('#largeVideo').fadeIn(300, function () {
  3161. VideoLayout.setLargeVideoVisible(true);
  3162. });
  3163. }
  3164. }
  3165. resize();
  3166. },
  3167. isVisible: function() {
  3168. var etherpadIframe = $('#etherpad>iframe');
  3169. return etherpadIframe && etherpadIframe.is(':visible');
  3170. }
  3171. };
  3172. module.exports = Etherpad;
  3173. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  3174. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3175. var UIUtil = require("../util/UIUtil");
  3176. var VideoLayout = require("../videolayout/VideoLayout");
  3177. var messageHandler = require("../util/MessageHandler");
  3178. var PreziPlayer = require("./PreziPlayer");
  3179. var preziPlayer = null;
  3180. var Prezi = {
  3181. /**
  3182. * Reloads the current presentation.
  3183. */
  3184. reloadPresentation: function() {
  3185. var iframe = document.getElementById(preziPlayer.options.preziId);
  3186. iframe.src = iframe.src;
  3187. },
  3188. /**
  3189. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  3190. * otherwise.
  3191. */
  3192. isPresentationVisible: function () {
  3193. return ($('#presentation>iframe') != null
  3194. && $('#presentation>iframe').css('opacity') == 1);
  3195. },
  3196. /**
  3197. * Opens the Prezi dialog, from which the user could choose a presentation
  3198. * to load.
  3199. */
  3200. openPreziDialog: function() {
  3201. var myprezi = APP.xmpp.getPrezi();
  3202. if (myprezi) {
  3203. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  3204. null,
  3205. "dialog.removePreziMsg",
  3206. null,
  3207. false,
  3208. "dialog.Remove",
  3209. function(e,v,m,f) {
  3210. if(v) {
  3211. APP.xmpp.removePreziFromPresence();
  3212. }
  3213. }
  3214. );
  3215. }
  3216. else if (preziPlayer != null) {
  3217. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  3218. null, "dialog.sharePreziMsg",
  3219. null,
  3220. false,
  3221. "dialog.Ok",
  3222. function(e,v,m,f) {
  3223. $.prompt.close();
  3224. }
  3225. );
  3226. }
  3227. else {
  3228. var html = APP.translation.generateTranslationHTML(
  3229. "dialog.sharePreziTitle");
  3230. var cancelButton = APP.translation.generateTranslationHTML(
  3231. "dialog.Cancel");
  3232. var shareButton = APP.translation.generateTranslationHTML(
  3233. "dialog.Share");
  3234. var backButton = APP.translation.generateTranslationHTML(
  3235. "dialog.Back");
  3236. var buttons = [];
  3237. var buttons1 = [];
  3238. // Cancel button to both states
  3239. buttons.push({title: cancelButton, value: false});
  3240. buttons1.push({title: cancelButton, value: false});
  3241. // Share button
  3242. buttons.push({title: shareButton, value: true});
  3243. // Back button
  3244. buttons1.push({title: backButton, value: true});
  3245. var linkError = APP.translation.generateTranslationHTML(
  3246. "dialog.preziLinkError");
  3247. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  3248. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  3249. var openPreziState = {
  3250. state0: {
  3251. html: '<h2>' + html + '</h2>' +
  3252. '<input name="preziUrl" type="text" ' +
  3253. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  3254. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  3255. '\' placeholder="' + defaultUrl + '" autofocus>',
  3256. persistent: false,
  3257. buttons: buttons,
  3258. focus: ':input:first',
  3259. defaultButton: 0,
  3260. submit: function (e, v, m, f) {
  3261. e.preventDefault();
  3262. if(v)
  3263. {
  3264. var preziUrl = f.preziUrl;
  3265. if (preziUrl)
  3266. {
  3267. var urlValue
  3268. = encodeURI(UIUtil.escapeHtml(preziUrl));
  3269. if (urlValue.indexOf('http://prezi.com/') != 0
  3270. && urlValue.indexOf('https://prezi.com/') != 0)
  3271. {
  3272. $.prompt.goToState('state1');
  3273. return false;
  3274. }
  3275. else {
  3276. var presIdTmp = urlValue.substring(
  3277. urlValue.indexOf("prezi.com/") + 10);
  3278. if (!isAlphanumeric(presIdTmp)
  3279. || presIdTmp.indexOf('/') < 2) {
  3280. $.prompt.goToState('state1');
  3281. return false;
  3282. }
  3283. else {
  3284. APP.xmpp.addToPresence("prezi", urlValue);
  3285. $.prompt.close();
  3286. }
  3287. }
  3288. }
  3289. }
  3290. else
  3291. $.prompt.close();
  3292. }
  3293. },
  3294. state1: {
  3295. html: '<h2>' + html + '</h2>' +
  3296. linkError,
  3297. persistent: false,
  3298. buttons: buttons1,
  3299. focus: ':input:first',
  3300. defaultButton: 1,
  3301. submit: function (e, v, m, f) {
  3302. e.preventDefault();
  3303. if (v === 0)
  3304. $.prompt.close();
  3305. else
  3306. $.prompt.goToState('state0');
  3307. }
  3308. }
  3309. };
  3310. messageHandler.openDialogWithStates(openPreziState);
  3311. }
  3312. }
  3313. };
  3314. /**
  3315. * A new presentation has been added.
  3316. *
  3317. * @param event the event indicating the add of a presentation
  3318. * @param jid the jid from which the presentation was added
  3319. * @param presUrl url of the presentation
  3320. * @param currentSlide the current slide to which we should move
  3321. */
  3322. function presentationAdded(event, jid, presUrl, currentSlide) {
  3323. console.log("presentation added", presUrl);
  3324. var presId = getPresentationId(presUrl);
  3325. var elementId = 'participant_'
  3326. + Strophe.getResourceFromJid(jid)
  3327. + '_' + presId;
  3328. VideoLayout.addPreziContainer(elementId);
  3329. VideoLayout.resizeThumbnails();
  3330. var controlsEnabled = false;
  3331. if (jid === APP.xmpp.myJid())
  3332. controlsEnabled = true;
  3333. setPresentationVisible(true);
  3334. $('#largeVideoContainer').hover(
  3335. function (event) {
  3336. if (Prezi.isPresentationVisible()) {
  3337. var reloadButtonRight = window.innerWidth
  3338. - $('#presentation>iframe').offset().left
  3339. - $('#presentation>iframe').width();
  3340. $('#reloadPresentation').css({ right: reloadButtonRight,
  3341. display:'inline-block'});
  3342. }
  3343. },
  3344. function (event) {
  3345. if (!Prezi.isPresentationVisible())
  3346. $('#reloadPresentation').css({display:'none'});
  3347. else {
  3348. var e = event.toElement || event.relatedTarget;
  3349. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  3350. $('#reloadPresentation').css({display:'none'});
  3351. }
  3352. });
  3353. preziPlayer = new PreziPlayer(
  3354. 'presentation',
  3355. {preziId: presId,
  3356. width: getPresentationWidth(),
  3357. height: getPresentationHeihgt(),
  3358. controls: controlsEnabled,
  3359. debug: true
  3360. });
  3361. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  3362. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  3363. console.log("prezi status", event.value);
  3364. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  3365. if (jid != APP.xmpp.myJid())
  3366. preziPlayer.flyToStep(currentSlide);
  3367. }
  3368. });
  3369. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  3370. console.log("event value", event.value);
  3371. APP.xmpp.addToPresence("preziSlide", event.value);
  3372. });
  3373. $("#" + elementId).css( 'background-image',
  3374. 'url(../images/avatarprezi.png)');
  3375. $("#" + elementId).click(
  3376. function () {
  3377. setPresentationVisible(true);
  3378. }
  3379. );
  3380. };
  3381. /**
  3382. * A presentation has been removed.
  3383. *
  3384. * @param event the event indicating the remove of a presentation
  3385. * @param jid the jid for which the presentation was removed
  3386. * @param the url of the presentation
  3387. */
  3388. function presentationRemoved(event, jid, presUrl) {
  3389. console.log('presentation removed', presUrl);
  3390. var presId = getPresentationId(presUrl);
  3391. setPresentationVisible(false);
  3392. $('#participant_'
  3393. + Strophe.getResourceFromJid(jid)
  3394. + '_' + presId).remove();
  3395. $('#presentation>iframe').remove();
  3396. if (preziPlayer != null) {
  3397. preziPlayer.destroy();
  3398. preziPlayer = null;
  3399. }
  3400. };
  3401. /**
  3402. * Indicates if the given string is an alphanumeric string.
  3403. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  3404. * purpose of checking URIs.
  3405. */
  3406. function isAlphanumeric(unsafeText) {
  3407. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  3408. return regex.test(unsafeText);
  3409. }
  3410. /**
  3411. * Returns the presentation id from the given url.
  3412. */
  3413. function getPresentationId (presUrl) {
  3414. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  3415. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  3416. }
  3417. /**
  3418. * Returns the presentation width.
  3419. */
  3420. function getPresentationWidth() {
  3421. var availableWidth = UIUtil.getAvailableVideoWidth();
  3422. var availableHeight = getPresentationHeihgt();
  3423. var aspectRatio = 16.0 / 9.0;
  3424. if (availableHeight < availableWidth / aspectRatio) {
  3425. availableWidth = Math.floor(availableHeight * aspectRatio);
  3426. }
  3427. return availableWidth;
  3428. }
  3429. /**
  3430. * Returns the presentation height.
  3431. */
  3432. function getPresentationHeihgt() {
  3433. var remoteVideos = $('#remoteVideos');
  3434. return window.innerHeight - remoteVideos.outerHeight();
  3435. }
  3436. /**
  3437. * Resizes the presentation iframe.
  3438. */
  3439. function resize() {
  3440. if ($('#presentation>iframe')) {
  3441. $('#presentation>iframe').width(getPresentationWidth());
  3442. $('#presentation>iframe').height(getPresentationHeihgt());
  3443. }
  3444. }
  3445. /**
  3446. * Shows/hides a presentation.
  3447. */
  3448. function setPresentationVisible(visible) {
  3449. var prezi = $('#presentation>iframe');
  3450. if (visible) {
  3451. // Trigger the video.selected event to indicate a change in the
  3452. // large video.
  3453. $(document).trigger("video.selected", [true]);
  3454. $('#largeVideo').fadeOut(300);
  3455. prezi.fadeIn(300, function() {
  3456. prezi.css({opacity:'1'});
  3457. ToolbarToggler.dockToolbar(true);
  3458. VideoLayout.setLargeVideoVisible(false);
  3459. });
  3460. $('#activeSpeaker').css('visibility', 'hidden');
  3461. }
  3462. else {
  3463. if (prezi.css('opacity') == '1') {
  3464. prezi.fadeOut(300, function () {
  3465. prezi.css({opacity:'0'});
  3466. $('#reloadPresentation').css({display:'none'});
  3467. $('#largeVideo').fadeIn(300, function() {
  3468. VideoLayout.setLargeVideoVisible(true);
  3469. ToolbarToggler.dockToolbar(false);
  3470. });
  3471. });
  3472. }
  3473. }
  3474. }
  3475. /**
  3476. * Presentation has been removed.
  3477. */
  3478. $(document).bind('presentationremoved.muc', presentationRemoved);
  3479. /**
  3480. * Presentation has been added.
  3481. */
  3482. $(document).bind('presentationadded.muc', presentationAdded);
  3483. /*
  3484. * Indicates presentation slide change.
  3485. */
  3486. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3487. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3488. preziPlayer.flyToStep(current);
  3489. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3490. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3491. preziPlayer.flyToStep(current, i);
  3492. }
  3493. }
  3494. });
  3495. /**
  3496. * On video selected event.
  3497. */
  3498. $(document).bind('video.selected', function (event, isPresentation) {
  3499. if (!isPresentation && $('#presentation>iframe')) {
  3500. setPresentationVisible(false);
  3501. }
  3502. });
  3503. $(window).resize(function () {
  3504. resize();
  3505. });
  3506. module.exports = Prezi;
  3507. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  3508. (function() {
  3509. "use strict";
  3510. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3511. window.PreziPlayer = (function() {
  3512. PreziPlayer.API_VERSION = 1;
  3513. PreziPlayer.CURRENT_STEP = 'currentStep';
  3514. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3515. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3516. PreziPlayer.STATUS_LOADING = 'loading';
  3517. PreziPlayer.STATUS_READY = 'ready';
  3518. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3519. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3520. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3521. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3522. PreziPlayer.EVENT_STATUS = "statusChange";
  3523. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3524. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3525. PreziPlayer.domain = "https://prezi.com";
  3526. PreziPlayer.path = "/player/";
  3527. PreziPlayer.players = {};
  3528. PreziPlayer.binded_methods = ['changesHandler'];
  3529. PreziPlayer.createMultiplePlayers = function(optionArray){
  3530. for(var i=0; i<optionArray.length; i++) {
  3531. var optionSet = optionArray[i];
  3532. new PreziPlayer(optionSet.id, optionSet);
  3533. };
  3534. };
  3535. PreziPlayer.messageReceived = function(event){
  3536. var message, item, player;
  3537. try {
  3538. message = JSON.parse(event.data);
  3539. if (message.id && (player = PreziPlayer.players[message.id])) {
  3540. if (player.options.debug === true) {
  3541. if (console && console.log)
  3542. console.log('received', message);
  3543. }
  3544. if (message.type === "changes") {
  3545. player.changesHandler(message);
  3546. }
  3547. for (var i = 0; i < player.callbacks.length; i++) {
  3548. item = player.callbacks[i];
  3549. if (item && message.type === item.event) {
  3550. item.callback(message);
  3551. }
  3552. }
  3553. }
  3554. } catch (e) { }
  3555. };
  3556. function PreziPlayer(id, options) {
  3557. var params, paramString = "", _this = this;
  3558. if (PreziPlayer.players[id]){
  3559. PreziPlayer.players[id].destroy();
  3560. }
  3561. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3562. var method_name = PreziPlayer.binded_methods[i];
  3563. _this[method_name] = __bind(_this[method_name], _this);
  3564. };
  3565. options = options || {};
  3566. this.options = options;
  3567. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3568. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3569. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3570. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3571. this.callbacks = [];
  3572. this.id = id;
  3573. this.embedTo = document.getElementById(id);
  3574. if (!this.embedTo) {
  3575. throw "The element id is not available.";
  3576. }
  3577. this.iframe = document.createElement('iframe');
  3578. params = [
  3579. { name: 'oid', value: options.preziId },
  3580. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3581. { name: 'controls', value: options.controls ? 1 : 0 }
  3582. ];
  3583. for(var i=0; i<params.length; i++) {
  3584. var param = params[i];
  3585. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3586. };
  3587. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3588. this.iframe.frameBorder = 0;
  3589. this.iframe.scrolling = "no";
  3590. this.iframe.width = options.width || 640;
  3591. this.iframe.height = options.height || 480;
  3592. this.embedTo.innerHTML = '';
  3593. // JITSI: IN CASE SOMETHING GOES WRONG.
  3594. try {
  3595. this.embedTo.appendChild(this.iframe);
  3596. }
  3597. catch (err) {
  3598. console.log("CATCH ERROR");
  3599. }
  3600. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3601. // crashes for us.
  3602. this.initPollInterval = setInterval(function(){
  3603. _this.sendMessage({'action': 'init'});
  3604. }, 500);
  3605. PreziPlayer.players[id] = this;
  3606. }
  3607. PreziPlayer.prototype.changesHandler = function(message) {
  3608. var key, value, j, item;
  3609. if (this.initPollInterval) {
  3610. clearInterval(this.initPollInterval);
  3611. this.initPollInterval = false;
  3612. }
  3613. for (key in message.data) {
  3614. if (message.data.hasOwnProperty(key)){
  3615. value = message.data[key];
  3616. this.values[key] = value;
  3617. for (j=0; j<this.callbacks.length; j++) {
  3618. item = this.callbacks[j];
  3619. if (item && item.event === key + "Change"){
  3620. item.callback({type: item.event, value: value});
  3621. }
  3622. }
  3623. }
  3624. }
  3625. };
  3626. PreziPlayer.prototype.destroy = function() {
  3627. if (this.initPollInterval) {
  3628. clearInterval(this.initPollInterval);
  3629. this.initPollInterval = false;
  3630. }
  3631. this.embedTo.innerHTML = '';
  3632. };
  3633. PreziPlayer.prototype.sendMessage = function(message) {
  3634. if (this.options.debug === true) {
  3635. if (console && console.log) console.log('sent', message);
  3636. }
  3637. message.version = PreziPlayer.API_VERSION;
  3638. message.id = this.id;
  3639. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3640. };
  3641. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3642. PreziPlayer.prototype.flyToNextStep = function() {
  3643. return this.sendMessage({
  3644. 'action': 'present',
  3645. 'data': ['moveToNextStep']
  3646. });
  3647. };
  3648. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3649. PreziPlayer.prototype.flyToPreviousStep = function() {
  3650. return this.sendMessage({
  3651. 'action': 'present',
  3652. 'data': ['moveToPrevStep']
  3653. });
  3654. };
  3655. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3656. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3657. var obj = this;
  3658. // check animation_step
  3659. if (animation_step > 0 &&
  3660. obj.values.animationCountOnSteps &&
  3661. obj.values.animationCountOnSteps[step] <= animation_step) {
  3662. animation_step = obj.values.animationCountOnSteps[step];
  3663. }
  3664. // jump to animation steps by calling flyToNextStep()
  3665. function doAnimationSteps() {
  3666. if (obj.values.isMoving == true) {
  3667. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3668. return;
  3669. }
  3670. while (animation_step-- > 0) {
  3671. obj.flyToNextStep(); // do the animation steps
  3672. }
  3673. }
  3674. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3675. // jump to the step
  3676. return this.sendMessage({
  3677. 'action': 'present',
  3678. 'data': ['moveToStep', step]
  3679. });
  3680. };
  3681. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3682. PreziPlayer.prototype.flyToObject = function(objectId) {
  3683. return this.sendMessage({
  3684. 'action': 'present',
  3685. 'data': ['moveToObject', objectId]
  3686. });
  3687. };
  3688. PreziPlayer.prototype.play = function(defaultDelay) {
  3689. return this.sendMessage({
  3690. 'action': 'present',
  3691. 'data': ['startAutoPlay', defaultDelay]
  3692. });
  3693. };
  3694. PreziPlayer.prototype.stop = function() {
  3695. return this.sendMessage({
  3696. 'action': 'present',
  3697. 'data': ['stopAutoPlay']
  3698. });
  3699. };
  3700. PreziPlayer.prototype.pause = function(defaultDelay) {
  3701. return this.sendMessage({
  3702. 'action': 'present',
  3703. 'data': ['pauseAutoPlay', defaultDelay]
  3704. });
  3705. };
  3706. PreziPlayer.prototype.getCurrentStep = function() {
  3707. return this.values.currentStep;
  3708. };
  3709. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3710. return this.values.currentAnimationStep;
  3711. };
  3712. PreziPlayer.prototype.getCurrentObject = function() {
  3713. return this.values.currentObject;
  3714. };
  3715. PreziPlayer.prototype.getStatus = function() {
  3716. return this.values.status;
  3717. };
  3718. PreziPlayer.prototype.isPlaying = function() {
  3719. return this.values.isAutoPlaying;
  3720. };
  3721. PreziPlayer.prototype.getStepCount = function() {
  3722. return this.values.stepCount;
  3723. };
  3724. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3725. return this.values.animationCountOnSteps;
  3726. };
  3727. PreziPlayer.prototype.getTitle = function() {
  3728. return this.values.title;
  3729. };
  3730. PreziPlayer.prototype.setDimensions = function(dims) {
  3731. for (var parameter in dims) {
  3732. this.iframe[parameter] = dims[parameter];
  3733. }
  3734. }
  3735. PreziPlayer.prototype.getDimensions = function() {
  3736. return {
  3737. width: parseInt(this.iframe.width, 10),
  3738. height: parseInt(this.iframe.height, 10)
  3739. }
  3740. }
  3741. PreziPlayer.prototype.on = function(event, callback) {
  3742. this.callbacks.push({
  3743. event: event,
  3744. callback: callback
  3745. });
  3746. };
  3747. PreziPlayer.prototype.off = function(event, callback) {
  3748. var j, item;
  3749. if (event === undefined) {
  3750. this.callbacks = [];
  3751. }
  3752. j = this.callbacks.length;
  3753. while (j--) {
  3754. item = this.callbacks[j];
  3755. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3756. this.callbacks.splice(j, 1);
  3757. }
  3758. }
  3759. };
  3760. if (window.addEventListener) {
  3761. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3762. } else {
  3763. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3764. }
  3765. return PreziPlayer;
  3766. })();
  3767. })();
  3768. module.exports = PreziPlayer;
  3769. },{}],20:[function(require,module,exports){
  3770. var Chat = require("./chat/Chat");
  3771. var ContactList = require("./contactlist/ContactList");
  3772. var Settings = require("./../../settings/Settings");
  3773. var SettingsMenu = require("./settings/SettingsMenu");
  3774. var VideoLayout = require("../videolayout/VideoLayout");
  3775. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3776. var UIUtil = require("../util/UIUtil");
  3777. var LargeVideo = require("../videolayout/LargeVideo");
  3778. /**
  3779. * Toggler for the chat, contact list, settings menu, etc..
  3780. */
  3781. var PanelToggler = (function(my) {
  3782. var currentlyOpen = null;
  3783. var buttons = {
  3784. '#chatspace': '#chatBottomButton',
  3785. '#contactlist': '#contactListButton',
  3786. '#settingsmenu': '#settingsButton'
  3787. };
  3788. /**
  3789. * Toggles the windows in the side panel
  3790. * @param object the window that should be shown
  3791. * @param selector the selector for the element containing the panel
  3792. * @param onOpenComplete function to be called when the panel is opened
  3793. * @param onOpen function to be called if the window is going to be opened
  3794. * @param onClose function to be called if the window is going to be closed
  3795. */
  3796. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3797. UIUtil.buttonClick(buttons[selector], "active");
  3798. if (object.isVisible()) {
  3799. $("#toast-container").animate({
  3800. right: '5px'
  3801. },
  3802. {
  3803. queue: false,
  3804. duration: 500
  3805. });
  3806. $(selector).hide("slide", {
  3807. direction: "right",
  3808. queue: false,
  3809. duration: 500
  3810. });
  3811. if(typeof onClose === "function") {
  3812. onClose();
  3813. }
  3814. currentlyOpen = null;
  3815. }
  3816. else {
  3817. // Undock the toolbar when the chat is shown and if we're in a
  3818. // video mode.
  3819. if (LargeVideo.isLargeVideoVisible()) {
  3820. ToolbarToggler.dockToolbar(false);
  3821. }
  3822. if(currentlyOpen) {
  3823. var current = $(currentlyOpen);
  3824. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3825. current.css('z-index', 4);
  3826. setTimeout(function () {
  3827. current.css('display', 'none');
  3828. current.css('z-index', 5);
  3829. }, 500);
  3830. }
  3831. $("#toast-container").animate({
  3832. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3833. },
  3834. {
  3835. queue: false,
  3836. duration: 500
  3837. });
  3838. $(selector).show("slide", {
  3839. direction: "right",
  3840. queue: false,
  3841. duration: 500,
  3842. complete: onOpenComplete
  3843. });
  3844. if(typeof onOpen === "function") {
  3845. onOpen();
  3846. }
  3847. currentlyOpen = selector;
  3848. }
  3849. };
  3850. /**
  3851. * Opens / closes the chat area.
  3852. */
  3853. my.toggleChat = function() {
  3854. var chatCompleteFunction = Chat.isVisible() ?
  3855. function() {} : function () {
  3856. Chat.scrollChatToBottom();
  3857. $('#chatspace').trigger('shown');
  3858. };
  3859. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  3860. toggle(Chat,
  3861. '#chatspace',
  3862. function () {
  3863. // Request the focus in the nickname field or the chat input field.
  3864. if ($('#nickname').css('visibility') === 'visible') {
  3865. $('#nickinput').focus();
  3866. } else {
  3867. $('#usermsg').focus();
  3868. }
  3869. },
  3870. null,
  3871. Chat.resizeChat,
  3872. null);
  3873. };
  3874. /**
  3875. * Opens / closes the contact list area.
  3876. */
  3877. my.toggleContactList = function () {
  3878. var completeFunction = ContactList.isVisible() ?
  3879. function() {} : function () { $('#contactlist').trigger('shown');};
  3880. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  3881. toggle(ContactList,
  3882. '#contactlist',
  3883. null,
  3884. function() {
  3885. ContactList.setVisualNotification(false);
  3886. },
  3887. null);
  3888. };
  3889. /**
  3890. * Opens / closes the settings menu
  3891. */
  3892. my.toggleSettingsMenu = function() {
  3893. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  3894. toggle(SettingsMenu,
  3895. '#settingsmenu',
  3896. null,
  3897. function() {
  3898. var settings = Settings.getSettings();
  3899. $('#setDisplayName').get(0).value = settings.displayName;
  3900. $('#setEmail').get(0).value = settings.email;
  3901. },
  3902. null);
  3903. };
  3904. /**
  3905. * Returns the size of the side panel.
  3906. */
  3907. my.getPanelSize = function () {
  3908. var availableHeight = window.innerHeight;
  3909. var availableWidth = window.innerWidth;
  3910. var panelWidth = 200;
  3911. if (availableWidth * 0.2 < 200) {
  3912. panelWidth = availableWidth * 0.2;
  3913. }
  3914. return [panelWidth, availableHeight];
  3915. };
  3916. my.isVisible = function() {
  3917. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3918. };
  3919. return my;
  3920. }(PanelToggler || {}));
  3921. module.exports = PanelToggler;
  3922. },{"../toolbars/ToolbarToggler":29,"../util/UIUtil":33,"../videolayout/LargeVideo":35,"../videolayout/VideoLayout":39,"./../../settings/Settings":47,"./chat/Chat":21,"./contactlist/ContactList":25,"./settings/SettingsMenu":26}],21:[function(require,module,exports){
  3923. /* global $, Util, nickname:true */
  3924. var Replacement = require("./Replacement");
  3925. var CommandsProcessor = require("./Commands");
  3926. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3927. var smileys = require("./smileys.json").smileys;
  3928. var NicknameHandler = require("../../util/NicknameHandler");
  3929. var UIUtil = require("../../util/UIUtil");
  3930. var UIEvents = require("../../../../service/UI/UIEvents");
  3931. var notificationInterval = false;
  3932. var unreadMessages = 0;
  3933. /**
  3934. * Shows/hides a visual notification, indicating that a message has arrived.
  3935. */
  3936. function setVisualNotification(show) {
  3937. var unreadMsgElement = document.getElementById('unreadMessages');
  3938. var unreadMsgBottomElement
  3939. = document.getElementById('bottomUnreadMessages');
  3940. var glower = $('#chatButton');
  3941. var bottomGlower = $('#chatBottomButton');
  3942. if (unreadMessages) {
  3943. unreadMsgElement.innerHTML = unreadMessages.toString();
  3944. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3945. ToolbarToggler.dockToolbar(true);
  3946. var chatButtonElement
  3947. = document.getElementById('chatButton').parentNode;
  3948. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3949. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3950. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3951. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3952. unreadMsgElement.setAttribute(
  3953. 'style',
  3954. 'top:' + topIndent +
  3955. '; left:' + leftIndent + ';');
  3956. var chatBottomButtonElement
  3957. = document.getElementById('chatBottomButton').parentNode;
  3958. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3959. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3960. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3961. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3962. unreadMsgBottomElement.setAttribute(
  3963. 'style',
  3964. 'top:' + bottomTopIndent +
  3965. '; left:' + bottomLeftIndent + ';');
  3966. if (!glower.hasClass('icon-chat-simple')) {
  3967. glower.removeClass('icon-chat');
  3968. glower.addClass('icon-chat-simple');
  3969. }
  3970. }
  3971. else {
  3972. unreadMsgElement.innerHTML = '';
  3973. unreadMsgBottomElement.innerHTML = '';
  3974. glower.removeClass('icon-chat-simple');
  3975. glower.addClass('icon-chat');
  3976. }
  3977. if (show && !notificationInterval) {
  3978. notificationInterval = window.setInterval(function () {
  3979. glower.toggleClass('active');
  3980. bottomGlower.toggleClass('active glowing');
  3981. }, 800);
  3982. }
  3983. else if (!show && notificationInterval) {
  3984. window.clearInterval(notificationInterval);
  3985. notificationInterval = false;
  3986. glower.removeClass('active');
  3987. bottomGlower.removeClass('glowing');
  3988. bottomGlower.addClass('active');
  3989. }
  3990. }
  3991. /**
  3992. * Returns the current time in the format it is shown to the user
  3993. * @returns {string}
  3994. */
  3995. function getCurrentTime(stamp) {
  3996. var now = (stamp? new Date(stamp): new Date());
  3997. var hour = now.getHours();
  3998. var minute = now.getMinutes();
  3999. var second = now.getSeconds();
  4000. if(hour.toString().length === 1) {
  4001. hour = '0'+hour;
  4002. }
  4003. if(minute.toString().length === 1) {
  4004. minute = '0'+minute;
  4005. }
  4006. if(second.toString().length === 1) {
  4007. second = '0'+second;
  4008. }
  4009. return hour+':'+minute+':'+second;
  4010. }
  4011. function toggleSmileys()
  4012. {
  4013. var smileys = $('#smileysContainer');
  4014. if(!smileys.is(':visible')) {
  4015. smileys.show("slide", { direction: "down", duration: 300});
  4016. } else {
  4017. smileys.hide("slide", { direction: "down", duration: 300});
  4018. }
  4019. $('#usermsg').focus();
  4020. }
  4021. function addClickFunction(smiley, number) {
  4022. smiley.onclick = function addSmileyToMessage() {
  4023. var usermsg = $('#usermsg');
  4024. var message = usermsg.val();
  4025. message += smileys['smiley' + number];
  4026. usermsg.val(message);
  4027. usermsg.get(0).setSelectionRange(message.length, message.length);
  4028. toggleSmileys();
  4029. usermsg.focus();
  4030. };
  4031. }
  4032. /**
  4033. * Adds the smileys container to the chat
  4034. */
  4035. function addSmileys() {
  4036. var smileysContainer = document.createElement('div');
  4037. smileysContainer.id = 'smileysContainer';
  4038. for(var i = 1; i <= 21; i++) {
  4039. var smileyContainer = document.createElement('div');
  4040. smileyContainer.id = 'smiley' + i;
  4041. smileyContainer.className = 'smileyContainer';
  4042. var smiley = document.createElement('img');
  4043. smiley.src = 'images/smileys/smiley' + i + '.svg';
  4044. smiley.className = 'smiley';
  4045. addClickFunction(smiley, i);
  4046. smileyContainer.appendChild(smiley);
  4047. smileysContainer.appendChild(smileyContainer);
  4048. }
  4049. $("#chatspace").append(smileysContainer);
  4050. }
  4051. /**
  4052. * Resizes the chat conversation.
  4053. */
  4054. function resizeChatConversation() {
  4055. var msgareaHeight = $('#usermsg').outerHeight();
  4056. var chatspace = $('#chatspace');
  4057. var width = chatspace.width();
  4058. var chat = $('#chatconversation');
  4059. var smileys = $('#smileysarea');
  4060. smileys.height(msgareaHeight);
  4061. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  4062. $('#smileysContainer').css('bottom', msgareaHeight);
  4063. chat.width(width - 10);
  4064. chat.height(window.innerHeight - 15 - msgareaHeight);
  4065. }
  4066. /**
  4067. * Chat related user interface.
  4068. */
  4069. var Chat = (function (my) {
  4070. /**
  4071. * Initializes chat related interface.
  4072. */
  4073. my.init = function () {
  4074. if(NicknameHandler.getNickname())
  4075. Chat.setChatConversationMode(true);
  4076. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  4077. function (nickname) {
  4078. Chat.setChatConversationMode(true);
  4079. });
  4080. $('#nickinput').keydown(function (event) {
  4081. if (event.keyCode === 13) {
  4082. event.preventDefault();
  4083. var val = UIUtil.escapeHtml(this.value);
  4084. this.value = '';
  4085. if (!NicknameHandler.getNickname()) {
  4086. NicknameHandler.setNickname(val);
  4087. return;
  4088. }
  4089. }
  4090. });
  4091. $('#usermsg').keydown(function (event) {
  4092. if (event.keyCode === 13) {
  4093. event.preventDefault();
  4094. var value = this.value;
  4095. $('#usermsg').val('').trigger('autosize.resize');
  4096. this.focus();
  4097. var command = new CommandsProcessor(value);
  4098. if(command.isCommand())
  4099. {
  4100. command.processCommand();
  4101. }
  4102. else
  4103. {
  4104. var message = UIUtil.escapeHtml(value);
  4105. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  4106. }
  4107. }
  4108. });
  4109. var onTextAreaResize = function () {
  4110. resizeChatConversation();
  4111. Chat.scrollChatToBottom();
  4112. };
  4113. $('#usermsg').autosize({callback: onTextAreaResize});
  4114. $("#chatspace").bind("shown",
  4115. function () {
  4116. unreadMessages = 0;
  4117. setVisualNotification(false);
  4118. });
  4119. addSmileys();
  4120. };
  4121. /**
  4122. * Appends the given message to the chat conversation.
  4123. */
  4124. my.updateChatConversation = function (from, displayName, message, myjid, stamp) {
  4125. var divClassName = '';
  4126. if (APP.xmpp.myJid() === from) {
  4127. divClassName = "localuser";
  4128. }
  4129. else {
  4130. divClassName = "remoteuser";
  4131. if (!Chat.isVisible()) {
  4132. unreadMessages++;
  4133. UIUtil.playSoundNotification('chatNotification');
  4134. setVisualNotification(true);
  4135. }
  4136. }
  4137. // replace links and smileys
  4138. // Strophe already escapes special symbols on sending,
  4139. // so we escape here only tags to avoid double &amp;
  4140. var escMessage = message.replace(/</g, '&lt;').
  4141. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  4142. var escDisplayName = UIUtil.escapeHtml(displayName);
  4143. message = Replacement.processReplacements(escMessage);
  4144. var messageContainer =
  4145. '<div class="chatmessage">'+
  4146. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  4147. '<div class="username ' + divClassName +'">' + escDisplayName +
  4148. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  4149. '</div>' + '<div class="usermessage">' + message + '</div>' +
  4150. '</div>';
  4151. $('#chatconversation').append(messageContainer);
  4152. $('#chatconversation').animate(
  4153. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  4154. };
  4155. /**
  4156. * Appends error message to the conversation
  4157. * @param errorMessage the received error message.
  4158. * @param originalText the original message.
  4159. */
  4160. my.chatAddError = function(errorMessage, originalText)
  4161. {
  4162. errorMessage = UIUtil.escapeHtml(errorMessage);
  4163. originalText = UIUtil.escapeHtml(originalText);
  4164. $('#chatconversation').append(
  4165. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  4166. (originalText? (' \"'+ originalText + '\"') : "") +
  4167. ' was not sent.' +
  4168. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  4169. $('#chatconversation').animate(
  4170. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  4171. };
  4172. /**
  4173. * Sets the subject to the UI
  4174. * @param subject the subject
  4175. */
  4176. my.chatSetSubject = function(subject)
  4177. {
  4178. if(subject)
  4179. subject = subject.trim();
  4180. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  4181. if(subject === "")
  4182. {
  4183. $("#subject").css({display: "none"});
  4184. }
  4185. else
  4186. {
  4187. $("#subject").css({display: "block"});
  4188. }
  4189. };
  4190. /**
  4191. * Sets the chat conversation mode.
  4192. */
  4193. my.setChatConversationMode = function (isConversationMode) {
  4194. if (isConversationMode) {
  4195. $('#nickname').css({visibility: 'hidden'});
  4196. $('#chatconversation').css({visibility: 'visible'});
  4197. $('#usermsg').css({visibility: 'visible'});
  4198. $('#smileysarea').css({visibility: 'visible'});
  4199. $('#usermsg').focus();
  4200. }
  4201. };
  4202. /**
  4203. * Resizes the chat area.
  4204. */
  4205. my.resizeChat = function () {
  4206. var chatSize = require("../SidePanelToggler").getPanelSize();
  4207. $('#chatspace').width(chatSize[0]);
  4208. $('#chatspace').height(chatSize[1]);
  4209. resizeChatConversation();
  4210. };
  4211. /**
  4212. * Indicates if the chat is currently visible.
  4213. */
  4214. my.isVisible = function () {
  4215. return $('#chatspace').is(":visible");
  4216. };
  4217. /**
  4218. * Shows and hides the window with the smileys
  4219. */
  4220. my.toggleSmileys = toggleSmileys;
  4221. /**
  4222. * Scrolls chat to the bottom.
  4223. */
  4224. my.scrollChatToBottom = function() {
  4225. setTimeout(function () {
  4226. $('#chatconversation').scrollTop(
  4227. $('#chatconversation')[0].scrollHeight);
  4228. }, 5);
  4229. };
  4230. return my;
  4231. }(Chat || {}));
  4232. module.exports = Chat;
  4233. },{"../../../../service/UI/UIEvents":103,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  4234. var UIUtil = require("../../util/UIUtil");
  4235. /**
  4236. * List with supported commands. The keys are the names of the commands and
  4237. * the value is the function that processes the message.
  4238. * @type {{String: function}}
  4239. */
  4240. var commands = {
  4241. "topic" : processTopic
  4242. };
  4243. /**
  4244. * Extracts the command from the message.
  4245. * @param message the received message
  4246. * @returns {string} the command
  4247. */
  4248. function getCommand(message)
  4249. {
  4250. if(message)
  4251. {
  4252. for(var command in commands)
  4253. {
  4254. if(message.indexOf("/" + command) == 0)
  4255. return command;
  4256. }
  4257. }
  4258. return "";
  4259. };
  4260. /**
  4261. * Processes the data for topic command.
  4262. * @param commandArguments the arguments of the topic command.
  4263. */
  4264. function processTopic(commandArguments)
  4265. {
  4266. var topic = UIUtil.escapeHtml(commandArguments);
  4267. APP.xmpp.setSubject(topic);
  4268. }
  4269. /**
  4270. * Constructs new CommandProccessor instance from a message that
  4271. * handles commands received via chat messages.
  4272. * @param message the message
  4273. * @constructor
  4274. */
  4275. function CommandsProcessor(message)
  4276. {
  4277. var command = getCommand(message);
  4278. /**
  4279. * Returns the name of the command.
  4280. * @returns {String} the command
  4281. */
  4282. this.getCommand = function()
  4283. {
  4284. return command;
  4285. };
  4286. var messageArgument = message.substr(command.length + 2);
  4287. /**
  4288. * Returns the arguments of the command.
  4289. * @returns {string}
  4290. */
  4291. this.getArgument = function()
  4292. {
  4293. return messageArgument;
  4294. };
  4295. }
  4296. /**
  4297. * Checks whether this instance is valid command or not.
  4298. * @returns {boolean}
  4299. */
  4300. CommandsProcessor.prototype.isCommand = function()
  4301. {
  4302. if(this.getCommand())
  4303. return true;
  4304. return false;
  4305. };
  4306. /**
  4307. * Processes the command.
  4308. */
  4309. CommandsProcessor.prototype.processCommand = function()
  4310. {
  4311. if(!this.isCommand())
  4312. return;
  4313. commands[this.getCommand()](this.getArgument());
  4314. };
  4315. module.exports = CommandsProcessor;
  4316. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  4317. var Smileys = require("./smileys.json");
  4318. /**
  4319. * Processes links and smileys in "body"
  4320. */
  4321. function processReplacements(body)
  4322. {
  4323. //make links clickable
  4324. body = linkify(body);
  4325. //add smileys
  4326. body = smilify(body);
  4327. return body;
  4328. }
  4329. /**
  4330. * Finds and replaces all links in the links in "body"
  4331. * with their <a href=""></a>
  4332. */
  4333. function linkify(inputText)
  4334. {
  4335. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  4336. //URLs starting with http://, https://, or ftp://
  4337. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  4338. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  4339. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  4340. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  4341. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  4342. //Change email addresses to mailto:: links.
  4343. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  4344. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  4345. return replacedText;
  4346. }
  4347. /**
  4348. * Replaces common smiley strings with images
  4349. */
  4350. function smilify(body)
  4351. {
  4352. if(!body) {
  4353. return body;
  4354. }
  4355. var regexs = Smileys["regexs"];
  4356. for(var smiley in regexs) {
  4357. if(regexs.hasOwnProperty(smiley)) {
  4358. body = body.replace(regexs[smiley],
  4359. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4360. }
  4361. }
  4362. return body;
  4363. }
  4364. module.exports = {
  4365. processReplacements: processReplacements,
  4366. linkify: linkify
  4367. };
  4368. },{"./smileys.json":24}],24:[function(require,module,exports){
  4369. module.exports={
  4370. "smileys": {
  4371. "smiley1": ":)",
  4372. "smiley2": ":(",
  4373. "smiley3": ":D",
  4374. "smiley4": "(y)",
  4375. "smiley5": " :P",
  4376. "smiley6": "(wave)",
  4377. "smiley7": "(blush)",
  4378. "smiley8": "(chuckle)",
  4379. "smiley9": "(shocked)",
  4380. "smiley10": ":*",
  4381. "smiley11": "(n)",
  4382. "smiley12": "(search)",
  4383. "smiley13": " <3",
  4384. "smiley14": "(oops)",
  4385. "smiley15": "(angry)",
  4386. "smiley16": "(angel)",
  4387. "smiley17": "(sick)",
  4388. "smiley18": ";(",
  4389. "smiley19": "(bomb)",
  4390. "smiley20": "(clap)",
  4391. "smiley21": " ;)"
  4392. },
  4393. "regexs": {
  4394. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4395. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4396. "smiley1": /(:-\)|:\))/gi,
  4397. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4398. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4399. "smiley6": /(\(wave\))/gi,
  4400. "smiley7": /(\(blush\))/gi,
  4401. "smiley8": /(\(chuckle\))/gi,
  4402. "smiley9": /(:-0|\(shocked\))/gi,
  4403. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4404. "smiley11": /(\(n\))/gi,
  4405. "smiley12": /(\(search\))/g,
  4406. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4407. "smiley14": /(\(oops\))/gi,
  4408. "smiley15": /(\(angry\))/gi,
  4409. "smiley16": /(\(angel\))/gi,
  4410. "smiley17": /(\(sick\))/gi,
  4411. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4412. "smiley19": /(\(bomb\))/gi,
  4413. "smiley20": /(\(clap\))/gi,
  4414. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4415. }
  4416. }
  4417. },{}],25:[function(require,module,exports){
  4418. var numberOfContacts = 0;
  4419. var notificationInterval;
  4420. /**
  4421. * Updates the number of participants in the contact list button and sets
  4422. * the glow
  4423. * @param delta indicates whether a new user has joined (1) or someone has
  4424. * left(-1)
  4425. */
  4426. function updateNumberOfParticipants(delta) {
  4427. numberOfContacts += delta;
  4428. if (numberOfContacts === 1) {
  4429. // when the user is alone we don't show the number of participants
  4430. $("#numberOfParticipants").text('');
  4431. ContactList.setVisualNotification(false);
  4432. } else if (numberOfContacts > 1) {
  4433. ContactList.setVisualNotification(!ContactList.isVisible());
  4434. $("#numberOfParticipants").text(numberOfContacts);
  4435. } else {
  4436. console.error("Invalid number of participants: " + numberOfContacts);
  4437. }
  4438. }
  4439. /**
  4440. * Creates the avatar element.
  4441. *
  4442. * @return the newly created avatar element
  4443. */
  4444. function createAvatar(id) {
  4445. var avatar = document.createElement('img');
  4446. avatar.className = "icon-avatar avatar";
  4447. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4448. return avatar;
  4449. }
  4450. /**
  4451. * Creates the display name paragraph.
  4452. *
  4453. * @param displayName the display name to set
  4454. */
  4455. function createDisplayNameParagraph(key, displayName) {
  4456. var p = document.createElement('p');
  4457. if(displayName)
  4458. p.innerText = displayName;
  4459. else if(key)
  4460. {
  4461. p.setAttribute("data-i18n",key);
  4462. p.innerText = APP.translation.translateString(key);
  4463. }
  4464. return p;
  4465. }
  4466. function stopGlowing(glower) {
  4467. window.clearInterval(notificationInterval);
  4468. notificationInterval = false;
  4469. glower.removeClass('glowing');
  4470. if (!ContactList.isVisible()) {
  4471. glower.removeClass('active');
  4472. }
  4473. }
  4474. /**
  4475. * Contact list.
  4476. */
  4477. var ContactList = {
  4478. /**
  4479. * Indicates if the chat is currently visible.
  4480. *
  4481. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4482. * otherwise
  4483. */
  4484. isVisible: function () {
  4485. return $('#contactlist').is(":visible");
  4486. },
  4487. /**
  4488. * Adds a contact for the given peerJid if such doesn't yet exist.
  4489. *
  4490. * @param peerJid the peerJid corresponding to the contact
  4491. * @param id the user's email or userId used to get the user's avatar
  4492. */
  4493. ensureAddContact: function (peerJid, id) {
  4494. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4495. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  4496. if (!contact || contact.length <= 0)
  4497. ContactList.addContact(peerJid, id);
  4498. },
  4499. /**
  4500. * Adds a contact for the given peer jid.
  4501. *
  4502. * @param peerJid the jid of the contact to add
  4503. * @param id the email or userId of the user
  4504. */
  4505. addContact: function (peerJid, id) {
  4506. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4507. var contactlist = $('#contacts');
  4508. var newContact = document.createElement('li');
  4509. newContact.id = resourceJid;
  4510. newContact.className = "clickable";
  4511. newContact.onclick = function (event) {
  4512. if (event.currentTarget.className === "clickable") {
  4513. $(ContactList).trigger('contactclicked', [peerJid]);
  4514. }
  4515. };
  4516. newContact.appendChild(createAvatar(id));
  4517. newContact.appendChild(createDisplayNameParagraph("participant"));
  4518. if (resourceJid === APP.xmpp.myResource()) {
  4519. contactlist.prepend(newContact);
  4520. }
  4521. else {
  4522. contactlist.append(newContact);
  4523. }
  4524. updateNumberOfParticipants(1);
  4525. },
  4526. /**
  4527. * Removes a contact for the given peer jid.
  4528. *
  4529. * @param peerJid the peerJid corresponding to the contact to remove
  4530. */
  4531. removeContact: function (peerJid) {
  4532. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4533. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  4534. if (contact && contact.length > 0) {
  4535. var contactlist = $('#contactlist>ul');
  4536. contactlist.get(0).removeChild(contact.get(0));
  4537. updateNumberOfParticipants(-1);
  4538. }
  4539. },
  4540. setVisualNotification: function (show, stopGlowingIn) {
  4541. var glower = $('#contactListButton');
  4542. if (show && !notificationInterval) {
  4543. notificationInterval = window.setInterval(function () {
  4544. glower.toggleClass('active glowing');
  4545. }, 800);
  4546. }
  4547. else if (!show && notificationInterval) {
  4548. stopGlowing(glower);
  4549. }
  4550. if (stopGlowingIn) {
  4551. setTimeout(function () {
  4552. stopGlowing(glower);
  4553. }, stopGlowingIn);
  4554. }
  4555. },
  4556. setClickable: function (resourceJid, isClickable) {
  4557. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  4558. if (isClickable) {
  4559. contact.addClass('clickable');
  4560. } else {
  4561. contact.removeClass('clickable');
  4562. }
  4563. },
  4564. onDisplayNameChange: function (peerJid, displayName) {
  4565. if (peerJid === 'localVideoContainer')
  4566. peerJid = APP.xmpp.myJid();
  4567. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4568. var contactName = $('#contacts #' + resourceJid + '>p');
  4569. if (contactName && displayName && displayName.length > 0)
  4570. contactName.html(displayName);
  4571. },
  4572. userAvatarChanged: function (resourceJid, contactListUrl) {
  4573. // set the avatar in the contact list
  4574. var contact = $('#' + resourceJid + '>img');
  4575. if (contact && contact.length > 0) {
  4576. contact.get(0).src = contactListUrl;
  4577. }
  4578. }
  4579. };
  4580. module.exports = ContactList;
  4581. },{}],26:[function(require,module,exports){
  4582. var Avatar = require("../../avatar/Avatar");
  4583. var Settings = require("./../../../settings/Settings");
  4584. var UIUtil = require("../../util/UIUtil");
  4585. var languages = require("../../../../service/translation/languages");
  4586. function generateLanguagesSelectBox()
  4587. {
  4588. var currentLang = APP.translation.getCurrentLanguage();
  4589. var html = "<select id=\"languages_selectbox\">";
  4590. var langArray = languages.getLanguages();
  4591. for(var i = 0; i < langArray.length; i++)
  4592. {
  4593. var lang = langArray[i];
  4594. html += "<option ";
  4595. if(lang === currentLang)
  4596. html += "selected ";
  4597. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4598. html += "</option>";
  4599. }
  4600. return html + "</select>";
  4601. }
  4602. var SettingsMenu = {
  4603. init: function () {
  4604. $("#startMutedOptions").before(generateLanguagesSelectBox());
  4605. APP.translation.translateElement($("#languages_selectbox"));
  4606. $('#settingsmenu>input').keyup(function(event){
  4607. if(event.keyCode === 13) {//enter
  4608. SettingsMenu.update();
  4609. }
  4610. });
  4611. if(APP.xmpp.isModerator())
  4612. {
  4613. $("#startMutedOptions").css("display", "block");
  4614. }
  4615. else
  4616. {
  4617. $("#startMutedOptions").css("display", "none");
  4618. }
  4619. $("#updateSettings").click(function () {
  4620. SettingsMenu.update();
  4621. });
  4622. },
  4623. onRoleChanged: function () {
  4624. if(APP.xmpp.isModerator())
  4625. {
  4626. $("#startMutedOptions").css("display", "block");
  4627. }
  4628. else
  4629. {
  4630. $("#startMutedOptions").css("display", "none");
  4631. }
  4632. },
  4633. setStartMuted: function (audio, video) {
  4634. $("#startAudioMuted").attr("checked", audio);
  4635. $("#startVideoMuted").attr("checked", video);
  4636. },
  4637. update: function() {
  4638. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4639. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4640. if(newDisplayName) {
  4641. var displayName = Settings.setDisplayName(newDisplayName);
  4642. APP.xmpp.addToPresence("displayName", displayName, true);
  4643. }
  4644. var language = $("#languages_selectbox").val();
  4645. APP.translation.setLanguage(language);
  4646. Settings.setLanguage(language);
  4647. APP.xmpp.addToPresence("email", newEmail);
  4648. var email = Settings.setEmail(newEmail);
  4649. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  4650. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  4651. APP.xmpp.addToPresence("startMuted",
  4652. [startAudioMuted, startVideoMuted]);
  4653. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4654. },
  4655. isVisible: function() {
  4656. return $('#settingsmenu').is(':visible');
  4657. },
  4658. setDisplayName: function(newDisplayName) {
  4659. var displayName = Settings.setDisplayName(newDisplayName);
  4660. $('#setDisplayName').get(0).value = displayName;
  4661. },
  4662. onDisplayNameChange: function(peerJid, newDisplayName) {
  4663. if(peerJid === 'localVideoContainer' ||
  4664. peerJid === APP.xmpp.myJid()) {
  4665. this.setDisplayName(newDisplayName);
  4666. }
  4667. },
  4668. changeAvatar: function (thumbUrl) {
  4669. $('#avatar').get(0).src = thumbUrl;
  4670. }
  4671. };
  4672. module.exports = SettingsMenu;
  4673. },{"../../../../service/translation/languages":108,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  4674. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4675. var buttonHandlers = {
  4676. "bottom_toolbar_contact_list": function () {
  4677. BottomToolbar.toggleContactList();
  4678. },
  4679. "bottom_toolbar_film_strip": function () {
  4680. BottomToolbar.toggleFilmStrip();
  4681. },
  4682. "bottom_toolbar_chat": function () {
  4683. BottomToolbar.toggleChat();
  4684. }
  4685. };
  4686. var BottomToolbar = (function (my) {
  4687. my.init = function () {
  4688. for(var k in buttonHandlers)
  4689. $("#" + k).click(buttonHandlers[k]);
  4690. };
  4691. my.toggleChat = function() {
  4692. PanelToggler.toggleChat();
  4693. };
  4694. my.toggleContactList = function() {
  4695. PanelToggler.toggleContactList();
  4696. };
  4697. my.toggleFilmStrip = function() {
  4698. var filmstrip = $("#remoteVideos");
  4699. filmstrip.toggleClass("hidden");
  4700. };
  4701. $(document).bind("remotevideo.resized", function (event, width, height) {
  4702. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4703. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4704. });
  4705. return my;
  4706. }(BottomToolbar || {}));
  4707. module.exports = BottomToolbar;
  4708. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  4709. /* global APP,$, buttonClick, config, lockRoom,
  4710. setSharedKey, Util */
  4711. var messageHandler = require("../util/MessageHandler");
  4712. var BottomToolbar = require("./BottomToolbar");
  4713. var Prezi = require("../prezi/Prezi");
  4714. var Etherpad = require("../etherpad/Etherpad");
  4715. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4716. var Authentication = require("../authentication/Authentication");
  4717. var UIUtil = require("../util/UIUtil");
  4718. var AuthenticationEvents
  4719. = require("../../../service/authentication/AuthenticationEvents");
  4720. var roomUrl = null;
  4721. var sharedKey = '';
  4722. var UI = null;
  4723. var buttonHandlers =
  4724. {
  4725. "toolbar_button_mute": function () {
  4726. return APP.UI.toggleAudio();
  4727. },
  4728. "toolbar_button_camera": function () {
  4729. return APP.UI.toggleVideo();
  4730. },
  4731. /*"toolbar_button_authentication": function () {
  4732. return Toolbar.authenticateClicked();
  4733. },*/
  4734. "toolbar_button_record": function () {
  4735. return toggleRecording();
  4736. },
  4737. "toolbar_button_security": function () {
  4738. return Toolbar.openLockDialog();
  4739. },
  4740. "toolbar_button_link": function () {
  4741. return Toolbar.openLinkDialog();
  4742. },
  4743. "toolbar_button_chat": function () {
  4744. return BottomToolbar.toggleChat();
  4745. },
  4746. "toolbar_button_prezi": function () {
  4747. return Prezi.openPreziDialog();
  4748. },
  4749. "toolbar_button_etherpad": function () {
  4750. return Etherpad.toggleEtherpad(0);
  4751. },
  4752. "toolbar_button_desktopsharing": function () {
  4753. return APP.desktopsharing.toggleScreenSharing();
  4754. },
  4755. "toolbar_button_fullScreen": function()
  4756. {
  4757. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4758. return Toolbar.toggleFullScreen();
  4759. },
  4760. "toolbar_button_sip": function () {
  4761. return callSipButtonClicked();
  4762. },
  4763. "toolbar_button_dialpad": function () {
  4764. return dialpadButtonClicked();
  4765. },
  4766. "toolbar_button_settings": function () {
  4767. PanelToggler.toggleSettingsMenu();
  4768. },
  4769. "toolbar_button_hangup": function () {
  4770. return hangup();
  4771. },
  4772. "toolbar_button_login": function () {
  4773. Toolbar.authenticateClicked();
  4774. },
  4775. "toolbar_button_logout": function () {
  4776. // Ask for confirmation
  4777. messageHandler.openTwoButtonDialog(
  4778. "dialog.logoutTitle",
  4779. null,
  4780. "dialog.logoutQuestion",
  4781. null,
  4782. false,
  4783. "dialog.Yes",
  4784. function (evt, yes) {
  4785. if (yes) {
  4786. APP.xmpp.logout(function (url) {
  4787. if (url) {
  4788. window.location.href = url;
  4789. } else {
  4790. hangup();
  4791. }
  4792. });
  4793. }
  4794. });
  4795. }
  4796. };
  4797. function hangup() {
  4798. APP.xmpp.disposeConference();
  4799. if(config.enableWelcomePage)
  4800. {
  4801. setTimeout(function()
  4802. {
  4803. window.localStorage.welcomePageDisabled = false;
  4804. window.location.pathname = "/";
  4805. }, 10000);
  4806. }
  4807. var title = APP.translation.generateTranslationHTML(
  4808. "dialog.sessTerminated");
  4809. var msg = APP.translation.generateTranslationHTML(
  4810. "dialog.hungUp");
  4811. var button = APP.translation.generateTranslationHTML(
  4812. "dialog.joinAgain");
  4813. var buttons = [];
  4814. buttons.push({title: button, value: true});
  4815. UI.messageHandler.openDialog(
  4816. title,
  4817. msg,
  4818. true,
  4819. buttons,
  4820. function(event, value, message, formVals)
  4821. {
  4822. window.location.reload();
  4823. return false;
  4824. }
  4825. );
  4826. }
  4827. /**
  4828. * Starts or stops the recording for the conference.
  4829. */
  4830. function toggleRecording() {
  4831. APP.xmpp.toggleRecording(function (callback) {
  4832. var msg = APP.translation.generateTranslationHTML(
  4833. "dialog.recordingToken");
  4834. var token = APP.translation.translateString("dialog.token");
  4835. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4836. '<h2>' + msg + '</h2>' +
  4837. '<input name="recordingToken" type="text" ' +
  4838. ' data-i18n="[placeholder]dialog.token" ' +
  4839. 'placeholder="' + token + '" autofocus>',
  4840. false,
  4841. "dialog.Save",
  4842. function (e, v, m, f) {
  4843. if (v) {
  4844. var token = f.recordingToken;
  4845. if (token) {
  4846. callback(UIUtil.escapeHtml(token));
  4847. }
  4848. }
  4849. },
  4850. null,
  4851. function () { },
  4852. ':input:first'
  4853. );
  4854. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4855. }
  4856. /**
  4857. * Locks / unlocks the room.
  4858. */
  4859. function lockRoom(lock) {
  4860. var currentSharedKey = '';
  4861. if (lock)
  4862. currentSharedKey = sharedKey;
  4863. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4864. // password is required
  4865. if (sharedKey)
  4866. {
  4867. console.log('set room password');
  4868. Toolbar.lockLockButton();
  4869. }
  4870. else
  4871. {
  4872. console.log('removed room password');
  4873. Toolbar.unlockLockButton();
  4874. }
  4875. }, function (err) {
  4876. console.warn('setting password failed', err);
  4877. messageHandler.showError("dialog.lockTitle",
  4878. "dialog.lockMessage");
  4879. Toolbar.setSharedKey('');
  4880. }, function () {
  4881. console.warn('room passwords not supported');
  4882. messageHandler.showError("dialog.warning",
  4883. "dialog.passwordNotSupported");
  4884. Toolbar.setSharedKey('');
  4885. });
  4886. };
  4887. /**
  4888. * Invite participants to conference.
  4889. */
  4890. function inviteParticipants() {
  4891. if (roomUrl === null)
  4892. return;
  4893. var sharedKeyText = "";
  4894. if (sharedKey && sharedKey.length > 0) {
  4895. sharedKeyText =
  4896. APP.translation.translateString("email.sharedKey",
  4897. {sharedKey: sharedKey});
  4898. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4899. }
  4900. var supportedBrowsers = "Chromium, Google Chrome " +
  4901. APP.translation.translateString("email.and") + " Opera";
  4902. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4903. var subject = APP.translation.translateString("email.subject",
  4904. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4905. var body = APP.translation.translateString("email.body",
  4906. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4907. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4908. body = body.replace(/\n/g, "%0D%0A");
  4909. if (window.localStorage.displayname) {
  4910. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4911. }
  4912. if (interfaceConfig.INVITATION_POWERED_BY) {
  4913. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4914. }
  4915. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4916. }
  4917. function dialpadButtonClicked()
  4918. {
  4919. //TODO show the dialpad window
  4920. }
  4921. function callSipButtonClicked()
  4922. {
  4923. var defaultNumber
  4924. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4925. var sipMsg = APP.translation.generateTranslationHTML(
  4926. "dialog.sipMsg");
  4927. messageHandler.openTwoButtonDialog(null, null, null,
  4928. '<h2>' + sipMsg + '</h2>' +
  4929. '<input name="sipNumber" type="text"' +
  4930. ' value="' + defaultNumber + '" autofocus>',
  4931. false,
  4932. "dialog.Dial",
  4933. function (e, v, m, f) {
  4934. if (v) {
  4935. var numberInput = f.sipNumber;
  4936. if (numberInput) {
  4937. APP.xmpp.dial(
  4938. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4939. }
  4940. }
  4941. },
  4942. null, null, ':input:first'
  4943. );
  4944. }
  4945. var Toolbar = (function (my) {
  4946. my.init = function (ui) {
  4947. for(var k in buttonHandlers)
  4948. $("#" + k).click(buttonHandlers[k]);
  4949. UI = ui;
  4950. // Update login info
  4951. APP.xmpp.addListener(
  4952. AuthenticationEvents.IDENTITY_UPDATED,
  4953. function (authenticationEnabled, userIdentity) {
  4954. var loggedIn = false;
  4955. if (userIdentity) {
  4956. loggedIn = true;
  4957. }
  4958. Toolbar.showAuthenticateButton(authenticationEnabled);
  4959. if (authenticationEnabled) {
  4960. Toolbar.setAuthenticatedIdentity(userIdentity);
  4961. Toolbar.showLoginButton(!loggedIn);
  4962. Toolbar.showLogoutButton(loggedIn);
  4963. }
  4964. }
  4965. );
  4966. },
  4967. /**
  4968. * Sets shared key
  4969. * @param sKey the shared key
  4970. */
  4971. my.setSharedKey = function (sKey) {
  4972. sharedKey = sKey;
  4973. };
  4974. my.authenticateClicked = function () {
  4975. Authentication.focusAuthenticationWindow();
  4976. if (!APP.xmpp.isExternalAuthEnabled()) {
  4977. Authentication.xmppAuthenticate();
  4978. return;
  4979. }
  4980. // Get authentication URL
  4981. if (!APP.xmpp.getMUCJoined()) {
  4982. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4983. // If conference has not been started yet - redirect to login page
  4984. window.location.href = url;
  4985. });
  4986. } else {
  4987. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4988. // Otherwise - open popup with authentication URL
  4989. var authenticationWindow = Authentication.createAuthenticationWindow(
  4990. function () {
  4991. // On popup closed - retry room allocation
  4992. APP.xmpp.allocateConferenceFocus(
  4993. APP.UI.getRoomName(),
  4994. function () { console.info("AUTH DONE"); }
  4995. );
  4996. }, url);
  4997. if (!authenticationWindow) {
  4998. messageHandler.openMessageDialog(
  4999. null, "dialog.popupError");
  5000. }
  5001. });
  5002. }
  5003. };
  5004. /**
  5005. * Updates the room invite url.
  5006. */
  5007. my.updateRoomUrl = function (newRoomUrl) {
  5008. roomUrl = newRoomUrl;
  5009. // If the invite dialog has been already opened we update the information.
  5010. var inviteLink = document.getElementById('inviteLinkRef');
  5011. if (inviteLink) {
  5012. inviteLink.value = roomUrl;
  5013. inviteLink.select();
  5014. $('#inviteLinkRef').parent()
  5015. .find('button[value=true]').prop('disabled', false);
  5016. }
  5017. };
  5018. /**
  5019. * Disables and enables some of the buttons.
  5020. */
  5021. my.setupButtonsFromConfig = function () {
  5022. if (config.disablePrezi)
  5023. {
  5024. $("#prezi_button").css({display: "none"});
  5025. }
  5026. };
  5027. /**
  5028. * Opens the lock room dialog.
  5029. */
  5030. my.openLockDialog = function () {
  5031. // Only the focus is able to set a shared key.
  5032. if (!APP.xmpp.isModerator()) {
  5033. if (sharedKey) {
  5034. messageHandler.openMessageDialog(null,
  5035. "dialog.passwordError");
  5036. } else {
  5037. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  5038. }
  5039. } else {
  5040. if (sharedKey) {
  5041. messageHandler.openTwoButtonDialog(null, null,
  5042. "dialog.passwordCheck",
  5043. null,
  5044. false,
  5045. "dialog.Remove",
  5046. function (e, v) {
  5047. if (v) {
  5048. Toolbar.setSharedKey('');
  5049. lockRoom(false);
  5050. }
  5051. });
  5052. } else {
  5053. var msg = APP.translation.generateTranslationHTML(
  5054. "dialog.passwordMsg");
  5055. var yourPassword = APP.translation.translateString(
  5056. "dialog.yourPassword");
  5057. messageHandler.openTwoButtonDialog(null, null, null,
  5058. '<h2>' + msg + '</h2>' +
  5059. '<input name="lockKey" type="text"' +
  5060. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  5061. 'placeholder="' + yourPassword + '" autofocus>',
  5062. false,
  5063. "dialog.Save",
  5064. function (e, v, m, f) {
  5065. if (v) {
  5066. var lockKey = f.lockKey;
  5067. if (lockKey) {
  5068. Toolbar.setSharedKey(
  5069. UIUtil.escapeHtml(lockKey));
  5070. lockRoom(true);
  5071. }
  5072. }
  5073. },
  5074. null, null, 'input:first'
  5075. );
  5076. }
  5077. }
  5078. };
  5079. /**
  5080. * Opens the invite link dialog.
  5081. */
  5082. my.openLinkDialog = function () {
  5083. var inviteAttreibutes;
  5084. if (roomUrl === null) {
  5085. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  5086. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  5087. } else {
  5088. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  5089. }
  5090. messageHandler.openTwoButtonDialog("dialog.shareLink",
  5091. null, null,
  5092. '<input id="inviteLinkRef" type="text" ' +
  5093. inviteAttreibutes + ' onclick="this.select();" readonly>',
  5094. false,
  5095. "dialog.Invite",
  5096. function (e, v) {
  5097. if (v) {
  5098. if (roomUrl) {
  5099. inviteParticipants();
  5100. }
  5101. }
  5102. },
  5103. function (event) {
  5104. if (roomUrl) {
  5105. document.getElementById('inviteLinkRef').select();
  5106. } else {
  5107. if (event && event.target)
  5108. $(event.target)
  5109. .find('button[value=true]').prop('disabled', true);
  5110. }
  5111. }
  5112. );
  5113. };
  5114. /**
  5115. * Opens the settings dialog.
  5116. * FIXME: not used ?
  5117. */
  5118. my.openSettingsDialog = function () {
  5119. var settings1 = APP.translation.generateTranslationHTML(
  5120. "dialog.settings1");
  5121. var settings2 = APP.translation.generateTranslationHTML(
  5122. "dialog.settings2");
  5123. var settings3 = APP.translation.generateTranslationHTML(
  5124. "dialog.settings3");
  5125. var yourPassword = APP.translation.translateString(
  5126. "dialog.yourPassword");
  5127. messageHandler.openTwoButtonDialog(null,
  5128. '<h2>' + settings1 + '</h2>' +
  5129. '<input type="checkbox" id="initMuted">' +
  5130. settings2 + '<br/>' +
  5131. '<input type="checkbox" id="requireNicknames">' +
  5132. settings3 +
  5133. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  5134. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  5135. null,
  5136. null,
  5137. false,
  5138. "dialog.Save",
  5139. function () {
  5140. document.getElementById('lockKey').focus();
  5141. },
  5142. function (e, v) {
  5143. if (v) {
  5144. if ($('#initMuted').is(":checked")) {
  5145. // it is checked
  5146. }
  5147. if ($('#requireNicknames').is(":checked")) {
  5148. // it is checked
  5149. }
  5150. /*
  5151. var lockKey = document.getElementById('lockKey');
  5152. if (lockKey.value) {
  5153. setSharedKey(lockKey.value);
  5154. lockRoom(true);
  5155. }
  5156. */
  5157. }
  5158. }
  5159. );
  5160. };
  5161. /**
  5162. * Toggles the application in and out of full screen mode
  5163. * (a.k.a. presentation mode in Chrome).
  5164. */
  5165. my.toggleFullScreen = function () {
  5166. var fsElement = document.documentElement;
  5167. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  5168. //Enter Full Screen
  5169. if (fsElement.mozRequestFullScreen) {
  5170. fsElement.mozRequestFullScreen();
  5171. }
  5172. else {
  5173. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  5174. }
  5175. } else {
  5176. //Exit Full Screen
  5177. if (document.mozCancelFullScreen) {
  5178. document.mozCancelFullScreen();
  5179. } else {
  5180. document.webkitCancelFullScreen();
  5181. }
  5182. }
  5183. };
  5184. /**
  5185. * Unlocks the lock button state.
  5186. */
  5187. my.unlockLockButton = function () {
  5188. if ($("#lockIcon").hasClass("icon-security-locked"))
  5189. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5190. };
  5191. /**
  5192. * Updates the lock button state to locked.
  5193. */
  5194. my.lockLockButton = function () {
  5195. if ($("#lockIcon").hasClass("icon-security"))
  5196. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5197. };
  5198. /**
  5199. * Shows or hides authentication button
  5200. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  5201. */
  5202. my.showAuthenticateButton = function (show) {
  5203. if (show) {
  5204. $('#authentication').css({display: "inline"});
  5205. }
  5206. else {
  5207. $('#authentication').css({display: "none"});
  5208. }
  5209. };
  5210. // Shows or hides the 'recording' button.
  5211. my.showRecordingButton = function (show) {
  5212. if (!config.enableRecording) {
  5213. return;
  5214. }
  5215. if (show) {
  5216. $('#recording').css({display: "inline"});
  5217. }
  5218. else {
  5219. $('#recording').css({display: "none"});
  5220. }
  5221. };
  5222. // Sets the state of the recording button
  5223. my.setRecordingButtonState = function (isRecording) {
  5224. var selector = $('#recordButton');
  5225. if (isRecording) {
  5226. selector.removeClass("icon-recEnable");
  5227. selector.addClass("icon-recEnable active");
  5228. } else {
  5229. selector.removeClass("icon-recEnable active");
  5230. selector.addClass("icon-recEnable");
  5231. }
  5232. };
  5233. // Shows or hides SIP calls button
  5234. my.showSipCallButton = function (show) {
  5235. if (APP.xmpp.isSipGatewayEnabled() && show) {
  5236. $('#sipCallButton').css({display: "inline-block"});
  5237. } else {
  5238. $('#sipCallButton').css({display: "none"});
  5239. }
  5240. };
  5241. // Shows or hides the dialpad button
  5242. my.showDialPadButton = function (show) {
  5243. if (show) {
  5244. $('#dialPadButton').css({display: "inline-block"});
  5245. } else {
  5246. $('#dialPadButton').css({display: "none"});
  5247. }
  5248. };
  5249. /**
  5250. * Displays user authenticated identity name(login).
  5251. * @param authIdentity identity name to be displayed.
  5252. */
  5253. my.setAuthenticatedIdentity = function (authIdentity) {
  5254. if (authIdentity) {
  5255. var selector = $('#toolbar_auth_identity');
  5256. selector.css({display: "list-item"});
  5257. selector.text(authIdentity);
  5258. } else {
  5259. $('#toolbar_auth_identity').css({display: "none"});
  5260. }
  5261. };
  5262. /**
  5263. * Shows/hides login button.
  5264. * @param show <tt>true</tt> to show
  5265. */
  5266. my.showLoginButton = function (show) {
  5267. if (show) {
  5268. $('#toolbar_button_login').css({display: "list-item"});
  5269. } else {
  5270. $('#toolbar_button_login').css({display: "none"});
  5271. }
  5272. };
  5273. /**
  5274. * Shows/hides logout button.
  5275. * @param show <tt>true</tt> to show
  5276. */
  5277. my.showLogoutButton = function (show) {
  5278. if (show) {
  5279. $('#toolbar_button_logout').css({display: "list-item"});
  5280. } else {
  5281. $('#toolbar_button_logout').css({display: "none"});
  5282. }
  5283. };
  5284. /**
  5285. * Sets the state of the button. The button has blue glow if desktop
  5286. * streaming is active.
  5287. * @param active the state of the desktop streaming.
  5288. */
  5289. my.changeDesktopSharingButtonState = function (active) {
  5290. var button = $("#desktopsharing > a");
  5291. if (active)
  5292. {
  5293. button.addClass("glow");
  5294. }
  5295. else
  5296. {
  5297. button.removeClass("glow");
  5298. }
  5299. };
  5300. return my;
  5301. }(Toolbar || {}));
  5302. module.exports = Toolbar;
  5303. },{"../../../service/authentication/AuthenticationEvents":104,"../authentication/Authentication":14,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../side_pannels/SidePanelToggler":20,"../util/MessageHandler":31,"../util/UIUtil":33,"./BottomToolbar":27}],29:[function(require,module,exports){
  5304. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  5305. var toolbarTimeoutObject,
  5306. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  5307. function showDesktopSharingButton() {
  5308. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  5309. $('#desktopsharing').css({display: "inline"});
  5310. } else {
  5311. $('#desktopsharing').css({display: "none"});
  5312. }
  5313. }
  5314. /**
  5315. * Hides the toolbar.
  5316. */
  5317. function hideToolbar() {
  5318. if(config.alwaysVisibleToolbar)
  5319. return;
  5320. var header = $("#header"),
  5321. bottomToolbar = $("#bottomToolbar");
  5322. var isToolbarHover = false;
  5323. header.find('*').each(function () {
  5324. var id = $(this).attr('id');
  5325. if ($("#" + id + ":hover").length > 0) {
  5326. isToolbarHover = true;
  5327. }
  5328. });
  5329. if ($("#bottomToolbar:hover").length > 0) {
  5330. isToolbarHover = true;
  5331. }
  5332. clearTimeout(toolbarTimeoutObject);
  5333. toolbarTimeoutObject = null;
  5334. if (!isToolbarHover) {
  5335. header.hide("slide", { direction: "up", duration: 300});
  5336. $('#subject').animate({top: "-=40"}, 300);
  5337. if ($("#remoteVideos").hasClass("hidden")) {
  5338. bottomToolbar.hide(
  5339. "slide", {direction: "right", duration: 300});
  5340. }
  5341. }
  5342. else {
  5343. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5344. }
  5345. }
  5346. var ToolbarToggler = {
  5347. /**
  5348. * Shows the main toolbar.
  5349. */
  5350. showToolbar: function () {
  5351. var header = $("#header"),
  5352. bottomToolbar = $("#bottomToolbar");
  5353. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  5354. header.show("slide", { direction: "up", duration: 300});
  5355. $('#subject').animate({top: "+=40"}, 300);
  5356. if (!bottomToolbar.is(":visible")) {
  5357. bottomToolbar.show(
  5358. "slide", {direction: "right", duration: 300});
  5359. }
  5360. if (toolbarTimeoutObject) {
  5361. clearTimeout(toolbarTimeoutObject);
  5362. toolbarTimeoutObject = null;
  5363. }
  5364. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5365. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  5366. }
  5367. if (APP.xmpp.isModerator())
  5368. {
  5369. // TODO: Enable settings functionality.
  5370. // Need to uncomment the settings button in index.html.
  5371. // $('#settingsButton').css({visibility:"visible"});
  5372. }
  5373. // Show/hide desktop sharing button
  5374. showDesktopSharingButton();
  5375. },
  5376. /**
  5377. * Docks/undocks the toolbar.
  5378. *
  5379. * @param isDock indicates what operation to perform
  5380. */
  5381. dockToolbar: function (isDock) {
  5382. if (isDock) {
  5383. // First make sure the toolbar is shown.
  5384. if (!$('#header').is(':visible')) {
  5385. this.showToolbar();
  5386. }
  5387. // Then clear the time out, to dock the toolbar.
  5388. if (toolbarTimeoutObject) {
  5389. clearTimeout(toolbarTimeoutObject);
  5390. toolbarTimeoutObject = null;
  5391. }
  5392. }
  5393. else {
  5394. if (!$('#header').is(':visible')) {
  5395. this.showToolbar();
  5396. }
  5397. else {
  5398. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5399. }
  5400. }
  5401. },
  5402. showDesktopSharingButton: showDesktopSharingButton
  5403. };
  5404. module.exports = ToolbarToggler;
  5405. },{}],30:[function(require,module,exports){
  5406. var JitsiPopover = (function () {
  5407. /**
  5408. * Constructs new JitsiPopover and attaches it to the element
  5409. * @param element jquery selector
  5410. * @param options the options for the popover.
  5411. * @constructor
  5412. */
  5413. function JitsiPopover(element, options)
  5414. {
  5415. this.options = {
  5416. skin: "white",
  5417. content: ""
  5418. };
  5419. if(options)
  5420. {
  5421. if(options.skin)
  5422. this.options.skin = options.skin;
  5423. if(options.content)
  5424. this.options.content = options.content;
  5425. }
  5426. this.elementIsHovered = false;
  5427. this.popoverIsHovered = false;
  5428. this.popoverShown = false;
  5429. element.data("jitsi_popover", this);
  5430. this.element = element;
  5431. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5432. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5433. '<div class="jitsiPopupmenuPadding"></div></div>';
  5434. var self = this;
  5435. this.element.on("mouseenter", function () {
  5436. self.elementIsHovered = true;
  5437. self.show();
  5438. }).on("mouseleave", function () {
  5439. self.elementIsHovered = false;
  5440. setTimeout(function () {
  5441. self.hide();
  5442. }, 10);
  5443. });
  5444. }
  5445. /**
  5446. * Shows the popover
  5447. */
  5448. JitsiPopover.prototype.show = function () {
  5449. this.createPopover();
  5450. this.popoverShown = true;
  5451. };
  5452. /**
  5453. * Hides the popover
  5454. */
  5455. JitsiPopover.prototype.hide = function () {
  5456. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5457. {
  5458. this.forceHide();
  5459. }
  5460. };
  5461. /**
  5462. * Hides the popover
  5463. */
  5464. JitsiPopover.prototype.forceHide = function () {
  5465. $(".jitsipopover").remove();
  5466. this.popoverShown = false;
  5467. };
  5468. /**
  5469. * Creates the popover html
  5470. */
  5471. JitsiPopover.prototype.createPopover = function () {
  5472. $("body").append(this.template);
  5473. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5474. var self = this;
  5475. $(".jitsipopover").on("mouseenter", function () {
  5476. self.popoverIsHovered = true;
  5477. }).on("mouseleave", function () {
  5478. self.popoverIsHovered = false;
  5479. self.hide();
  5480. });
  5481. this.refreshPosition();
  5482. };
  5483. /**
  5484. * Refreshes the position of the popover
  5485. */
  5486. JitsiPopover.prototype.refreshPosition = function () {
  5487. $(".jitsipopover").position({
  5488. my: "bottom",
  5489. at: "top",
  5490. collision: "fit",
  5491. of: this.element,
  5492. using: function (position, elements) {
  5493. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5494. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5495. $(".jitsipopover > .arrow").css({left: calcLeft});
  5496. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5497. }
  5498. });
  5499. };
  5500. /**
  5501. * Updates the content of popover.
  5502. * @param content new content
  5503. */
  5504. JitsiPopover.prototype.updateContent = function (content) {
  5505. this.options.content = content;
  5506. if(!this.popoverShown)
  5507. return;
  5508. $(".jitsipopover").remove();
  5509. this.createPopover();
  5510. };
  5511. return JitsiPopover;
  5512. })();
  5513. module.exports = JitsiPopover;
  5514. },{}],31:[function(require,module,exports){
  5515. /* global $, APP, jQuery, toastr */
  5516. var messageHandler = (function(my) {
  5517. /**
  5518. * Shows a message to the user.
  5519. *
  5520. * @param titleString the title of the message
  5521. * @param messageString the text of the message
  5522. */
  5523. my.openMessageDialog = function(titleKey, messageKey) {
  5524. var title = null;
  5525. if(titleKey)
  5526. {
  5527. title = APP.translation.generateTranslationHTML(titleKey);
  5528. }
  5529. var message = APP.translation.generateTranslationHTML(messageKey);
  5530. $.prompt(message,
  5531. {
  5532. title: title,
  5533. persistent: false
  5534. }
  5535. );
  5536. };
  5537. /**
  5538. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5539. *
  5540. * @param titleString the title of the message
  5541. * @param msgString the text of the message
  5542. * @param persistent boolean value which determines whether the message is persistent or not
  5543. * @param leftButton the fist button's text
  5544. * @param submitFunction function to be called on submit
  5545. * @param loadedFunction function to be called after the prompt is fully loaded
  5546. * @param closeFunction function to be called after the prompt is closed
  5547. * @param focus optional focus selector or button index to be focused after
  5548. * the dialog is opened
  5549. * @param defaultButton index of default button which will be activated when
  5550. * the user press 'enter'. Indexed from 0.
  5551. */
  5552. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5553. persistent, leftButtonKey, submitFunction, loadedFunction,
  5554. closeFunction, focus, defaultButton)
  5555. {
  5556. var buttons = [];
  5557. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  5558. buttons.push({ title: leftButton, value: true});
  5559. var cancelButton
  5560. = APP.translation.generateTranslationHTML("dialog.Cancel");
  5561. buttons.push({title: cancelButton, value: false});
  5562. var message = msgString, title = titleString;
  5563. if (titleKey)
  5564. {
  5565. title = APP.translation.generateTranslationHTML(titleKey);
  5566. }
  5567. if (msgKey) {
  5568. message = APP.translation.generateTranslationHTML(msgKey);
  5569. }
  5570. $.prompt(message, {
  5571. title: title,
  5572. persistent: false,
  5573. buttons: buttons,
  5574. defaultButton: defaultButton,
  5575. focus: focus,
  5576. loaded: loadedFunction,
  5577. submit: submitFunction,
  5578. close: closeFunction
  5579. });
  5580. };
  5581. /**
  5582. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5583. *
  5584. * @param titleString the title of the message
  5585. * @param msgString the text of the message
  5586. * @param persistent boolean value which determines whether the message is persistent or not
  5587. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5588. * that will be passed to submitFunction
  5589. * @param submitFunction function to be called on submit
  5590. * @param loadedFunction function to be called after the prompt is fully loaded
  5591. */
  5592. my.openDialog = function (titleString, msgString, persistent, buttons,
  5593. submitFunction, loadedFunction) {
  5594. var args = {
  5595. title: titleString,
  5596. persistent: persistent,
  5597. buttons: buttons,
  5598. defaultButton: 1,
  5599. loaded: loadedFunction,
  5600. submit: submitFunction
  5601. };
  5602. if (persistent) {
  5603. args.closeText = '';
  5604. }
  5605. return new Impromptu(msgString, args);
  5606. };
  5607. /**
  5608. * Closes currently opened dialog.
  5609. */
  5610. my.closeDialog = function () {
  5611. $.prompt.close();
  5612. };
  5613. /**
  5614. * Shows a dialog with different states to the user.
  5615. *
  5616. * @param statesObject object containing all the states of the dialog
  5617. */
  5618. my.openDialogWithStates = function (statesObject, options) {
  5619. return new Impromptu(statesObject, options);
  5620. };
  5621. /**
  5622. * Opens new popup window for given <tt>url</tt> centered over current
  5623. * window.
  5624. *
  5625. * @param url the URL to be displayed in the popup window
  5626. * @param w the width of the popup window
  5627. * @param h the height of the popup window
  5628. * @param onPopupClosed optional callback function called when popup window
  5629. * has been closed.
  5630. *
  5631. * @returns popup window object if opened successfully or undefined
  5632. * in case we failed to open it(popup blocked)
  5633. */
  5634. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5635. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5636. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5637. var popup = window.open(
  5638. url, '_blank',
  5639. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5640. if (popup && onPopupClosed) {
  5641. var pollTimer = window.setInterval(function () {
  5642. if (popup.closed !== false) {
  5643. window.clearInterval(pollTimer);
  5644. onPopupClosed();
  5645. }
  5646. }, 200);
  5647. }
  5648. return popup;
  5649. };
  5650. /**
  5651. * Shows a dialog prompting the user to send an error report.
  5652. *
  5653. * @param titleString the title of the message
  5654. * @param msgString the text of the message
  5655. * @param error the error that is being reported
  5656. */
  5657. my.openReportDialog = function(titleKey, msgKey, error) {
  5658. my.openMessageDialog(titleKey, msgKey);
  5659. console.log(error);
  5660. //FIXME send the error to the server
  5661. };
  5662. /**
  5663. * Shows an error dialog to the user.
  5664. * @param title the title of the message
  5665. * @param message the text of the messafe
  5666. */
  5667. my.showError = function(titleKey, msgKey) {
  5668. if(!titleKey) {
  5669. titleKey = "dialog.oops";
  5670. }
  5671. if(!msgKey)
  5672. {
  5673. msgKey = "dialog.defaultError";
  5674. }
  5675. messageHandler.openMessageDialog(titleKey, msgKey);
  5676. };
  5677. my.notify = function(displayName, displayNameKey,
  5678. cls, messageKey, messageArguments, options) {
  5679. var displayNameSpan = '<span class="nickname" ';
  5680. if(displayName)
  5681. {
  5682. displayNameSpan += ">" + displayName;
  5683. }
  5684. else
  5685. {
  5686. displayNameSpan += "data-i18n='" + displayNameKey +
  5687. "'>" + APP.translation.translateString(displayNameKey);
  5688. }
  5689. displayNameSpan += "</span>";
  5690. toastr.info(
  5691. displayNameSpan + '<br>' +
  5692. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5693. (messageArguments?
  5694. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5695. : "") + ">" +
  5696. APP.translation.translateString(messageKey,
  5697. messageArguments) +
  5698. '</span>', null, options);
  5699. };
  5700. return my;
  5701. }(messageHandler || {}));
  5702. module.exports = messageHandler;
  5703. },{}],32:[function(require,module,exports){
  5704. var UIEvents = require("../../../service/UI/UIEvents");
  5705. var nickname = null;
  5706. var eventEmitter = null;
  5707. var NickanameHandler = {
  5708. init: function (emitter) {
  5709. eventEmitter = emitter;
  5710. var storedDisplayName = window.localStorage.displayname;
  5711. if (storedDisplayName) {
  5712. nickname = storedDisplayName;
  5713. }
  5714. },
  5715. setNickname: function (newNickname) {
  5716. if (!newNickname || nickname === newNickname)
  5717. return;
  5718. nickname = newNickname;
  5719. window.localStorage.displayname = nickname;
  5720. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5721. },
  5722. getNickname: function () {
  5723. return nickname;
  5724. },
  5725. addListener: function (type, listener) {
  5726. eventEmitter.on(type, listener);
  5727. }
  5728. };
  5729. module.exports = NickanameHandler;
  5730. },{"../../../service/UI/UIEvents":103}],33:[function(require,module,exports){
  5731. /**
  5732. * Created by hristo on 12/22/14.
  5733. */
  5734. module.exports = {
  5735. /**
  5736. * Returns the available video width.
  5737. */
  5738. getAvailableVideoWidth: function (isVisible) {
  5739. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5740. if(typeof isVisible === "undefined" || isVisible === null)
  5741. isVisible = PanelToggler.isVisible();
  5742. var rightPanelWidth
  5743. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  5744. return window.innerWidth - rightPanelWidth;
  5745. },
  5746. /**
  5747. * Changes the style class of the element given by id.
  5748. */
  5749. buttonClick: function(id, classname) {
  5750. $(id).toggleClass(classname); // add the class to the clicked element
  5751. },
  5752. /**
  5753. * Returns the text width for the given element.
  5754. *
  5755. * @param el the element
  5756. */
  5757. getTextWidth: function (el) {
  5758. return (el.clientWidth + 1);
  5759. },
  5760. /**
  5761. * Returns the text height for the given element.
  5762. *
  5763. * @param el the element
  5764. */
  5765. getTextHeight: function (el) {
  5766. return (el.clientHeight + 1);
  5767. },
  5768. /**
  5769. * Plays the sound given by id.
  5770. *
  5771. * @param id the identifier of the audio element.
  5772. */
  5773. playSoundNotification: function (id) {
  5774. document.getElementById(id).play();
  5775. },
  5776. /**
  5777. * Escapes the given text.
  5778. */
  5779. escapeHtml: function (unsafeText) {
  5780. return $('<div/>').text(unsafeText).html();
  5781. },
  5782. imageToGrayScale: function (canvas) {
  5783. var context = canvas.getContext('2d');
  5784. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5785. var pixels = imgData.data;
  5786. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5787. var grayscale
  5788. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5789. pixels[i ] = grayscale; // red
  5790. pixels[i+1] = grayscale; // green
  5791. pixels[i+2] = grayscale; // blue
  5792. // pixels[i+3] is alpha
  5793. }
  5794. // redraw the image in black & white
  5795. context.putImageData(imgData, 0, 0);
  5796. },
  5797. setTooltip: function (element, key, position) {
  5798. element.setAttribute("data-i18n", "[data-content]" + key);
  5799. element.setAttribute("data-toggle", "popover");
  5800. element.setAttribute("data-placement", position);
  5801. element.setAttribute("data-html", true);
  5802. element.setAttribute("data-container", "body");
  5803. }
  5804. };
  5805. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  5806. var JitsiPopover = require("../util/JitsiPopover");
  5807. /**
  5808. * Constructs new connection indicator.
  5809. * @param videoContainer the video container associated with the indicator.
  5810. * @constructor
  5811. */
  5812. function ConnectionIndicator(videoContainer, jid)
  5813. {
  5814. this.videoContainer = videoContainer;
  5815. this.bandwidth = null;
  5816. this.packetLoss = null;
  5817. this.bitrate = null;
  5818. this.showMoreValue = false;
  5819. this.resolution = null;
  5820. this.transport = [];
  5821. this.popover = null;
  5822. this.jid = jid;
  5823. this.create();
  5824. }
  5825. /**
  5826. * Values for the connection quality
  5827. * @type {{98: string,
  5828. * 81: string,
  5829. * 64: string,
  5830. * 47: string,
  5831. * 30: string,
  5832. * 0: string}}
  5833. */
  5834. ConnectionIndicator.connectionQualityValues = {
  5835. 98: "18px", //full
  5836. 81: "15px",//4 bars
  5837. 64: "11px",//3 bars
  5838. 47: "7px",//2 bars
  5839. 30: "3px",//1 bar
  5840. 0: "0px"//empty
  5841. };
  5842. ConnectionIndicator.getIP = function(value)
  5843. {
  5844. return value.substring(0, value.lastIndexOf(":"));
  5845. };
  5846. ConnectionIndicator.getPort = function(value)
  5847. {
  5848. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5849. };
  5850. ConnectionIndicator.getStringFromArray = function (array) {
  5851. var res = "";
  5852. for(var i = 0; i < array.length; i++)
  5853. {
  5854. res += (i === 0? "" : ", ") + array[i];
  5855. }
  5856. return res;
  5857. };
  5858. /**
  5859. * Generates the html content.
  5860. * @returns {string} the html content.
  5861. */
  5862. ConnectionIndicator.prototype.generateText = function () {
  5863. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5864. var translate = APP.translation.translateString;
  5865. if(this.bitrate === null)
  5866. {
  5867. downloadBitrate = "N/A";
  5868. uploadBitrate = "N/A";
  5869. }
  5870. else
  5871. {
  5872. downloadBitrate =
  5873. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5874. uploadBitrate =
  5875. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5876. }
  5877. if(this.packetLoss === null)
  5878. {
  5879. packetLoss = "N/A";
  5880. }
  5881. else
  5882. {
  5883. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5884. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5885. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5886. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5887. }
  5888. var resolutionValue = null;
  5889. if(this.resolution && this.jid != null)
  5890. {
  5891. var keys = Object.keys(this.resolution);
  5892. for(var ssrc in this.resolution)
  5893. {
  5894. resolutionValue = this.resolution[ssrc];
  5895. }
  5896. }
  5897. if(this.jid === null)
  5898. {
  5899. resolution = "";
  5900. if(this.resolution === null || !Object.keys(this.resolution) ||
  5901. Object.keys(this.resolution).length === 0)
  5902. {
  5903. resolution = "N/A";
  5904. }
  5905. else
  5906. for(i in this.resolution)
  5907. {
  5908. resolutionValue = this.resolution[i];
  5909. if(resolutionValue)
  5910. {
  5911. if(resolutionValue.height &&
  5912. resolutionValue.width)
  5913. {
  5914. resolution += (resolution === ""? "" : ", ") +
  5915. resolutionValue.width + "x" +
  5916. resolutionValue.height;
  5917. }
  5918. }
  5919. }
  5920. }
  5921. else if(!resolutionValue ||
  5922. !resolutionValue.height ||
  5923. !resolutionValue.width)
  5924. {
  5925. resolution = "N/A";
  5926. }
  5927. else
  5928. {
  5929. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5930. }
  5931. var result = "<table style='width:100%'>" +
  5932. "<tr>" +
  5933. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5934. translate("connectionindicator.bitrate") + "</span></td>" +
  5935. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5936. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5937. uploadBitrate + "</td>" +
  5938. "</tr><tr>" +
  5939. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5940. translate("connectionindicator.packetloss") + "</span></td>" +
  5941. "<td>" + packetLoss + "</td>" +
  5942. "</tr><tr>" +
  5943. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5944. translate("connectionindicator.resolution") + "</span></td>" +
  5945. "<td>" + resolution + "</td></tr></table>";
  5946. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  5947. result += "<div class=\"jitsipopover_showmore\" " +
  5948. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5949. this.jid + "')\" data-i18n='connectionindicator." +
  5950. (this.showMoreValue ? "less" : "more") + "'>" +
  5951. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5952. "</div><br />";
  5953. }
  5954. if(this.showMoreValue)
  5955. {
  5956. var downloadBandwidth, uploadBandwidth, transport;
  5957. if(this.bandwidth === null)
  5958. {
  5959. downloadBandwidth = "N/A";
  5960. uploadBandwidth = "N/A";
  5961. }
  5962. else
  5963. {
  5964. downloadBandwidth = this.bandwidth.download?
  5965. this.bandwidth.download + " Kbps" :
  5966. "N/A";
  5967. uploadBandwidth = this.bandwidth.upload?
  5968. this.bandwidth.upload + " Kbps" :
  5969. "N/A";
  5970. }
  5971. if(!this.transport || this.transport.length === 0)
  5972. {
  5973. transport = "<tr>" +
  5974. "<td><span class='jitsipopover_blue' " +
  5975. "data-i18n='connectionindicator.address'>" +
  5976. translate("connectionindicator.address") + "</span></td>" +
  5977. "<td> N/A</td></tr>";
  5978. }
  5979. else
  5980. {
  5981. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5982. for(i = 0; i < this.transport.length; i++)
  5983. {
  5984. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5985. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5986. var localIP =
  5987. ConnectionIndicator.getIP(this.transport[i].localip);
  5988. var localPort =
  5989. ConnectionIndicator.getPort(this.transport[i].localip);
  5990. if(data.remoteIP.indexOf(ip) == -1)
  5991. {
  5992. data.remoteIP.push(ip);
  5993. }
  5994. if(data.remotePort.indexOf(port) == -1)
  5995. {
  5996. data.remotePort.push(port);
  5997. }
  5998. if(data.localIP.indexOf(localIP) == -1)
  5999. {
  6000. data.localIP.push(localIP);
  6001. }
  6002. if(data.localPort.indexOf(localPort) == -1)
  6003. {
  6004. data.localPort.push(localPort);
  6005. }
  6006. }
  6007. var local_address_key = "connectionindicator.localaddress";
  6008. var remote_address_key = "connectionindicator.remoteaddress";
  6009. var localTransport =
  6010. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6011. local_address_key +"' data-i18n-options='" +
  6012. JSON.stringify({count: data.localIP.length}) + "'>" +
  6013. translate(local_address_key, {count: data.localIP.length}) +
  6014. "</span></td><td> " +
  6015. ConnectionIndicator.getStringFromArray(data.localIP) +
  6016. "</td></tr>";
  6017. transport =
  6018. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6019. remote_address_key + "' data-i18n-options='" +
  6020. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  6021. translate(remote_address_key,
  6022. {count: data.remoteIP.length}) +
  6023. "</span></td><td> " +
  6024. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  6025. "</td></tr>";
  6026. var key_remote = "connectionindicator.remoteport",
  6027. key_local = "connectionindicator.localport";
  6028. transport += "<tr>" +
  6029. "<td>" +
  6030. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  6031. "' data-i18n-options='" +
  6032. JSON.stringify({count: this.transport.length}) + "'>" +
  6033. translate(key_remote, {count: this.transport.length}) +
  6034. "</span></td><td>";
  6035. localTransport += "<tr>" +
  6036. "<td>" +
  6037. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  6038. "' data-i18n-options='" +
  6039. JSON.stringify({count: this.transport.length}) + "'>" +
  6040. translate(key_local, {count: this.transport.length}) +
  6041. "</span></td><td>";
  6042. transport +=
  6043. ConnectionIndicator.getStringFromArray(data.remotePort);
  6044. localTransport +=
  6045. ConnectionIndicator.getStringFromArray(data.localPort);
  6046. transport += "</td></tr>";
  6047. transport += localTransport + "</td></tr>";
  6048. transport +="<tr>" +
  6049. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  6050. translate("connectionindicator.transport") + "</span></td>" +
  6051. "<td>" + this.transport[0].type + "</td></tr>";
  6052. }
  6053. result += "<table style='width:100%'>" +
  6054. "<tr>" +
  6055. "<td>" +
  6056. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  6057. translate("connectionindicator.bandwidth") + "</span>" +
  6058. "</td><td>" +
  6059. "<span class='jitsipopover_green'>&darr;</span>" +
  6060. downloadBandwidth +
  6061. " <span class='jitsipopover_orange'>&uarr;</span>" +
  6062. uploadBandwidth + "</td></tr>";
  6063. result += transport + "</table>";
  6064. }
  6065. return result;
  6066. };
  6067. /**
  6068. * Shows or hide the additional information.
  6069. */
  6070. ConnectionIndicator.prototype.showMore = function () {
  6071. this.showMoreValue = !this.showMoreValue;
  6072. this.updatePopoverData();
  6073. };
  6074. function createIcon(classes)
  6075. {
  6076. var icon = document.createElement("span");
  6077. for(var i in classes)
  6078. {
  6079. icon.classList.add(classes[i]);
  6080. }
  6081. icon.appendChild(
  6082. document.createElement("i")).classList.add("icon-connection");
  6083. return icon;
  6084. }
  6085. /**
  6086. * Creates the indicator
  6087. */
  6088. ConnectionIndicator.prototype.create = function () {
  6089. this.connectionIndicatorContainer = document.createElement("div");
  6090. this.connectionIndicatorContainer.className = "connectionindicator";
  6091. this.connectionIndicatorContainer.style.display = "none";
  6092. this.videoContainer.container.appendChild(this.connectionIndicatorContainer);
  6093. this.popover = new JitsiPopover(
  6094. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  6095. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  6096. APP.translation.translateString("connectionindicator.na") + "</div>",
  6097. skin: "black"});
  6098. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  6099. createIcon(["connection", "connection_empty"]));
  6100. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  6101. createIcon(["connection", "connection_full"]));
  6102. };
  6103. /**
  6104. * Removes the indicator
  6105. */
  6106. ConnectionIndicator.prototype.remove = function()
  6107. {
  6108. this.connectionIndicatorContainer.remove();
  6109. this.popover.forceHide();
  6110. };
  6111. /**
  6112. * Updates the data of the indicator
  6113. * @param percent the percent of connection quality
  6114. * @param object the statistics data.
  6115. */
  6116. ConnectionIndicator.prototype.updateConnectionQuality =
  6117. function (percent, object) {
  6118. if(percent === null)
  6119. {
  6120. this.connectionIndicatorContainer.style.display = "none";
  6121. this.popover.forceHide();
  6122. return;
  6123. }
  6124. else
  6125. {
  6126. if(this.connectionIndicatorContainer.style.display == "none") {
  6127. this.connectionIndicatorContainer.style.display = "block";
  6128. this.videoContainer.updateIconPositions();
  6129. }
  6130. }
  6131. this.bandwidth = object.bandwidth;
  6132. this.bitrate = object.bitrate;
  6133. this.packetLoss = object.packetLoss;
  6134. this.transport = object.transport;
  6135. if(object.resolution)
  6136. {
  6137. this.resolution = object.resolution;
  6138. }
  6139. for(var quality in ConnectionIndicator.connectionQualityValues)
  6140. {
  6141. if(percent >= quality)
  6142. {
  6143. this.fullIcon.style.width =
  6144. ConnectionIndicator.connectionQualityValues[quality];
  6145. }
  6146. }
  6147. this.updatePopoverData();
  6148. };
  6149. /**
  6150. * Updates the resolution
  6151. * @param resolution the new resolution
  6152. */
  6153. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  6154. this.resolution = resolution;
  6155. this.updatePopoverData();
  6156. };
  6157. /**
  6158. * Updates the content of the popover
  6159. */
  6160. ConnectionIndicator.prototype.updatePopoverData = function () {
  6161. this.popover.updateContent(
  6162. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  6163. APP.translation.translateElement($(".connection_info"));
  6164. };
  6165. /**
  6166. * Hides the popover
  6167. */
  6168. ConnectionIndicator.prototype.hide = function () {
  6169. this.popover.forceHide();
  6170. };
  6171. /**
  6172. * Hides the indicator
  6173. */
  6174. ConnectionIndicator.prototype.hideIndicator = function () {
  6175. this.connectionIndicatorContainer.style.display = "none";
  6176. if(this.popover)
  6177. this.popover.forceHide();
  6178. };
  6179. module.exports = ConnectionIndicator;
  6180. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  6181. var Avatar = require("../avatar/Avatar");
  6182. var UIUtil = require("../util/UIUtil");
  6183. var UIEvents = require("../../../service/UI/UIEvents");
  6184. var xmpp = require("../../xmpp/xmpp");
  6185. var video = $('#largeVideo');
  6186. var currentVideoWidth = null;
  6187. var currentVideoHeight = null;
  6188. // By default we use camera
  6189. var getVideoSize = getCameraVideoSize;
  6190. var getVideoPosition = getCameraVideoPosition;
  6191. var currentSmallVideo = null;
  6192. var oldSmallVideo = null;
  6193. /**
  6194. * Sets the size and position of the given video element.
  6195. *
  6196. * @param video the video element to position
  6197. * @param width the desired video width
  6198. * @param height the desired video height
  6199. * @param horizontalIndent the left and right indent
  6200. * @param verticalIndent the top and bottom indent
  6201. */
  6202. function positionVideo(video,
  6203. width,
  6204. height,
  6205. horizontalIndent,
  6206. verticalIndent,
  6207. animate) {
  6208. if(animate)
  6209. {
  6210. video.animate({
  6211. width: width,
  6212. height: height,
  6213. top: verticalIndent,
  6214. bottom: verticalIndent,
  6215. left: horizontalIndent,
  6216. right: horizontalIndent
  6217. },
  6218. {
  6219. queue: false,
  6220. duration: 500
  6221. });
  6222. }
  6223. else
  6224. {
  6225. video.width(width);
  6226. video.height(height);
  6227. video.css({ top: verticalIndent + 'px',
  6228. bottom: verticalIndent + 'px',
  6229. left: horizontalIndent + 'px',
  6230. right: horizontalIndent + 'px'});
  6231. }
  6232. }
  6233. /**
  6234. * Returns an array of the video dimensions, so that it keeps it's aspect
  6235. * ratio and fits available area with it's larger dimension. This method
  6236. * ensures that whole video will be visible and can leave empty areas.
  6237. *
  6238. * @return an array with 2 elements, the video width and the video height
  6239. */
  6240. function getDesktopVideoSize(videoWidth,
  6241. videoHeight,
  6242. videoSpaceWidth,
  6243. videoSpaceHeight) {
  6244. if (!videoWidth)
  6245. videoWidth = currentVideoWidth;
  6246. if (!videoHeight)
  6247. videoHeight = currentVideoHeight;
  6248. var aspectRatio = videoWidth / videoHeight;
  6249. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6250. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6251. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6252. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6253. {
  6254. availableHeight = videoSpaceHeight;
  6255. availableWidth = availableHeight * aspectRatio;
  6256. }
  6257. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6258. {
  6259. availableWidth = videoSpaceWidth;
  6260. availableHeight = availableWidth / aspectRatio;
  6261. }
  6262. return [availableWidth, availableHeight];
  6263. }
  6264. /**
  6265. * Returns an array of the video horizontal and vertical indents,
  6266. * so that if fits its parent.
  6267. *
  6268. * @return an array with 2 elements, the horizontal indent and the vertical
  6269. * indent
  6270. */
  6271. function getCameraVideoPosition(videoWidth,
  6272. videoHeight,
  6273. videoSpaceWidth,
  6274. videoSpaceHeight) {
  6275. // Parent height isn't completely calculated when we position the video in
  6276. // full screen mode and this is why we use the screen height in this case.
  6277. // Need to think it further at some point and implement it properly.
  6278. var isFullScreen = document.fullScreen ||
  6279. document.mozFullScreen ||
  6280. document.webkitIsFullScreen;
  6281. if (isFullScreen)
  6282. videoSpaceHeight = window.innerHeight;
  6283. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6284. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  6285. return [horizontalIndent, verticalIndent];
  6286. }
  6287. /**
  6288. * Returns an array of the video horizontal and vertical indents.
  6289. * Centers horizontally and top aligns vertically.
  6290. *
  6291. * @return an array with 2 elements, the horizontal indent and the vertical
  6292. * indent
  6293. */
  6294. function getDesktopVideoPosition(videoWidth,
  6295. videoHeight,
  6296. videoSpaceWidth,
  6297. videoSpaceHeight) {
  6298. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6299. var verticalIndent = 0;// Top aligned
  6300. return [horizontalIndent, verticalIndent];
  6301. }
  6302. /**
  6303. * Returns an array of the video dimensions, so that it covers the screen.
  6304. * It leaves no empty areas, but some parts of the video might not be visible.
  6305. *
  6306. * @return an array with 2 elements, the video width and the video height
  6307. */
  6308. function getCameraVideoSize(videoWidth,
  6309. videoHeight,
  6310. videoSpaceWidth,
  6311. videoSpaceHeight) {
  6312. if (!videoWidth)
  6313. videoWidth = currentVideoWidth;
  6314. if (!videoHeight)
  6315. videoHeight = currentVideoHeight;
  6316. var aspectRatio = videoWidth / videoHeight;
  6317. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6318. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6319. if (availableWidth / aspectRatio < videoSpaceHeight) {
  6320. availableHeight = videoSpaceHeight;
  6321. availableWidth = availableHeight * aspectRatio;
  6322. }
  6323. if (availableHeight * aspectRatio < videoSpaceWidth) {
  6324. availableWidth = videoSpaceWidth;
  6325. availableHeight = availableWidth / aspectRatio;
  6326. }
  6327. return [availableWidth, availableHeight];
  6328. }
  6329. /**
  6330. * Updates the src of the active speaker avatar
  6331. * @param jid of the current active speaker
  6332. */
  6333. function updateActiveSpeakerAvatarSrc() {
  6334. var avatar = $("#activeSpeakerAvatar")[0];
  6335. var jid = currentSmallVideo.peerJid;
  6336. var url = Avatar.getGravatarUrl(jid);
  6337. if(avatar.src === url)
  6338. return;
  6339. var isMuted = null;
  6340. if(!LargeVideo.VideoLayout.isInLastN(currentSmallVideo.resourceJid)) {
  6341. isMuted = true;
  6342. }
  6343. else
  6344. {
  6345. isMuted = APP.RTC.isVideoMuted(jid);
  6346. }
  6347. if (jid && isMuted !== null) {
  6348. avatar.src = url;
  6349. $("#largeVideo").css("visibility", isMuted ? "hidden" : "visible");
  6350. currentSmallVideo.showAvatar(isMuted);
  6351. }
  6352. }
  6353. function changeVideo(isVisible) {
  6354. updateActiveSpeakerAvatarSrc();
  6355. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  6356. var videoTransform = document.getElementById('largeVideo')
  6357. .style.webkitTransform;
  6358. var flipX = currentSmallVideo.flipX;
  6359. if (flipX && videoTransform !== 'scaleX(-1)') {
  6360. document.getElementById('largeVideo').style.webkitTransform
  6361. = "scaleX(-1)";
  6362. }
  6363. else if (!flipX && videoTransform === 'scaleX(-1)') {
  6364. document.getElementById('largeVideo').style.webkitTransform
  6365. = "none";
  6366. }
  6367. var isDesktop = APP.RTC.isVideoSrcDesktop(currentSmallVideo.peerJid);
  6368. // Change the way we'll be measuring and positioning large video
  6369. getVideoSize = isDesktop
  6370. ? getDesktopVideoSize
  6371. : getCameraVideoSize;
  6372. getVideoPosition = isDesktop
  6373. ? getDesktopVideoPosition
  6374. : getCameraVideoPosition;
  6375. // Only if the large video is currently visible.
  6376. // Disable previous dominant speaker video.
  6377. if (oldSmallVideo) {
  6378. oldSmallVideo.enableDominantSpeaker(false);
  6379. }
  6380. // Enable new dominant speaker in the remote videos section.
  6381. if (currentSmallVideo) {
  6382. currentSmallVideo.enableDominantSpeaker(true);
  6383. }
  6384. if (isVisible) {
  6385. // using "this" should be ok because we're called
  6386. // from within the fadeOut event.
  6387. $(this).fadeIn(300);
  6388. }
  6389. if(oldSmallVideo)
  6390. oldSmallVideo.showAvatar();
  6391. }
  6392. var LargeVideo = {
  6393. init: function (VideoLayout, emitter) {
  6394. this.VideoLayout = VideoLayout;
  6395. this.eventEmitter = emitter;
  6396. var self = this;
  6397. // Listen for large video size updates
  6398. document.getElementById('largeVideo')
  6399. .addEventListener('loadedmetadata', function (e) {
  6400. currentVideoWidth = this.videoWidth;
  6401. currentVideoHeight = this.videoHeight;
  6402. self.position(currentVideoWidth, currentVideoHeight);
  6403. });
  6404. },
  6405. /**
  6406. * Indicates if the large video is currently visible.
  6407. *
  6408. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6409. */
  6410. isLargeVideoVisible: function() {
  6411. return video.is(':visible');
  6412. },
  6413. /**
  6414. * Updates the large video with the given new video source.
  6415. */
  6416. updateLargeVideo: function(resourceJid, forceUpdate) {
  6417. console.log('hover in', resourceJid);
  6418. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  6419. if ((currentSmallVideo && currentSmallVideo.resourceJid !== resourceJid)
  6420. || forceUpdate) {
  6421. $('#activeSpeaker').css('visibility', 'hidden');
  6422. if(currentSmallVideo) {
  6423. oldSmallVideo = currentSmallVideo;
  6424. } else {
  6425. oldSmallVideo = null;
  6426. }
  6427. currentSmallVideo = newSmallVideo;
  6428. var oldJid = null;
  6429. if(oldSmallVideo)
  6430. oldJid = oldSmallVideo.peerJid;
  6431. if (oldJid !== resourceJid) {
  6432. // we want the notification to trigger even if userJid is undefined,
  6433. // or null.
  6434. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6435. resourceJid);
  6436. }
  6437. video.fadeOut(300, changeVideo.bind(video, this.isLargeVideoVisible()));
  6438. } else {
  6439. if(currentSmallVideo) {
  6440. currentSmallVideo.showAvatar();
  6441. }
  6442. }
  6443. },
  6444. /**
  6445. * Shows/hides the large video.
  6446. */
  6447. setLargeVideoVisible: function(isVisible) {
  6448. if (isVisible) {
  6449. $('#largeVideo').css({visibility: 'visible'});
  6450. $('.watermark').css({visibility: 'visible'});
  6451. if(currentSmallVideo)
  6452. currentSmallVideo.enableDominantSpeaker(true);
  6453. }
  6454. else {
  6455. $('#largeVideo').css({visibility: 'hidden'});
  6456. $('#activeSpeaker').css('visibility', 'hidden');
  6457. $('.watermark').css({visibility: 'hidden'});
  6458. if(currentSmallVideo)
  6459. currentSmallVideo.enableDominantSpeaker(false);
  6460. }
  6461. },
  6462. onVideoTypeChanged: function (jid) {
  6463. if(jid && currentSmallVideo && jid === currentSmallVideo.peerJid)
  6464. {
  6465. var isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  6466. getVideoSize = isDesktop
  6467. ? getDesktopVideoSize
  6468. : getCameraVideoSize;
  6469. getVideoPosition = isDesktop
  6470. ? getDesktopVideoPosition
  6471. : getCameraVideoPosition;
  6472. this.position(null, null);
  6473. }
  6474. },
  6475. /**
  6476. * Positions the large video.
  6477. *
  6478. * @param videoWidth the stream video width
  6479. * @param videoHeight the stream video height
  6480. */
  6481. position: function (videoWidth, videoHeight,
  6482. videoSpaceWidth, videoSpaceHeight, animate) {
  6483. if(!videoSpaceWidth)
  6484. videoSpaceWidth = $('#videospace').width();
  6485. if(!videoSpaceHeight)
  6486. videoSpaceHeight = window.innerHeight;
  6487. var videoSize = getVideoSize(videoWidth,
  6488. videoHeight,
  6489. videoSpaceWidth,
  6490. videoSpaceHeight);
  6491. var largeVideoWidth = videoSize[0];
  6492. var largeVideoHeight = videoSize[1];
  6493. var videoPosition = getVideoPosition(largeVideoWidth,
  6494. largeVideoHeight,
  6495. videoSpaceWidth,
  6496. videoSpaceHeight);
  6497. var horizontalIndent = videoPosition[0];
  6498. var verticalIndent = videoPosition[1];
  6499. positionVideo($('#largeVideo'),
  6500. largeVideoWidth,
  6501. largeVideoHeight,
  6502. horizontalIndent, verticalIndent, animate);
  6503. },
  6504. isLargeVideoOnTop: function () {
  6505. var Etherpad = require("../etherpad/Etherpad");
  6506. var Prezi = require("../prezi/Prezi");
  6507. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6508. },
  6509. resize: function (animate, isVisible, completeFunction) {
  6510. var availableHeight = window.innerHeight;
  6511. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  6512. if (availableWidth < 0 || availableHeight < 0) return;
  6513. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6514. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6515. $('#activeSpeaker').css('top', top);
  6516. if(animate)
  6517. {
  6518. $('#videospace').animate({
  6519. right: window.innerWidth - availableWidth,
  6520. width: availableWidth,
  6521. height: availableHeight
  6522. },
  6523. {
  6524. queue: false,
  6525. duration: 500,
  6526. complete: completeFunction
  6527. });
  6528. $('#largeVideoContainer').animate({
  6529. width: availableWidth,
  6530. height: availableHeight
  6531. },
  6532. {
  6533. queue: false,
  6534. duration: 500
  6535. });
  6536. }
  6537. else
  6538. {
  6539. $('#videospace').width(availableWidth);
  6540. $('#videospace').height(availableHeight);
  6541. $('#largeVideoContainer').width(availableWidth);
  6542. $('#largeVideoContainer').height(availableHeight);
  6543. }
  6544. return [availableWidth, availableHeight];
  6545. },
  6546. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  6547. var size = this.resize(true, isVisible, completeFunction);
  6548. this.position(null, null, size[0], size[1], true);
  6549. },
  6550. getResourceJid: function () {
  6551. if(!currentSmallVideo)
  6552. return null;
  6553. return currentSmallVideo.resourceJid;
  6554. },
  6555. updateAvatar: function (resourceJid) {
  6556. if (resourceJid === this.getResourceJid()) {
  6557. updateActiveSpeakerAvatarSrc();
  6558. }
  6559. },
  6560. showAvatar: function (resourceJid, show) {
  6561. if(this.getResourceJid() === resourceJid
  6562. && LargeVideo.isLargeVideoOnTop())
  6563. {
  6564. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  6565. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  6566. return true;
  6567. }
  6568. return false;
  6569. }
  6570. }
  6571. module.exports = LargeVideo;
  6572. },{"../../../service/UI/UIEvents":103,"../../xmpp/xmpp":66,"../avatar/Avatar":16,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../util/UIUtil":33}],36:[function(require,module,exports){
  6573. var SmallVideo = require("./SmallVideo");
  6574. var ConnectionIndicator = require("./ConnectionIndicator");
  6575. var NicknameHandler = require("../util/NicknameHandler");
  6576. var UIUtil = require("../util/UIUtil");
  6577. var LargeVideo = require("./LargeVideo");
  6578. function LocalVideo(VideoLayout)
  6579. {
  6580. this.videoSpanId = "localVideoContainer";
  6581. this.container = $("#localVideoContainer").get(0);
  6582. this.VideoLayout = VideoLayout;
  6583. this.flipX = true;
  6584. this.peerJid = null;
  6585. this.resourceJid = null;
  6586. }
  6587. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  6588. LocalVideo.prototype.constructor = LocalVideo;
  6589. /**
  6590. * Creates the edit display name button.
  6591. *
  6592. * @returns the edit button
  6593. */
  6594. function createEditDisplayNameButton() {
  6595. var editButton = document.createElement('a');
  6596. editButton.className = 'displayname';
  6597. UIUtil.setTooltip(editButton,
  6598. "videothumbnail.editnickname",
  6599. "top");
  6600. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6601. return editButton;
  6602. }
  6603. /**
  6604. * Sets the display name for the given video span id.
  6605. */
  6606. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  6607. if (!this.container) {
  6608. console.warn(
  6609. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  6610. return;
  6611. }
  6612. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  6613. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  6614. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6615. // If we already have a display name for this video.
  6616. if (nameSpan.length > 0) {
  6617. if (nameSpan.text() !== displayName) {
  6618. if (displayName && displayName.length > 0)
  6619. {
  6620. var meHTML = APP.translation.generateTranslationHTML("me");
  6621. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  6622. }
  6623. else
  6624. $('#localDisplayName').html(defaultLocalDisplayName);
  6625. }
  6626. } else {
  6627. var editButton = createEditDisplayNameButton();
  6628. nameSpan = document.createElement('span');
  6629. nameSpan.className = 'displayname';
  6630. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  6631. if (displayName && displayName.length > 0) {
  6632. var meHTML = APP.translation.generateTranslationHTML("me");
  6633. nameSpan.innerHTML = displayName + meHTML;
  6634. }
  6635. else {
  6636. nameSpan.innerHTML = defaultLocalDisplayName;
  6637. }
  6638. nameSpan.id = 'localDisplayName';
  6639. this.container.appendChild(editButton);
  6640. //translates popover of edit button
  6641. APP.translation.translateElement($("a.displayname"));
  6642. var editableText = document.createElement('input');
  6643. editableText.className = 'displayname';
  6644. editableText.type = 'text';
  6645. editableText.id = 'editDisplayName';
  6646. if (displayName && displayName.length) {
  6647. editableText.value = displayName;
  6648. }
  6649. var defaultNickname = APP.translation.translateString(
  6650. "defaultNickname", {name: "Jane Pink"});
  6651. editableText.setAttribute('style', 'display:none;');
  6652. editableText.setAttribute('data-18n',
  6653. '[placeholder]defaultNickname');
  6654. editableText.setAttribute("data-i18n-options",
  6655. JSON.stringify({name: "Jane Pink"}));
  6656. editableText.setAttribute("placeholder", defaultNickname);
  6657. this.container.appendChild(editableText);
  6658. var self = this;
  6659. $('#localVideoContainer .displayname')
  6660. .bind("click", function (e) {
  6661. e.preventDefault();
  6662. e.stopPropagation();
  6663. $('#localDisplayName').hide();
  6664. $('#editDisplayName').show();
  6665. $('#editDisplayName').focus();
  6666. $('#editDisplayName').select();
  6667. $('#editDisplayName').one("focusout", function (e) {
  6668. self.VideoLayout.inputDisplayNameHandler(this.value);
  6669. });
  6670. $('#editDisplayName').on('keydown', function (e) {
  6671. if (e.keyCode === 13) {
  6672. e.preventDefault();
  6673. self.VideoLayout.inputDisplayNameHandler(this.value);
  6674. }
  6675. });
  6676. });
  6677. }
  6678. }
  6679. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  6680. NicknameHandler.setNickname(name);
  6681. if (!$('#localDisplayName').is(":visible")) {
  6682. if (NicknameHandler.getNickname())
  6683. {
  6684. var meHTML = APP.translation.generateTranslationHTML("me");
  6685. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6686. }
  6687. else
  6688. {
  6689. var defaultHTML = APP.translation.generateTranslationHTML(
  6690. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6691. $('#localDisplayName')
  6692. .html(defaultHTML);
  6693. }
  6694. $('#localDisplayName').show();
  6695. }
  6696. $('#editDisplayName').hide();
  6697. }
  6698. LocalVideo.prototype.createConnectionIndicator = function()
  6699. {
  6700. if(this.connectionIndicator)
  6701. return;
  6702. this.connectionIndicator
  6703. = new ConnectionIndicator(this, null);
  6704. }
  6705. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  6706. var self = this;
  6707. function localVideoClick(event) {
  6708. event.stopPropagation();
  6709. self.VideoLayout.handleVideoThumbClicked(
  6710. false,
  6711. APP.xmpp.myResource());
  6712. }
  6713. $('#localVideoContainer').click(localVideoClick);
  6714. // Add hover handler
  6715. $('#localVideoContainer').hover(
  6716. function() {
  6717. self.showDisplayName(true);
  6718. },
  6719. function() {
  6720. if (!LargeVideo.isLargeVideoVisible()
  6721. || APP.xmpp.myResource() !== LargeVideo.getResourceJid())
  6722. self.showDisplayName(false);
  6723. }
  6724. );
  6725. if(isMuted)
  6726. {
  6727. APP.UI.setVideoMute(true);
  6728. return;
  6729. }
  6730. this.flipX = (stream.videoType == "screen")? false : true;
  6731. var localVideo = document.createElement('video');
  6732. localVideo.id = 'localVideo_' +
  6733. APP.RTC.getStreamID(stream.getOriginalStream());
  6734. localVideo.autoplay = true;
  6735. localVideo.volume = 0; // is it required if audio is separated ?
  6736. localVideo.oncontextmenu = function () { return false; };
  6737. var localVideoContainer = document.getElementById('localVideoWrapper');
  6738. localVideoContainer.appendChild(localVideo);
  6739. var localVideoSelector = $('#' + localVideo.id);
  6740. // Add click handler to both video and video wrapper elements in case
  6741. // there's no video.
  6742. localVideoSelector.click(localVideoClick);
  6743. if (this.flipX) {
  6744. localVideoSelector.addClass("flipVideoX");
  6745. }
  6746. // Attach WebRTC stream
  6747. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  6748. // Add stream ended handler
  6749. stream.getOriginalStream().onended = function () {
  6750. localVideoContainer.removeChild(localVideo);
  6751. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  6752. };
  6753. }
  6754. LocalVideo.prototype.joined = function (jid) {
  6755. this.peerJid = jid;
  6756. this.resourceJid = Strophe.getResourceFromJid(jid);
  6757. }
  6758. module.exports = LocalVideo;
  6759. },{"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  6760. var ConnectionIndicator = require("./ConnectionIndicator");
  6761. var SmallVideo = require("./SmallVideo");
  6762. var AudioLevels = require("../audio_levels/AudioLevels");
  6763. var LargeVideo = require("./LargeVideo");
  6764. var Avatar = require("../avatar/Avatar");
  6765. function RemoteVideo(peerJid, VideoLayout)
  6766. {
  6767. this.peerJid = peerJid;
  6768. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  6769. this.videoSpanId = 'participant_' + this.resourceJid;
  6770. this.VideoLayout = VideoLayout;
  6771. this.addRemoteVideoContainer();
  6772. this.connectionIndicator = new ConnectionIndicator(
  6773. this, this.peerJid);
  6774. this.setDisplayName();
  6775. var nickfield = document.createElement('span');
  6776. nickfield.className = "nick";
  6777. nickfield.appendChild(document.createTextNode(this.resourceJid));
  6778. this.container.appendChild(nickfield);
  6779. this.flipX = false;
  6780. }
  6781. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  6782. RemoteVideo.prototype.constructor = RemoteVideo;
  6783. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  6784. this.container = RemoteVideo.createContainer(this.videoSpanId);
  6785. if (APP.xmpp.isModerator())
  6786. this.addRemoteVideoMenu();
  6787. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  6788. return this.container;
  6789. };
  6790. /**
  6791. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6792. * given <tt>parentElement</tt>.
  6793. *
  6794. * @param jid the jid indicating the video for which we're adding a menu.
  6795. * @param parentElement the parent element where this menu will be added
  6796. */
  6797. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  6798. var spanElement = document.createElement('span');
  6799. spanElement.className = 'remotevideomenu';
  6800. this.container.appendChild(spanElement);
  6801. var menuElement = document.createElement('i');
  6802. menuElement.className = 'fa fa-angle-down';
  6803. menuElement.title = 'Remote user controls';
  6804. spanElement.appendChild(menuElement);
  6805. var popupmenuElement = document.createElement('ul');
  6806. popupmenuElement.className = 'popupmenu';
  6807. popupmenuElement.id
  6808. = 'remote_popupmenu_' + this.resourceJid;
  6809. spanElement.appendChild(popupmenuElement);
  6810. var muteMenuItem = document.createElement('li');
  6811. var muteLinkItem = document.createElement('a');
  6812. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6813. if (!this.isMuted) {
  6814. muteLinkItem.innerHTML = mutedIndicator +
  6815. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6816. muteLinkItem.className = 'mutelink';
  6817. }
  6818. else {
  6819. muteLinkItem.innerHTML = mutedIndicator +
  6820. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6821. muteLinkItem.className = 'mutelink disabled';
  6822. }
  6823. var self = this;
  6824. muteLinkItem.onclick = function(){
  6825. if ($(this).attr('disabled') != undefined) {
  6826. event.preventDefault();
  6827. }
  6828. var isMute = self.isMuted == true;
  6829. APP.xmpp.setMute(self.peerJid, !isMute);
  6830. popupmenuElement.setAttribute('style', 'display:none;');
  6831. if (isMute) {
  6832. this.innerHTML = mutedIndicator +
  6833. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6834. this.className = 'mutelink disabled';
  6835. }
  6836. else {
  6837. this.innerHTML = mutedIndicator +
  6838. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6839. this.className = 'mutelink';
  6840. }
  6841. };
  6842. muteMenuItem.appendChild(muteLinkItem);
  6843. popupmenuElement.appendChild(muteMenuItem);
  6844. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6845. var ejectMenuItem = document.createElement('li');
  6846. var ejectLinkItem = document.createElement('a');
  6847. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6848. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6849. ejectLinkItem.onclick = function(){
  6850. APP.xmpp.eject(self.peerJid);
  6851. popupmenuElement.setAttribute('style', 'display:none;');
  6852. };
  6853. ejectMenuItem.appendChild(ejectLinkItem);
  6854. popupmenuElement.appendChild(ejectMenuItem);
  6855. var paddingSpan = document.createElement('span');
  6856. paddingSpan.className = 'popupmenuPadding';
  6857. popupmenuElement.appendChild(paddingSpan);
  6858. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6859. }
  6860. /**
  6861. * Removes the remote stream element corresponding to the given stream and
  6862. * parent container.
  6863. *
  6864. * @param stream the stream
  6865. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6866. * @param container
  6867. */
  6868. RemoteVideo.prototype.removeRemoteStreamElement = function (stream, isVideo, id) {
  6869. if (!this.container)
  6870. return false;
  6871. var select = null;
  6872. if (isVideo) {
  6873. select = $('#' + id);
  6874. }
  6875. else
  6876. select = $('#' + this.videoSpanId + '>audio');
  6877. // Mark video as removed to cancel waiting loop(if video is removed
  6878. // before has started)
  6879. select.removed = true;
  6880. select.remove();
  6881. var audioCount = $('#' + this.videoSpanId + '>audio').length;
  6882. var videoCount = $('#' + this.videoSpanId + '>video').length;
  6883. if (!audioCount && !videoCount) {
  6884. console.log("Remove whole user", this.videoSpanId);
  6885. if(this.connectionIndicator)
  6886. this.connectionIndicator.remove();
  6887. // Remove whole container
  6888. this.container.remove();
  6889. this.VideoLayout.resizeThumbnails();
  6890. }
  6891. if (isVideo)
  6892. this.VideoLayout.updateRemovedVideo(this.resourceJid);
  6893. };
  6894. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  6895. if (!this.container)
  6896. return;
  6897. var self = this;
  6898. var isVideo = stream.getVideoTracks().length > 0;
  6899. var streamElement = SmallVideo.createStreamElement(sid, stream);
  6900. var newElementId = streamElement.id;
  6901. this.container.appendChild(streamElement);
  6902. var sel = $('#' + newElementId);
  6903. sel.hide();
  6904. // If the container is currently visible we attach the stream.
  6905. if (!isVideo
  6906. || (this.container.offsetParent !== null && isVideo)) {
  6907. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  6908. // when video playback starts
  6909. if (isVideo && stream.id !== 'mixedmslabel') {
  6910. var onPlayingHandler = function () {
  6911. // FIXME: why do i have to do this for FF?
  6912. APP.RTC.attachMediaStream(sel, stream);
  6913. self.VideoLayout.videoactive(sel, self.resourceJid);
  6914. sel.off("playing", onPlayingHandler);
  6915. };
  6916. sel.on("playing", onPlayingHandler);
  6917. }
  6918. APP.RTC.attachMediaStream(sel, stream);
  6919. }
  6920. var self = this;
  6921. stream.onended = function () {
  6922. console.log('stream ended', this);
  6923. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  6924. };
  6925. // Add click handler.
  6926. this.container.onclick = function (event) {
  6927. /*
  6928. * FIXME It turns out that videoThumb may not exist (if there is
  6929. * no actual video).
  6930. */
  6931. var videoThumb = $('#' + self.videoSpanId + '>video').get(0);
  6932. if (videoThumb) {
  6933. self.VideoLayout.handleVideoThumbClicked(
  6934. false,
  6935. self.resourceJid);
  6936. }
  6937. event.stopPropagation();
  6938. event.preventDefault();
  6939. return false;
  6940. };
  6941. //FIXME
  6942. // Add hover handler
  6943. $(this.container).hover(
  6944. function() {
  6945. self.showDisplayName(true);
  6946. },
  6947. function() {
  6948. var videoSrc = null;
  6949. if ($('#' + self.videoSpanId + '>video')
  6950. && $('#' + self.videoSpanId + '>video').length > 0) {
  6951. videoSrc = APP.RTC.getVideoSrc($('#' + self.videoSpanId + '>video').get(0));
  6952. }
  6953. // If the video has been "pinned" by the user we want to
  6954. // keep the display name on place.
  6955. if (!LargeVideo.isLargeVideoVisible()
  6956. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6957. self.showDisplayName(false);
  6958. }
  6959. );
  6960. }
  6961. /**
  6962. * Show/hide peer container for the given resourceJid.
  6963. */
  6964. RemoteVideo.prototype.showPeerContainer = function (state) {
  6965. if (!this.container)
  6966. return;
  6967. var isHide = state === 'hide';
  6968. var resizeThumbnails = false;
  6969. if (!isHide) {
  6970. if (!$(this.container).is(':visible')) {
  6971. resizeThumbnails = true;
  6972. $(this.container).show();
  6973. }
  6974. this.showAvatar(state !== 'show');
  6975. }
  6976. else if ($(this.container).is(':visible') && isHide)
  6977. {
  6978. resizeThumbnails = true;
  6979. $(this.container).hide();
  6980. if(this.connectionIndicator)
  6981. this.connectionIndicator.hide();
  6982. }
  6983. if (resizeThumbnails) {
  6984. this.VideoLayout.resizeThumbnails();
  6985. }
  6986. // We want to be able to pin a participant from the contact list, even
  6987. // if he's not in the lastN set!
  6988. // ContactList.setClickable(resourceJid, !isHide);
  6989. };
  6990. RemoteVideo.prototype.removeConnectionIndicator = function () {
  6991. if(this.connectionIndicator)
  6992. this.connectionIndicator.remove();
  6993. }
  6994. RemoteVideo.prototype.hideConnectionIndicator = function () {
  6995. if(this.connectionIndicator)
  6996. this.connectionIndicator.hide();
  6997. }
  6998. /**
  6999. * Updates the remote video menu.
  7000. *
  7001. * @param jid the jid indicating the video for which we're adding a menu.
  7002. * @param isMuted indicates the current mute state
  7003. */
  7004. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  7005. var muteMenuItem
  7006. = $('#remote_popupmenu_'
  7007. + this.resourceJid
  7008. + '>li>a.mutelink');
  7009. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7010. if (muteMenuItem.length) {
  7011. var muteLink = muteMenuItem.get(0);
  7012. if (isMuted === 'true') {
  7013. muteLink.innerHTML = mutedIndicator + ' Muted';
  7014. muteLink.className = 'mutelink disabled';
  7015. }
  7016. else {
  7017. muteLink.innerHTML = mutedIndicator + ' Mute';
  7018. muteLink.className = 'mutelink';
  7019. }
  7020. }
  7021. }
  7022. /**
  7023. * Sets the display name for the given video span id.
  7024. */
  7025. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  7026. if (!this.container) {
  7027. console.warn(
  7028. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  7029. return;
  7030. }
  7031. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7032. // If we already have a display name for this video.
  7033. if (nameSpan.length > 0) {
  7034. if (displayName && displayName.length > 0)
  7035. {
  7036. $('#' + this.videoSpanId + '_name').html(displayName);
  7037. }
  7038. else if (key && key.length > 0)
  7039. {
  7040. var nameHtml = APP.translation.generateTranslationHTML(key);
  7041. $('#' + this.videoSpanId + '_name').html(nameHtml);
  7042. }
  7043. else
  7044. $('#' + this.videoSpanId + '_name').text(
  7045. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  7046. } else {
  7047. nameSpan = document.createElement('span');
  7048. nameSpan.className = 'displayname';
  7049. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7050. if (displayName && displayName.length > 0) {
  7051. nameSpan.innerText = displayName;
  7052. }
  7053. else
  7054. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  7055. nameSpan.id = this.videoSpanId + '_name';
  7056. }
  7057. }
  7058. /**
  7059. * Removes remote video menu element from video element identified by
  7060. * given <tt>videoElementId</tt>.
  7061. *
  7062. * @param videoElementId the id of local or remote video element.
  7063. */
  7064. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  7065. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  7066. if (menuSpan.length) {
  7067. menuSpan.remove();
  7068. }
  7069. }
  7070. RemoteVideo.createContainer = function (spanId) {
  7071. var container = document.createElement('span');
  7072. container.id = spanId;
  7073. container.className = 'videocontainer';
  7074. var remotes = document.getElementById('remoteVideos');
  7075. return remotes.appendChild(container);
  7076. };
  7077. module.exports = RemoteVideo;
  7078. },{"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  7079. var UIUtil = require("../util/UIUtil");
  7080. var LargeVideo = require("./LargeVideo");
  7081. function SmallVideo(){
  7082. this.isMuted = false;
  7083. this.hasAvatar = false;
  7084. }
  7085. function setVisibility(selector, show) {
  7086. if (selector && selector.length > 0) {
  7087. selector.css("visibility", show ? "visible" : "hidden");
  7088. }
  7089. }
  7090. SmallVideo.prototype.showDisplayName = function(isShow) {
  7091. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  7092. if (isShow) {
  7093. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  7094. nameSpan.setAttribute("style", "display:inline-block;");
  7095. }
  7096. else {
  7097. if (nameSpan)
  7098. nameSpan.setAttribute("style", "display:none;");
  7099. }
  7100. };
  7101. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  7102. if(!this.container)
  7103. return;
  7104. $("#" + this.videoSpanId + " > .noMic").remove();
  7105. $("#" + this.videoSpanId + " > .noVideo").remove();
  7106. if(!devices.audio)
  7107. {
  7108. this.container.appendChild(
  7109. document.createElement("div")).setAttribute("class","noMic");
  7110. }
  7111. if(!devices.video)
  7112. {
  7113. this.container.appendChild(
  7114. document.createElement("div")).setAttribute("class","noVideo");
  7115. }
  7116. if(!devices.audio && !devices.video)
  7117. {
  7118. $("#" + this.videoSpanId + " > .noMic").css("background-position", "75%");
  7119. $("#" + this.videoSpanId + " > .noVideo").css("background-position", "25%");
  7120. $("#" + this.videoSpanId + " > .noVideo").css("background-color", "transparent");
  7121. }
  7122. }
  7123. /**
  7124. * Shows the presence status message for the given video.
  7125. */
  7126. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  7127. if (!this.container) {
  7128. // No container
  7129. return;
  7130. }
  7131. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  7132. if (!statusSpan.length) {
  7133. //Add status span
  7134. statusSpan = document.createElement('span');
  7135. statusSpan.className = 'status';
  7136. statusSpan.id = this.videoSpanId + '_status';
  7137. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  7138. statusSpan = $('#' + this.videoSpanId + '>span.status');
  7139. }
  7140. // Display status
  7141. if (statusMsg && statusMsg.length) {
  7142. $('#' + this.videoSpanId + '_status').text(statusMsg);
  7143. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  7144. }
  7145. else {
  7146. // Hide
  7147. statusSpan.get(0).setAttribute("style", "display:none;");
  7148. }
  7149. };
  7150. /**
  7151. * Creates an audio or video stream element.
  7152. */
  7153. SmallVideo.createStreamElement = function (sid, stream) {
  7154. var isVideo = stream.getVideoTracks().length > 0;
  7155. var element = isVideo
  7156. ? document.createElement('video')
  7157. : document.createElement('audio');
  7158. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  7159. + sid + '_' + APP.RTC.getStreamID(stream);
  7160. element.id = id;
  7161. element.autoplay = true;
  7162. element.oncontextmenu = function () { return false; };
  7163. return element;
  7164. };
  7165. /**
  7166. * Updates the data for the indicator
  7167. * @param id the id of the indicator
  7168. * @param percent the percent for connection quality
  7169. * @param object the data
  7170. */
  7171. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  7172. if(this.connectionIndicator)
  7173. this.connectionIndicator.updateConnectionQuality(percent, object);
  7174. }
  7175. SmallVideo.prototype.hideIndicator = function () {
  7176. if(this.connectionIndicator)
  7177. this.connectionIndicator.hideIndicator();
  7178. }
  7179. /**
  7180. * Shows audio muted indicator over small videos.
  7181. * @param {string} isMuted
  7182. */
  7183. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  7184. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  7185. if (!isMuted) {
  7186. if (audioMutedSpan.length > 0) {
  7187. audioMutedSpan.popover('hide');
  7188. audioMutedSpan.remove();
  7189. }
  7190. }
  7191. else {
  7192. if(audioMutedSpan.length == 0 ) {
  7193. audioMutedSpan = document.createElement('span');
  7194. audioMutedSpan.className = 'audioMuted';
  7195. UIUtil.setTooltip(audioMutedSpan,
  7196. "videothumbnail.mute",
  7197. "top");
  7198. this.container.appendChild(audioMutedSpan);
  7199. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  7200. var mutedIndicator = document.createElement('i');
  7201. mutedIndicator.className = 'icon-mic-disabled';
  7202. audioMutedSpan.appendChild(mutedIndicator);
  7203. }
  7204. this.updateIconPositions();
  7205. }
  7206. this.isMuted = isMuted;
  7207. };
  7208. /**
  7209. * Shows video muted indicator over small videos.
  7210. */
  7211. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  7212. this.showAvatar(isMuted);
  7213. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  7214. if (isMuted === false) {
  7215. if (videoMutedSpan.length > 0) {
  7216. videoMutedSpan.remove();
  7217. }
  7218. }
  7219. else {
  7220. if(videoMutedSpan.length == 0) {
  7221. videoMutedSpan = document.createElement('span');
  7222. videoMutedSpan.className = 'videoMuted';
  7223. this.container.appendChild(videoMutedSpan);
  7224. var mutedIndicator = document.createElement('i');
  7225. mutedIndicator.className = 'icon-camera-disabled';
  7226. UIUtil.setTooltip(mutedIndicator,
  7227. "videothumbnail.videomute",
  7228. "top");
  7229. videoMutedSpan.appendChild(mutedIndicator);
  7230. //translate texts for muted indicator
  7231. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  7232. }
  7233. this.updateIconPositions();
  7234. }
  7235. };
  7236. SmallVideo.prototype.enableDominantSpeaker = function (isEnable)
  7237. {
  7238. var displayName = this.resourceJid;
  7239. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7240. if (nameSpan.length > 0)
  7241. displayName = nameSpan.html();
  7242. console.log("UI enable dominant speaker",
  7243. displayName,
  7244. this.resourceJid,
  7245. isEnable);
  7246. if (!this.container) {
  7247. return;
  7248. }
  7249. var video = $('#' + this.videoSpanId + '>video');
  7250. if (video && video.length > 0) {
  7251. if (isEnable) {
  7252. this.showDisplayName(LargeVideo.isLargeVideoOnTop());
  7253. if (!this.container.classList.contains("dominantspeaker"))
  7254. this.container.classList.add("dominantspeaker");
  7255. }
  7256. else {
  7257. this.showDisplayName(false);
  7258. if (this.container.classList.contains("dominantspeaker"))
  7259. this.container.classList.remove("dominantspeaker");
  7260. }
  7261. }
  7262. this.showAvatar();
  7263. };
  7264. SmallVideo.prototype.updateIconPositions = function () {
  7265. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  7266. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  7267. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  7268. if(connectionIndicator.length > 0
  7269. && connectionIndicator[0].style.display != "none") {
  7270. audioMutedSpan.css({right: "23px"});
  7271. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7272. }
  7273. else
  7274. {
  7275. audioMutedSpan.css({right: "0px"});
  7276. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7277. }
  7278. }
  7279. /**
  7280. * Creates the element indicating the moderator(owner) of the conference.
  7281. *
  7282. * @param parentElement the parent element where the owner indicator will
  7283. * be added
  7284. */
  7285. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  7286. // Show moderator indicator
  7287. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  7288. if (!indicatorSpan || indicatorSpan.length === 0) {
  7289. indicatorSpan = document.createElement('span');
  7290. indicatorSpan.className = 'focusindicator';
  7291. this.container.appendChild(indicatorSpan);
  7292. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  7293. }
  7294. if (indicatorSpan.children().length !== 0)
  7295. return;
  7296. var moderatorIndicator = document.createElement('i');
  7297. moderatorIndicator.className = 'fa fa-star';
  7298. indicatorSpan[0].appendChild(moderatorIndicator);
  7299. UIUtil.setTooltip(indicatorSpan[0],
  7300. "videothumbnail.moderator",
  7301. "top");
  7302. //translates text in focus indicators
  7303. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  7304. }
  7305. SmallVideo.prototype.getSrc = function () {
  7306. return APP.RTC.getVideoSrc($('#' + this.videoSpanId).find("video").get(0));
  7307. }
  7308. SmallVideo.prototype.focus = function(isFocused)
  7309. {
  7310. if(!isFocused) {
  7311. this.container.classList.remove("videoContainerFocused");
  7312. }
  7313. else
  7314. {
  7315. this.container.classList.add("videoContainerFocused");
  7316. }
  7317. }
  7318. SmallVideo.prototype.hasVideo = function () {
  7319. return $("#" + this.videoSpanId).find("video").length !== 0;
  7320. }
  7321. /**
  7322. * Hides or shows the user's avatar
  7323. * @param show whether we should show the avatar or not
  7324. * video because there is no dominant speaker and no focused speaker
  7325. */
  7326. SmallVideo.prototype.showAvatar = function (show) {
  7327. if(!this.hasAvatar)
  7328. return;
  7329. var video = $('#' + this.videoSpanId).find("video");
  7330. var avatar = $('#avatar_' + this.resourceJid);
  7331. if (show === undefined || show === null) {
  7332. if(!this.VideoLayout.isInLastN(this.resourceJid)) {
  7333. show = true;
  7334. }
  7335. else
  7336. {
  7337. show = APP.RTC.isVideoMuted(this.peerJid);
  7338. }
  7339. }
  7340. if (LargeVideo.showAvatar(this.resourceJid, show))
  7341. {
  7342. setVisibility(avatar, false);
  7343. setVisibility(video, false);
  7344. } else {
  7345. if (video && video.length > 0) {
  7346. setVisibility(video, !show);
  7347. }
  7348. setVisibility(avatar, show);
  7349. }
  7350. }
  7351. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  7352. var thumbnail = $('#' + this.videoSpanId);
  7353. var avatar = $('#avatar_' + this.resourceJid);
  7354. this.hasAvatar = true;
  7355. // set the avatar in the thumbnail
  7356. if (avatar && avatar.length > 0) {
  7357. avatar[0].src = thumbUrl;
  7358. } else {
  7359. if (thumbnail && thumbnail.length > 0) {
  7360. avatar = document.createElement('img');
  7361. avatar.id = 'avatar_' + this.resourceJid;
  7362. avatar.className = 'userAvatar';
  7363. avatar.src = thumbUrl;
  7364. thumbnail.append(avatar);
  7365. }
  7366. }
  7367. }
  7368. module.exports = SmallVideo;
  7369. },{"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  7370. var AudioLevels = require("../audio_levels/AudioLevels");
  7371. var Avatar = require("../avatar/Avatar");
  7372. var ContactList = require("../side_pannels/contactlist/ContactList");
  7373. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  7374. var UIEvents = require("../../../service/UI/UIEvents");
  7375. var RemoteVideo = require("./RemoteVideo");
  7376. var LargeVideo = require("./LargeVideo");
  7377. var LocalVideo = require("./LocalVideo");
  7378. var remoteVideos = {};
  7379. var localVideoThumbnail = null;
  7380. var currentDominantSpeaker = null;
  7381. var lastNCount = config.channelLastN;
  7382. var localLastNCount = config.channelLastN;
  7383. var localLastNSet = [];
  7384. var lastNEndpointsCache = [];
  7385. var lastNPickupJid = null;
  7386. var eventEmitter = null;
  7387. /**
  7388. * Currently focused video jid
  7389. * @type {String}
  7390. */
  7391. var focusedVideoResourceJid = null;
  7392. var VideoLayout = (function (my) {
  7393. my.init = function (emitter) {
  7394. eventEmitter = emitter;
  7395. localVideoThumbnail = new LocalVideo(VideoLayout);
  7396. VideoLayout.resizeLargeVideoContainer();
  7397. LargeVideo.init(VideoLayout, emitter);
  7398. };
  7399. my.isInLastN = function(resource) {
  7400. return lastNCount < 0 // lastN is disabled, return true
  7401. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  7402. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  7403. };
  7404. my.changeLocalStream = function (stream, isMuted) {
  7405. VideoLayout.changeLocalVideo(stream, isMuted);
  7406. };
  7407. my.changeLocalAudio = function(stream, isMuted) {
  7408. if(isMuted)
  7409. APP.UI.setAudioMuted(true, true);
  7410. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  7411. document.getElementById('localAudio').autoplay = true;
  7412. document.getElementById('localAudio').volume = 0;
  7413. };
  7414. my.changeLocalVideo = function(stream, isMuted) {
  7415. // Set default display name.
  7416. localVideoThumbnail.setDisplayName();
  7417. localVideoThumbnail.createConnectionIndicator();
  7418. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  7419. localVideoThumbnail.changeVideo(stream, isMuted);
  7420. LargeVideo.updateLargeVideo(
  7421. APP.xmpp.myResource(),
  7422. /* force update only before conference starts */
  7423. !APP.xmpp.isConferenceInProgress());
  7424. };
  7425. my.mucJoined = function () {
  7426. var myResourceJid = APP.xmpp.myResource();
  7427. localVideoThumbnail.joined(APP.xmpp.myJid());
  7428. if (!LargeVideo.getResourceJid())
  7429. LargeVideo.updateLargeVideo(myResourceJid, true);
  7430. };
  7431. /**
  7432. * Adds or removes icons for not available camera and microphone.
  7433. * @param resourceJid the jid of user
  7434. * @param devices available devices
  7435. */
  7436. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  7437. if(!devices)
  7438. return;
  7439. if(!resourceJid)
  7440. {
  7441. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  7442. }
  7443. else
  7444. {
  7445. if(remoteVideos[resourceJid])
  7446. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  7447. }
  7448. }
  7449. /**
  7450. * Checks if removed video is currently displayed and tries to display
  7451. * another one instead.
  7452. * @param removedVideoSrc src stream identifier of the video.
  7453. */
  7454. my.updateRemovedVideo = function(resourceJid) {
  7455. if (resourceJid === LargeVideo.getResourceJid()) {
  7456. // this is currently displayed as large
  7457. // pick the last visible video in the row
  7458. // if nobody else is left, this picks the local video
  7459. var pick
  7460. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  7461. .get(0);
  7462. if (!pick) {
  7463. console.info("Last visible video no longer exists");
  7464. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  7465. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  7466. // Try local video
  7467. console.info("Fallback to local video...");
  7468. pick = $('#remoteVideos>span>span>video').get(0);
  7469. }
  7470. }
  7471. // mute if localvideo
  7472. if (pick) {
  7473. var container = pick.parentNode;
  7474. } else {
  7475. console.warn("Failed to elect large video");
  7476. container = $('#remoteVideos>span[id!="mixedstream"]:visible:last').get(0);
  7477. }
  7478. var jid = null;
  7479. if(container)
  7480. {
  7481. if(container.id == "localVideoWrapper")
  7482. {
  7483. jid = APP.xmpp.myResource();
  7484. }
  7485. else
  7486. {
  7487. jid = VideoLayout.getPeerContainerResourceJid(container);
  7488. }
  7489. }
  7490. else
  7491. return;
  7492. LargeVideo.updateLargeVideo(jid);
  7493. }
  7494. };
  7495. my.onRemoteStreamAdded = function (stream) {
  7496. if (stream.peerjid) {
  7497. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  7498. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  7499. remoteVideos[resourceJid].addRemoteStreamElement(
  7500. stream.sid,
  7501. stream.getOriginalStream(),
  7502. stream.ssrc);
  7503. }
  7504. };
  7505. my.getLargeVideoJid = function () {
  7506. return LargeVideo.getResourceJid();
  7507. };
  7508. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  7509. resourceJid) {
  7510. if(focusedVideoResourceJid) {
  7511. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  7512. if(oldSmallVideo)
  7513. oldSmallVideo.focus(false);
  7514. }
  7515. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  7516. // Unlock current focused.
  7517. if (focusedVideoResourceJid === resourceJid)
  7518. {
  7519. focusedVideoResourceJid = null;
  7520. // Enable the currently set dominant speaker.
  7521. if (currentDominantSpeaker) {
  7522. if(smallVideo && smallVideo.hasVideo())
  7523. {
  7524. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  7525. }
  7526. }
  7527. if (!noPinnedEndpointChangedEvent) {
  7528. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  7529. }
  7530. return;
  7531. }
  7532. // Lock new video
  7533. focusedVideoResourceJid = resourceJid;
  7534. // Update focused/pinned interface.
  7535. if (resourceJid)
  7536. {
  7537. if(smallVideo)
  7538. smallVideo.focus(true);
  7539. if (!noPinnedEndpointChangedEvent) {
  7540. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  7541. }
  7542. }
  7543. if (LargeVideo.getResourceJid() === resourceJid &&
  7544. LargeVideo.isLargeVideoOnTop()) {
  7545. return;
  7546. }
  7547. // Triggers a "video.selected" event. The "false" parameter indicates
  7548. // this isn't a prezi.
  7549. $(document).trigger("video.selected", [false]);
  7550. LargeVideo.updateLargeVideo(resourceJid);
  7551. $('audio').each(function (idx, el) {
  7552. el.volume = 0;
  7553. el.volume = 1;
  7554. });
  7555. };
  7556. /**
  7557. * Checks if container for participant identified by given peerJid exists
  7558. * in the document and creates it eventually.
  7559. *
  7560. * @param peerJid peer Jid to check.
  7561. * @param userId user email or id for setting the avatar
  7562. *
  7563. * @return Returns <tt>true</tt> if the peer container exists,
  7564. * <tt>false</tt> - otherwise
  7565. */
  7566. my.ensurePeerContainerExists = function(peerJid, userId) {
  7567. ContactList.ensureAddContact(peerJid, userId);
  7568. var resourceJid = Strophe.getResourceFromJid(peerJid);
  7569. if(!remoteVideos[resourceJid])
  7570. {
  7571. remoteVideos[resourceJid] = new RemoteVideo(peerJid, VideoLayout);
  7572. Avatar.setUserAvatar(peerJid, userId);
  7573. // In case this is not currently in the last n we don't show it.
  7574. if (localLastNCount
  7575. && localLastNCount > 0
  7576. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  7577. remoteVideos[resourceJid].showPeerContainer('hide');
  7578. }
  7579. else
  7580. VideoLayout.resizeThumbnails();
  7581. }
  7582. };
  7583. my.inputDisplayNameHandler = function (name) {
  7584. localVideoThumbnail.inputDisplayNameHandler(name);
  7585. };
  7586. my.videoactive = function (videoelem, resourceJid) {
  7587. videoelem.show();
  7588. VideoLayout.resizeThumbnails();
  7589. // Update the large video to the last added video only if there's no
  7590. // current dominant, focused speaker or prezi playing or update it to
  7591. // the current dominant speaker.
  7592. if ((!focusedVideoResourceJid &&
  7593. !currentDominantSpeaker &&
  7594. !require("../prezi/Prezi").isPresentationVisible()) ||
  7595. (resourceJid &&
  7596. currentDominantSpeaker === resourceJid)) {
  7597. LargeVideo.updateLargeVideo(resourceJid, true);
  7598. }
  7599. }
  7600. /**
  7601. * Shows the presence status message for the given video.
  7602. */
  7603. my.setPresenceStatus = function (resourceJid, statusMsg) {
  7604. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  7605. };
  7606. /**
  7607. * Shows a visual indicator for the moderator of the conference.
  7608. */
  7609. my.showModeratorIndicator = function () {
  7610. var isModerator = APP.xmpp.isModerator();
  7611. if (isModerator) {
  7612. localVideoThumbnail.createModeratorIndicatorElement();
  7613. }
  7614. var members = APP.xmpp.getMembers();
  7615. Object.keys(members).forEach(function (jid) {
  7616. if (Strophe.getResourceFromJid(jid) === 'focus') {
  7617. // Skip server side focus
  7618. return;
  7619. }
  7620. var resourceJid = Strophe.getResourceFromJid(jid);
  7621. var member = members[jid];
  7622. if (member.role === 'moderator') {
  7623. remoteVideos[resourceJid].removeRemoteVideoMenu();
  7624. remoteVideos[resourceJid].createModeratorIndicatorElement();
  7625. } else if (isModerator) {
  7626. // We are moderator, but user is not - add menu
  7627. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7628. remoteVideos[resourceJid].addRemoteVideoMenu();
  7629. }
  7630. }
  7631. });
  7632. };
  7633. /*
  7634. * Shows or hides the audio muted indicator over the local thumbnail video.
  7635. * @param {boolean} isMuted
  7636. */
  7637. my.showLocalAudioIndicator = function(isMuted) {
  7638. localVideoThumbnail.showAudioIndicator(isMuted);
  7639. };
  7640. /**
  7641. * Resizes the large video container.
  7642. */
  7643. my.resizeLargeVideoContainer = function () {
  7644. LargeVideo.resize();
  7645. VideoLayout.resizeThumbnails();
  7646. LargeVideo.position();
  7647. };
  7648. /**
  7649. * Resizes thumbnails.
  7650. */
  7651. my.resizeThumbnails = function(animate) {
  7652. var videoSpaceWidth = $('#remoteVideos').width();
  7653. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7654. var width = thumbnailSize[0];
  7655. var height = thumbnailSize[1];
  7656. $('.userAvatar').css('left', (width - height) / 2);
  7657. if(animate)
  7658. {
  7659. $('#remoteVideos').animate({
  7660. height: height
  7661. },
  7662. {
  7663. queue: false,
  7664. duration: 500
  7665. });
  7666. $('#remoteVideos>span').animate({
  7667. height: height,
  7668. width: width
  7669. },
  7670. {
  7671. queue: false,
  7672. duration: 500,
  7673. complete: function () {
  7674. $(document).trigger(
  7675. "remotevideo.resized",
  7676. [width,
  7677. height]);
  7678. }
  7679. });
  7680. }
  7681. else
  7682. {
  7683. // size videos so that while keeping AR and max height, we have a
  7684. // nice fit
  7685. $('#remoteVideos').height(height);
  7686. $('#remoteVideos>span').width(width);
  7687. $('#remoteVideos>span').height(height);
  7688. $(document).trigger("remotevideo.resized", [width, height]);
  7689. }
  7690. };
  7691. /**
  7692. * Calculates the thumbnail size.
  7693. *
  7694. * @param videoSpaceWidth the width of the video space
  7695. */
  7696. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7697. // Calculate the available height, which is the inner window height minus
  7698. // 39px for the header minus 2px for the delimiter lines on the top and
  7699. // bottom of the large video, minus the 36px space inside the remoteVideos
  7700. // container used for highlighting shadow.
  7701. var availableHeight = 100;
  7702. var numvids = $('#remoteVideos>span:visible').length;
  7703. if (localLastNCount && localLastNCount > 0) {
  7704. numvids = Math.min(localLastNCount + 1, numvids);
  7705. }
  7706. // Remove the 3px borders arround videos and border around the remote
  7707. // videos area and the 4 pixels between the local video and the others
  7708. //TODO: Find out where the 4 pixels come from and remove them
  7709. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7710. var availableWidth = availableWinWidth / numvids;
  7711. var aspectRatio = 16.0 / 9.0;
  7712. var maxHeight = Math.min(160, availableHeight);
  7713. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7714. if (availableHeight < availableWidth / aspectRatio) {
  7715. availableWidth = Math.floor(availableHeight * aspectRatio);
  7716. }
  7717. return [availableWidth, availableHeight];
  7718. };
  7719. /**
  7720. * Returns the corresponding resource jid to the given peer container
  7721. * DOM element.
  7722. *
  7723. * @return the corresponding resource jid to the given peer container
  7724. * DOM element
  7725. */
  7726. my.getPeerContainerResourceJid = function (containerElement) {
  7727. var i = containerElement.id.indexOf('participant_');
  7728. if (i >= 0)
  7729. return containerElement.id.substring(i + 12);
  7730. };
  7731. /**
  7732. * On contact list item clicked.
  7733. */
  7734. $(ContactList).bind('contactclicked', function(event, jid) {
  7735. if (!jid) {
  7736. return;
  7737. }
  7738. var resource = Strophe.getResourceFromJid(jid);
  7739. var videoContainer = $("#participant_" + resource);
  7740. if (videoContainer.length > 0) {
  7741. var videoThumb = $('video', videoContainer).get(0);
  7742. // It is not always the case that a videoThumb exists (if there is
  7743. // no actual video).
  7744. if (videoThumb) {
  7745. if (videoThumb.src && videoThumb.src != '') {
  7746. // We have a video src, great! Let's update the large video
  7747. // now.
  7748. VideoLayout.handleVideoThumbClicked(
  7749. false,
  7750. Strophe.getResourceFromJid(jid));
  7751. } else {
  7752. // If we don't have a video src for jid, there's absolutely
  7753. // no point in calling handleVideoThumbClicked; Quite
  7754. // simply, it won't work because it needs an src to attach
  7755. // to the large video.
  7756. //
  7757. // Instead, we trigger the pinned endpoint changed event to
  7758. // let the bridge adjust its lastN set for myjid and store
  7759. // the pinned user in the lastNPickupJid variable to be
  7760. // picked up later by the lastN changed event handler.
  7761. lastNPickupJid = jid;
  7762. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7763. Strophe.getResourceFromJid(jid));
  7764. }
  7765. } else if (jid == APP.xmpp.myJid()) {
  7766. $("#localVideoContainer").click();
  7767. }
  7768. }
  7769. });
  7770. /**
  7771. * On audio muted event.
  7772. */
  7773. my.onAudioMute = function (jid, isMuted) {
  7774. var resourceJid = Strophe.getResourceFromJid(jid);
  7775. if (resourceJid === APP.xmpp.myResource()) {
  7776. localVideoThumbnail.showAudioIndicator(isMuted);
  7777. } else {
  7778. VideoLayout.ensurePeerContainerExists(jid);
  7779. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  7780. if (APP.xmpp.isModerator()) {
  7781. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  7782. }
  7783. }
  7784. };
  7785. /**
  7786. * On video muted event.
  7787. */
  7788. my.onVideoMute = function (jid, value) {
  7789. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, value))
  7790. return;
  7791. if (jid === APP.xmpp.myJid()) {
  7792. localVideoThumbnail.showVideoIndicator(value);
  7793. } else {
  7794. VideoLayout.ensurePeerContainerExists(jid);
  7795. remoteVideos[Strophe.getResourceFromJid(jid)].showVideoIndicator(value);
  7796. }
  7797. };
  7798. /**
  7799. * Display name changed.
  7800. */
  7801. my.onDisplayNameChanged =
  7802. function (jid, displayName, status) {
  7803. if (jid === 'localVideoContainer'
  7804. || jid === APP.xmpp.myJid()) {
  7805. localVideoThumbnail.setDisplayName(displayName);
  7806. } else {
  7807. VideoLayout.ensurePeerContainerExists(jid);
  7808. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  7809. displayName,
  7810. status);
  7811. }
  7812. };
  7813. /**
  7814. * On dominant speaker changed event.
  7815. */
  7816. my.onDominantSpeakerChanged = function (resourceJid) {
  7817. // We ignore local user events.
  7818. if (resourceJid === APP.xmpp.myResource())
  7819. return;
  7820. var members = APP.xmpp.getMembers();
  7821. // Update the current dominant speaker.
  7822. if (resourceJid !== currentDominantSpeaker) {
  7823. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7824. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7825. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7826. !members[currentJID].displayName)) {
  7827. remoteVideos[resourceJid].setDisplayName(null);
  7828. }
  7829. if(resourceJid && (!members || !members[newJID] ||
  7830. !members[newJID].displayName)) {
  7831. remoteVideos[resourceJid].setDisplayName(null,
  7832. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7833. }
  7834. currentDominantSpeaker = resourceJid;
  7835. } else {
  7836. return;
  7837. }
  7838. // Obtain container for new dominant speaker.
  7839. var container = document.getElementById(
  7840. 'participant_' + resourceJid);
  7841. // Local video will not have container found, but that's ok
  7842. // since we don't want to switch to local video.
  7843. if (container && !focusedVideoResourceJid)
  7844. {
  7845. var video = container.getElementsByTagName("video");
  7846. // Update the large video if the video source is already available,
  7847. // otherwise wait for the "videoactive.jingle" event.
  7848. if (video.length && video[0].currentTime > 0) {
  7849. LargeVideo.updateLargeVideo(resourceJid);
  7850. }
  7851. }
  7852. };
  7853. /**
  7854. * On last N change event.
  7855. *
  7856. * @param lastNEndpoints the list of last N endpoints
  7857. * @param endpointsEnteringLastN the list currently entering last N
  7858. * endpoints
  7859. */
  7860. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7861. endpointsEnteringLastN,
  7862. stream) {
  7863. if (lastNCount !== lastNEndpoints.length)
  7864. lastNCount = lastNEndpoints.length;
  7865. lastNEndpointsCache = lastNEndpoints;
  7866. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7867. //
  7868. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7869. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7870. // so E sees them. C is only in E's local LastN set.
  7871. //
  7872. // If F starts talking and LastN = 3, then E should see thumbnails for
  7873. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7874. // enters E's local LastN ejecting C.
  7875. // Increase the local LastN set size, if necessary.
  7876. if (lastNCount > localLastNCount) {
  7877. localLastNCount = lastNCount;
  7878. }
  7879. // Update the local LastN set preserving the order in which the
  7880. // endpoints appeared in the LastN/local LastN set.
  7881. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7882. for (var i = 0; i < localLastNSet.length; i++) {
  7883. if (nextLocalLastNSet.length >= localLastNCount) {
  7884. break;
  7885. }
  7886. var resourceJid = localLastNSet[i];
  7887. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7888. nextLocalLastNSet.push(resourceJid);
  7889. }
  7890. }
  7891. localLastNSet = nextLocalLastNSet;
  7892. var updateLargeVideo = false;
  7893. // Handle LastN/local LastN changes.
  7894. $('#remoteVideos>span').each(function( index, element ) {
  7895. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7896. var isReceived = true;
  7897. if (resourceJid
  7898. && lastNEndpoints.indexOf(resourceJid) < 0
  7899. && localLastNSet.indexOf(resourceJid) < 0) {
  7900. console.log("Remove from last N", resourceJid);
  7901. remoteVideos[resourceJid].showPeerContainer('hide');
  7902. isReceived = false;
  7903. } else if (resourceJid
  7904. && $('#participant_' + resourceJid).is(':visible')
  7905. && lastNEndpoints.indexOf(resourceJid) < 0
  7906. && localLastNSet.indexOf(resourceJid) >= 0) {
  7907. remoteVideos[resourceJid].showPeerContainer('avatar');
  7908. isReceived = false;
  7909. }
  7910. if (!isReceived) {
  7911. // resourceJid has dropped out of the server side lastN set, so
  7912. // it is no longer being received. If resourceJid was being
  7913. // displayed in the large video we have to switch to another
  7914. // user.
  7915. if (!updateLargeVideo && resourceJid === LargeVideo.getResourceJid()) {
  7916. updateLargeVideo = true;
  7917. }
  7918. }
  7919. });
  7920. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7921. endpointsEnteringLastN = lastNEndpoints;
  7922. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7923. endpointsEnteringLastN.forEach(function (resourceJid) {
  7924. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7925. remoteVideos[resourceJid].showPeerContainer('show');
  7926. if (!isVisible) {
  7927. console.log("Add to last N", resourceJid);
  7928. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7929. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7930. var sel = $('#participant_' + resourceJid + '>video');
  7931. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  7932. if (lastNPickupJid == mediaStream.peerjid) {
  7933. // Clean up the lastN pickup jid.
  7934. lastNPickupJid = null;
  7935. // Don't fire the events again, they've already
  7936. // been fired in the contact list click handler.
  7937. VideoLayout.handleVideoThumbClicked(
  7938. false,
  7939. Strophe.getResourceFromJid(mediaStream.peerjid));
  7940. updateLargeVideo = false;
  7941. }
  7942. remoteVideos[resourceJid].waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream);
  7943. }
  7944. });
  7945. }
  7946. // The endpoint that was being shown in the large video has dropped out
  7947. // of the lastN set and there was no lastN pickup jid. We need to update
  7948. // the large video now.
  7949. if (updateLargeVideo) {
  7950. var resource, container, src;
  7951. var myResource
  7952. = APP.xmpp.myResource();
  7953. // Find out which endpoint to show in the large video.
  7954. for (var i = 0; i < lastNEndpoints.length; i++) {
  7955. resource = lastNEndpoints[i];
  7956. if (!resource || resource === myResource)
  7957. continue;
  7958. // videoSrcToSsrc needs to be update for this call to succeed.
  7959. LargeVideo.updateLargeVideo(resource);
  7960. break;
  7961. }
  7962. }
  7963. };
  7964. /**
  7965. * Updates local stats
  7966. * @param percent
  7967. * @param object
  7968. */
  7969. my.updateLocalConnectionStats = function (percent, object) {
  7970. var resolution = null;
  7971. if(object.resolution !== null)
  7972. {
  7973. resolution = object.resolution;
  7974. object.resolution = resolution[APP.xmpp.myJid()];
  7975. delete resolution[APP.xmpp.myJid()];
  7976. }
  7977. localVideoThumbnail.updateStatsIndicator(percent, object);
  7978. for(var jid in resolution)
  7979. {
  7980. if(resolution[jid] === null)
  7981. continue;
  7982. var resourceJid = Strophe.getResourceFromJid(jid);
  7983. if(remoteVideos[resourceJid] && remoteVideos[resourceJid].connectionIndicator)
  7984. {
  7985. remoteVideos[resourceJid].connectionIndicator.updateResolution(resolution[jid]);
  7986. }
  7987. }
  7988. };
  7989. /**
  7990. * Updates remote stats.
  7991. * @param jid the jid associated with the stats
  7992. * @param percent the connection quality percent
  7993. * @param object the stats data
  7994. */
  7995. my.updateConnectionStats = function (jid, percent, object) {
  7996. var resourceJid = Strophe.getResourceFromJid(jid);
  7997. if(remoteVideos[resourceJid])
  7998. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  7999. };
  8000. /**
  8001. * Removes the connection
  8002. * @param jid
  8003. */
  8004. my.removeConnectionIndicator = function (jid) {
  8005. remoteVideos[Strophe.getResourceFromJid(jid)].removeConnectionIndicator();
  8006. };
  8007. /**
  8008. * Hides the connection indicator
  8009. * @param jid
  8010. */
  8011. my.hideConnectionIndicator = function (jid) {
  8012. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  8013. };
  8014. /**
  8015. * Hides all the indicators
  8016. */
  8017. my.onStatsStop = function () {
  8018. for(var video in remoteVideos)
  8019. {
  8020. remoteVideos[video].hideIndicator();
  8021. }
  8022. localVideoThumbnail.hideIndicator();
  8023. };
  8024. my.participantLeft = function (jid) {
  8025. // Unlock large video
  8026. var resourceJid = Strophe.getResourceFromJid(jid);
  8027. if (focusedVideoResourceJid === resourceJid)
  8028. {
  8029. console.info("Focused video owner has left the conference");
  8030. focusedVideoResourceJid = null;
  8031. }
  8032. };
  8033. my.onVideoTypeChanged = function (jid) {
  8034. LargeVideo.onVideoTypeChanged(jid);
  8035. };
  8036. my.showMore = function (jid) {
  8037. if(APP.xmpp.myJid = jid)
  8038. {
  8039. localVideoThumbnail.connectionIndicator.showMore();
  8040. }
  8041. else
  8042. {
  8043. remoteVideos[Strophe.getResourceFromJid(jid)].connectionIndicator.showMore();
  8044. }
  8045. };
  8046. my.addPreziContainer = function (id) {
  8047. return RemoteVideo.createContainer(id);
  8048. };
  8049. my.setLargeVideoVisible = function (isVisible) {
  8050. LargeVideo.setLargeVideoVisible(isVisible);
  8051. if(!isVisible && focusedVideoResourceJid)
  8052. {
  8053. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8054. if(smallVideo)
  8055. smallVideo.focus(false);
  8056. smallVideo.showAvatar();
  8057. focusedVideoResourceJid = null;
  8058. }
  8059. };
  8060. /**
  8061. * Resizes the video area
  8062. * @param completeFunction a function to be called when the video space is resized
  8063. */
  8064. my.resizeVideoArea = function(isVisible, completeFunction) {
  8065. LargeVideo.resizeVideoAreaAnimated(isVisible, completeFunction);
  8066. VideoLayout.resizeThumbnails(true);
  8067. };
  8068. my.getSmallVideo = function (resourceJid) {
  8069. if(resourceJid == APP.xmpp.myResource())
  8070. {
  8071. return localVideoThumbnail;
  8072. }
  8073. else
  8074. {
  8075. if(!remoteVideos[resourceJid])
  8076. return null;
  8077. return remoteVideos[resourceJid];
  8078. }
  8079. };
  8080. my.userAvatarChanged = function(resourceJid, thumbUrl)
  8081. {
  8082. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8083. if(smallVideo)
  8084. smallVideo.avatarChanged(thumbUrl);
  8085. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  8086. };
  8087. return my;
  8088. }(VideoLayout || {}));
  8089. module.exports = VideoLayout;
  8090. },{"../../../service/RTC/MediaStreamTypes":98,"../../../service/UI/UIEvents":103,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  8091. //var nouns = [
  8092. //];
  8093. var pluralNouns = [
  8094. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  8095. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  8096. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  8097. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  8098. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  8099. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  8100. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  8101. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  8102. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  8103. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  8104. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  8105. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  8106. ];
  8107. //var places = [
  8108. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  8109. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  8110. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  8111. // "Bridge"
  8112. //];
  8113. var verbs = [
  8114. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  8115. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  8116. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  8117. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  8118. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  8119. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  8120. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  8121. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  8122. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  8123. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  8124. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  8125. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  8126. ];
  8127. var adverbs = [
  8128. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  8129. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  8130. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  8131. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  8132. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  8133. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  8134. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  8135. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  8136. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  8137. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  8138. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  8139. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  8140. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  8141. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  8142. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  8143. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  8144. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  8145. ];
  8146. var adjectives = [
  8147. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  8148. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  8149. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  8150. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  8151. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  8152. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  8153. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  8154. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  8155. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  8156. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  8157. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  8158. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  8159. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  8160. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  8161. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  8162. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  8163. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  8164. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  8165. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  8166. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  8167. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  8168. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  8169. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  8170. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  8171. "Zealous"
  8172. ];
  8173. //var pronouns = [
  8174. //];
  8175. //var conjunctions = [
  8176. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  8177. //];
  8178. /*
  8179. * Maps a string (category name) to the array of words from that category.
  8180. */
  8181. var CATEGORIES =
  8182. {
  8183. //"_NOUN_": nouns,
  8184. "_PLURALNOUN_": pluralNouns,
  8185. //"_PLACE_": places,
  8186. "_VERB_": verbs,
  8187. "_ADVERB_": adverbs,
  8188. "_ADJECTIVE_": adjectives
  8189. //"_PRONOUN_": pronouns,
  8190. //"_CONJUNCTION_": conjunctions,
  8191. };
  8192. var PATTERNS = [
  8193. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  8194. // BeautifulFungiOrSpaghetti
  8195. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  8196. // AmazinglyScaryToy
  8197. //"_ADVERB__ADJECTIVE__NOUN_",
  8198. // NeitherTrashNorRifle
  8199. //"Neither_NOUN_Nor_NOUN_",
  8200. //"Either_NOUN_Or_NOUN_",
  8201. // EitherCopulateOrInvestigate
  8202. //"Either_VERB_Or_VERB_",
  8203. //"Neither_VERB_Nor_VERB_",
  8204. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  8205. //"The_ADVERB__ADJECTIVE__NOUN_",
  8206. //"The_ADVERB__ADJECTIVE__NOUN_s",
  8207. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  8208. // WolvesComputeBadly
  8209. //"_PLURALNOUN__VERB__ADVERB_",
  8210. // UniteFacilitateAndMerge
  8211. //"_VERB__VERB_And_VERB_",
  8212. //NastyWitchesAtThePub
  8213. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  8214. ];
  8215. /*
  8216. * Returns a random element from the array 'arr'
  8217. */
  8218. function randomElement(arr)
  8219. {
  8220. return arr[Math.floor(Math.random() * arr.length)];
  8221. }
  8222. /*
  8223. * Returns true if the string 's' contains one of the
  8224. * template strings.
  8225. */
  8226. function hasTemplate(s)
  8227. {
  8228. for (var template in CATEGORIES){
  8229. if (s.indexOf(template) >= 0){
  8230. return true;
  8231. }
  8232. }
  8233. }
  8234. /**
  8235. * Generates new room name.
  8236. */
  8237. var RoomNameGenerator = {
  8238. generateRoomWithoutSeparator: function()
  8239. {
  8240. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  8241. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  8242. var name = randomElement(PATTERNS);
  8243. var word;
  8244. while (hasTemplate(name)){
  8245. for (var template in CATEGORIES){
  8246. word = randomElement(CATEGORIES[template]);
  8247. name = name.replace(template, word);
  8248. }
  8249. }
  8250. return name;
  8251. }
  8252. }
  8253. module.exports = RoomNameGenerator;
  8254. },{}],41:[function(require,module,exports){
  8255. var animateTimeout, updateTimeout;
  8256. var RoomNameGenerator = require("./RoomnameGenerator");
  8257. function enter_room()
  8258. {
  8259. var val = $("#enter_room_field").val();
  8260. if(!val) {
  8261. val = $("#enter_room_field").attr("room_name");
  8262. }
  8263. if (val) {
  8264. window.location.pathname = "/" + val;
  8265. }
  8266. }
  8267. function animate(word) {
  8268. var currentVal = $("#enter_room_field").attr("placeholder");
  8269. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  8270. animateTimeout = setTimeout(function() {
  8271. animate(word.substring(1, word.length))
  8272. }, 70);
  8273. }
  8274. function update_roomname()
  8275. {
  8276. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  8277. $("#enter_room_field").attr("room_name", word);
  8278. $("#enter_room_field").attr("placeholder", "");
  8279. clearTimeout(animateTimeout);
  8280. animate(word);
  8281. updateTimeout = setTimeout(update_roomname, 10000);
  8282. }
  8283. function setupWelcomePage()
  8284. {
  8285. $("#videoconference_page").hide();
  8286. $("#domain_name").text(
  8287. window.location.protocol + "//" + window.location.host + "/");
  8288. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  8289. var leftWatermarkDiv
  8290. = $("#welcome_page_header div[class='watermark leftwatermark']");
  8291. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  8292. {
  8293. leftWatermarkDiv.css({display: 'block'});
  8294. leftWatermarkDiv.parent().get(0).href
  8295. = interfaceConfig.JITSI_WATERMARK_LINK;
  8296. }
  8297. }
  8298. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  8299. var rightWatermarkDiv
  8300. = $("#welcome_page_header div[class='watermark rightwatermark']");
  8301. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  8302. rightWatermarkDiv.css({display: 'block'});
  8303. rightWatermarkDiv.parent().get(0).href
  8304. = interfaceConfig.BRAND_WATERMARK_LINK;
  8305. rightWatermarkDiv.get(0).style.backgroundImage
  8306. = "url(images/rightwatermark.png)";
  8307. }
  8308. }
  8309. if (interfaceConfig.SHOW_POWERED_BY) {
  8310. $("#welcome_page_header>a[class='poweredby']")
  8311. .css({display: 'block'});
  8312. }
  8313. $("#enter_room_button").click(function()
  8314. {
  8315. enter_room();
  8316. });
  8317. $("#enter_room_field").keydown(function (event) {
  8318. if (event.keyCode === 13 /* enter */) {
  8319. enter_room();
  8320. }
  8321. });
  8322. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  8323. var updateTimeout;
  8324. var animateTimeout;
  8325. $("#reload_roomname").click(function () {
  8326. clearTimeout(updateTimeout);
  8327. clearTimeout(animateTimeout);
  8328. update_roomname();
  8329. });
  8330. $("#reload_roomname").show();
  8331. update_roomname();
  8332. }
  8333. $("#disable_welcome").click(function () {
  8334. window.localStorage.welcomePageDisabled
  8335. = $("#disable_welcome").is(":checked");
  8336. });
  8337. }
  8338. module.exports = setupWelcomePage;
  8339. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  8340. var params = {};
  8341. function getConfigParamsFromUrl() {
  8342. if(!location.hash)
  8343. return {};
  8344. var hash = location.hash.substr(1);
  8345. var result = {};
  8346. hash.split("&").forEach(function(part) {
  8347. var item = part.split("=");
  8348. result[item[0]] = JSON.parse(
  8349. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  8350. });
  8351. return result;
  8352. }
  8353. params = getConfigParamsFromUrl();
  8354. var URLProcessor = {
  8355. setConfigParametersFromUrl: function () {
  8356. for(var k in params)
  8357. {
  8358. if(typeof k !== "string" || k.indexOf("config.") === -1)
  8359. continue;
  8360. var v = params[k];
  8361. var confKey = k.substr(7);
  8362. if(config[confKey] && typeof config[confKey] !== typeof v)
  8363. {
  8364. console.warn("The type of " + k +
  8365. " is wrong. That parameter won't be updated in config.js.");
  8366. continue;
  8367. }
  8368. config[confKey] = v;
  8369. }
  8370. }
  8371. };
  8372. module.exports = URLProcessor;
  8373. },{}],43:[function(require,module,exports){
  8374. var EventEmitter = require("events");
  8375. var eventEmitter = new EventEmitter();
  8376. var CQEvents = require("../../service/connectionquality/CQEvents");
  8377. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8378. /**
  8379. * local stats
  8380. * @type {{}}
  8381. */
  8382. var stats = {};
  8383. /**
  8384. * remote stats
  8385. * @type {{}}
  8386. */
  8387. var remoteStats = {};
  8388. /**
  8389. * Interval for sending statistics to other participants
  8390. * @type {null}
  8391. */
  8392. var sendIntervalId = null;
  8393. /**
  8394. * Start statistics sending.
  8395. */
  8396. function startSendingStats() {
  8397. sendStats();
  8398. sendIntervalId = setInterval(sendStats, 10000);
  8399. }
  8400. /**
  8401. * Sends statistics to other participants
  8402. */
  8403. function sendStats() {
  8404. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  8405. }
  8406. /**
  8407. * Converts statistics to format for sending through XMPP
  8408. * @param stats the statistics
  8409. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8410. */
  8411. function convertToMUCStats(stats) {
  8412. return {
  8413. "bitrate_download": stats.bitrate.download,
  8414. "bitrate_upload": stats.bitrate.upload,
  8415. "packetLoss_total": stats.packetLoss.total,
  8416. "packetLoss_download": stats.packetLoss.download,
  8417. "packetLoss_upload": stats.packetLoss.upload
  8418. };
  8419. }
  8420. /**
  8421. * Converts statitistics to format used by VideoLayout
  8422. * @param stats
  8423. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8424. */
  8425. function parseMUCStats(stats) {
  8426. return {
  8427. bitrate: {
  8428. download: stats.bitrate_download,
  8429. upload: stats.bitrate_upload
  8430. },
  8431. packetLoss: {
  8432. total: stats.packetLoss_total,
  8433. download: stats.packetLoss_download,
  8434. upload: stats.packetLoss_upload
  8435. }
  8436. };
  8437. }
  8438. var ConnectionQuality = {
  8439. init: function () {
  8440. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8441. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8442. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8443. },
  8444. /**
  8445. * Updates the local statistics
  8446. * @param data new statistics
  8447. */
  8448. updateLocalStats: function (data) {
  8449. stats = data;
  8450. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8451. if (sendIntervalId == null) {
  8452. startSendingStats();
  8453. }
  8454. },
  8455. /**
  8456. * Updates remote statistics
  8457. * @param jid the jid associated with the statistics
  8458. * @param data the statistics
  8459. */
  8460. updateRemoteStats: function (jid, data) {
  8461. if (data == null || data.packetLoss_total == null) {
  8462. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8463. return;
  8464. }
  8465. remoteStats[jid] = parseMUCStats(data);
  8466. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8467. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8468. },
  8469. /**
  8470. * Stops statistics sending.
  8471. */
  8472. stopSendingStats: function () {
  8473. clearInterval(sendIntervalId);
  8474. sendIntervalId = null;
  8475. //notify UI about stopping statistics gathering
  8476. eventEmitter.emit(CQEvents.STOP);
  8477. },
  8478. /**
  8479. * Returns the local statistics.
  8480. */
  8481. getStats: function () {
  8482. return stats;
  8483. },
  8484. addListener: function (type, listener) {
  8485. eventEmitter.on(type, listener);
  8486. }
  8487. };
  8488. module.exports = ConnectionQuality;
  8489. },{"../../service/connectionquality/CQEvents":105,"../../service/xmpp/XMPPEvents":109,"events":1}],44:[function(require,module,exports){
  8490. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8491. getUserMediaWithConstraints */
  8492. /**
  8493. * Indicates that desktop stream is currently in use(for toggle purpose).
  8494. * @type {boolean}
  8495. */
  8496. var isUsingScreenStream = false;
  8497. /**
  8498. * Indicates that switch stream operation is in progress and prevent from
  8499. * triggering new events.
  8500. * @type {boolean}
  8501. */
  8502. var switchInProgress = false;
  8503. /**
  8504. * Method used to get screen sharing stream.
  8505. *
  8506. * @type {function (stream_callback, failure_callback}
  8507. */
  8508. var obtainDesktopStream = null;
  8509. /**
  8510. * Indicates whether desktop sharing extension is installed.
  8511. * @type {boolean}
  8512. */
  8513. var extInstalled = false;
  8514. /**
  8515. * Indicates whether update of desktop sharing extension is required.
  8516. * @type {boolean}
  8517. */
  8518. var extUpdateRequired = false;
  8519. /**
  8520. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8521. * it can be <tt>null</tt>.
  8522. *
  8523. * @type {null|boolean}
  8524. */
  8525. var _desktopSharingEnabled = null;
  8526. var EventEmitter = require("events");
  8527. var eventEmitter = new EventEmitter();
  8528. var DesktopSharingEventTypes
  8529. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8530. /**
  8531. * Method obtains desktop stream from WebRTC 'screen' source.
  8532. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8533. */
  8534. function obtainWebRTCScreen(streamCallback, failCallback) {
  8535. APP.RTC.getUserMediaWithConstraints(
  8536. ['screen'],
  8537. streamCallback,
  8538. failCallback
  8539. );
  8540. }
  8541. /**
  8542. * Constructs inline install URL for Chrome desktop streaming extension.
  8543. * The 'chromeExtensionId' must be defined in config.js.
  8544. * @returns {string}
  8545. */
  8546. function getWebStoreInstallUrl()
  8547. {
  8548. return "https://chrome.google.com/webstore/detail/" +
  8549. config.chromeExtensionId;
  8550. }
  8551. /**
  8552. * Checks whether extension update is required.
  8553. * @param minVersion minimal required version
  8554. * @param extVersion current extension version
  8555. * @returns {boolean}
  8556. */
  8557. function isUpdateRequired(minVersion, extVersion)
  8558. {
  8559. try
  8560. {
  8561. var s1 = minVersion.split('.');
  8562. var s2 = extVersion.split('.');
  8563. var len = Math.max(s1.length, s2.length);
  8564. for (var i = 0; i < len; i++)
  8565. {
  8566. var n1 = 0,
  8567. n2 = 0;
  8568. if (i < s1.length)
  8569. n1 = parseInt(s1[i]);
  8570. if (i < s2.length)
  8571. n2 = parseInt(s2[i]);
  8572. if (isNaN(n1) || isNaN(n2))
  8573. {
  8574. return true;
  8575. }
  8576. else if (n1 !== n2)
  8577. {
  8578. return n1 > n2;
  8579. }
  8580. }
  8581. // will happen if boths version has identical numbers in
  8582. // their components (even if one of them is longer, has more components)
  8583. return false;
  8584. }
  8585. catch (e)
  8586. {
  8587. console.error("Failed to parse extension version", e);
  8588. APP.UI.messageHandler.showError("dialog.error",
  8589. "dialog.detectext");
  8590. return true;
  8591. }
  8592. }
  8593. function checkExtInstalled(callback) {
  8594. if (!chrome.runtime) {
  8595. // No API, so no extension for sure
  8596. callback(false, false);
  8597. return;
  8598. }
  8599. chrome.runtime.sendMessage(
  8600. config.chromeExtensionId,
  8601. { getVersion: true },
  8602. function (response) {
  8603. if (!response || !response.version) {
  8604. // Communication failure - assume that no endpoint exists
  8605. console.warn(
  8606. "Extension not installed?: ", chrome.runtime.lastError);
  8607. callback(false, false);
  8608. return;
  8609. }
  8610. // Check installed extension version
  8611. var extVersion = response.version;
  8612. console.log('Extension version is: ' + extVersion);
  8613. var updateRequired
  8614. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8615. callback(!updateRequired, updateRequired);
  8616. }
  8617. );
  8618. }
  8619. function doGetStreamFromExtension(streamCallback, failCallback) {
  8620. // Sends 'getStream' msg to the extension.
  8621. // Extension id must be defined in the config.
  8622. chrome.runtime.sendMessage(
  8623. config.chromeExtensionId,
  8624. { getStream: true, sources: config.desktopSharingSources },
  8625. function (response) {
  8626. if (!response) {
  8627. failCallback(chrome.runtime.lastError);
  8628. return;
  8629. }
  8630. console.log("Response from extension: " + response);
  8631. if (response.streamId) {
  8632. APP.RTC.getUserMediaWithConstraints(
  8633. ['desktop'],
  8634. function (stream) {
  8635. streamCallback(stream);
  8636. },
  8637. failCallback,
  8638. null, null, null,
  8639. response.streamId);
  8640. } else {
  8641. failCallback("Extension failed to get the stream");
  8642. }
  8643. }
  8644. );
  8645. }
  8646. /**
  8647. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8648. * stream for returned stream token.
  8649. */
  8650. function obtainScreenFromExtension(streamCallback, failCallback) {
  8651. if (extInstalled) {
  8652. doGetStreamFromExtension(streamCallback, failCallback);
  8653. } else {
  8654. if (extUpdateRequired) {
  8655. alert(
  8656. 'Jitsi Desktop Streamer requires update. ' +
  8657. 'Changes will take effect after next Chrome restart.');
  8658. }
  8659. chrome.webstore.install(
  8660. getWebStoreInstallUrl(),
  8661. function (arg) {
  8662. console.log("Extension installed successfully", arg);
  8663. extInstalled = true;
  8664. // We need to give a moment for the endpoint to become available
  8665. window.setTimeout(function () {
  8666. doGetStreamFromExtension(streamCallback, failCallback);
  8667. }, 500);
  8668. },
  8669. function (arg) {
  8670. console.log("Failed to install the extension", arg);
  8671. failCallback(arg);
  8672. APP.UI.messageHandler.showError("dialog.error",
  8673. "dialog.failtoinstall");
  8674. }
  8675. );
  8676. }
  8677. }
  8678. /**
  8679. * Call this method to toggle desktop sharing feature.
  8680. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8681. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8682. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8683. * enabled), pass any other string or nothing in order to disable this
  8684. * feature completely.
  8685. */
  8686. function setDesktopSharing(method) {
  8687. // Check if we are running chrome
  8688. if (!navigator.webkitGetUserMedia) {
  8689. obtainDesktopStream = null;
  8690. console.info("Desktop sharing disabled");
  8691. } else if (method == "ext") {
  8692. obtainDesktopStream = obtainScreenFromExtension;
  8693. console.info("Using Chrome extension for desktop sharing");
  8694. } else if (method == "webrtc") {
  8695. obtainDesktopStream = obtainWebRTCScreen;
  8696. console.info("Using Chrome WebRTC for desktop sharing");
  8697. }
  8698. // Reset enabled cache
  8699. _desktopSharingEnabled = null;
  8700. }
  8701. /**
  8702. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8703. * config.js to support inline installs. Host site must be selected as main
  8704. * website of published extension.
  8705. */
  8706. function initInlineInstalls()
  8707. {
  8708. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8709. }
  8710. function getVideoStreamFailed(error) {
  8711. console.error("Failed to obtain the stream to switch to", error);
  8712. switchInProgress = false;
  8713. isUsingScreenStream = false;
  8714. newStreamCreated(null);
  8715. }
  8716. function getDesktopStreamFailed(error) {
  8717. console.error("Failed to obtain the stream to switch to", error);
  8718. switchInProgress = false;
  8719. }
  8720. function streamSwitchDone() {
  8721. switchInProgress = false;
  8722. eventEmitter.emit(
  8723. DesktopSharingEventTypes.SWITCHING_DONE,
  8724. isUsingScreenStream);
  8725. }
  8726. function newStreamCreated(stream)
  8727. {
  8728. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8729. stream, isUsingScreenStream, streamSwitchDone);
  8730. }
  8731. module.exports = {
  8732. isUsingScreenStream: function () {
  8733. return isUsingScreenStream;
  8734. },
  8735. /**
  8736. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8737. * and enabled.
  8738. */
  8739. isDesktopSharingEnabled: function () {
  8740. if (_desktopSharingEnabled === null) {
  8741. if (obtainDesktopStream === obtainScreenFromExtension) {
  8742. // Parse chrome version
  8743. var userAgent = navigator.userAgent.toLowerCase();
  8744. // We can assume that user agent is chrome, because it's
  8745. // enforced when 'ext' streaming method is set
  8746. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8747. console.log("Chrome version" + userAgent, ver);
  8748. _desktopSharingEnabled = ver >= 34;
  8749. } else {
  8750. _desktopSharingEnabled =
  8751. obtainDesktopStream === obtainWebRTCScreen;
  8752. }
  8753. }
  8754. return _desktopSharingEnabled;
  8755. },
  8756. init: function () {
  8757. setDesktopSharing(config.desktopSharing);
  8758. // Initialize Chrome extension inline installs
  8759. if (config.chromeExtensionId) {
  8760. initInlineInstalls();
  8761. // Check if extension is installed
  8762. checkExtInstalled(function (installed, updateRequired) {
  8763. extInstalled = installed;
  8764. extUpdateRequired = updateRequired;
  8765. console.info(
  8766. "Chrome extension installed: " + extInstalled +
  8767. " updateRequired: " + extUpdateRequired);
  8768. });
  8769. }
  8770. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8771. },
  8772. addListener: function (listener, type)
  8773. {
  8774. eventEmitter.on(type, listener);
  8775. },
  8776. removeListener: function (listener, type) {
  8777. eventEmitter.removeListener(type, listener);
  8778. },
  8779. /*
  8780. * Toggles screen sharing.
  8781. */
  8782. toggleScreenSharing: function () {
  8783. if (switchInProgress || !obtainDesktopStream) {
  8784. console.warn("Switch in progress or no method defined");
  8785. return;
  8786. }
  8787. switchInProgress = true;
  8788. if (!isUsingScreenStream)
  8789. {
  8790. // Switch to desktop stream
  8791. obtainDesktopStream(
  8792. function (stream) {
  8793. // We now use screen stream
  8794. isUsingScreenStream = true;
  8795. // Hook 'ended' event to restore camera
  8796. // when screen stream stops
  8797. stream.addEventListener('ended',
  8798. function (e) {
  8799. if (!switchInProgress && isUsingScreenStream) {
  8800. APP.desktopsharing.toggleScreenSharing();
  8801. }
  8802. }
  8803. );
  8804. newStreamCreated(stream);
  8805. },
  8806. getDesktopStreamFailed);
  8807. } else {
  8808. // Disable screen stream
  8809. APP.RTC.getUserMediaWithConstraints(
  8810. ['video'],
  8811. function (stream) {
  8812. // We are now using camera stream
  8813. isUsingScreenStream = false;
  8814. newStreamCreated(stream);
  8815. },
  8816. getVideoStreamFailed, config.resolution || '360'
  8817. );
  8818. }
  8819. }
  8820. };
  8821. },{"../../service/desktopsharing/DesktopSharingEventTypes":106,"events":1}],45:[function(require,module,exports){
  8822. //maps keycode to character, id of popover for given function and function
  8823. var shortcuts = {
  8824. 67: {
  8825. character: "C",
  8826. id: "toggleChatPopover",
  8827. function: APP.UI.toggleChat
  8828. },
  8829. 70: {
  8830. character: "F",
  8831. id: "filmstripPopover",
  8832. function: APP.UI.toggleFilmStrip
  8833. },
  8834. 77: {
  8835. character: "M",
  8836. id: "mutePopover",
  8837. function: APP.UI.toggleAudio
  8838. },
  8839. 84: {
  8840. character: "T",
  8841. function: function() {
  8842. if(!APP.RTC.localAudio.isMuted()) {
  8843. APP.UI.toggleAudio();
  8844. }
  8845. }
  8846. },
  8847. 86: {
  8848. character: "V",
  8849. id: "toggleVideoPopover",
  8850. function: APP.UI.toggleVideo
  8851. }
  8852. };
  8853. var KeyboardShortcut = {
  8854. init: function () {
  8855. window.onkeyup = function(e) {
  8856. var keycode = e.which;
  8857. if(!($(":focus").is("input[type=text]") ||
  8858. $(":focus").is("input[type=password]") ||
  8859. $(":focus").is("textarea"))) {
  8860. if (typeof shortcuts[keycode] === "object") {
  8861. shortcuts[keycode].function();
  8862. }
  8863. else if (keycode >= "0".charCodeAt(0) &&
  8864. keycode <= "9".charCodeAt(0)) {
  8865. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8866. }
  8867. //esc while the smileys are visible hides them
  8868. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8869. APP.UI.toggleSmileys();
  8870. }
  8871. };
  8872. window.onkeydown = function(e) {
  8873. if(!($(":focus").is("input[type=text]") ||
  8874. $(":focus").is("input[type=password]") ||
  8875. $(":focus").is("textarea"))) {
  8876. if(e.which === "T".charCodeAt(0)) {
  8877. if(APP.RTC.localAudio.isMuted()) {
  8878. APP.UI.toggleAudio();
  8879. }
  8880. }
  8881. }
  8882. };
  8883. var self = this;
  8884. $('body').popover({ selector: '[data-toggle=popover]',
  8885. trigger: 'click hover',
  8886. content: function() {
  8887. return this.getAttribute("content") +
  8888. self.getShortcut(this.getAttribute("shortcut"));
  8889. }
  8890. });
  8891. },
  8892. /**
  8893. *
  8894. * @param id indicates the popover associated with the shortcut
  8895. * @returns {string} the keyboard shortcut used for the id given
  8896. */
  8897. getShortcut: function (id) {
  8898. for (var keycode in shortcuts) {
  8899. if (shortcuts.hasOwnProperty(keycode)) {
  8900. if (shortcuts[keycode].id === id) {
  8901. return " (" + shortcuts[keycode].character + ")";
  8902. }
  8903. }
  8904. }
  8905. return "";
  8906. }
  8907. };
  8908. module.exports = KeyboardShortcut;
  8909. },{}],46:[function(require,module,exports){
  8910. /* global APP */
  8911. /**
  8912. * This module is meant to (eventually) contain and manage all information
  8913. * about members/participants of the conference, so that other modules don't
  8914. * have to do it on their own, and so that other modules can access members'
  8915. * information from a single place.
  8916. *
  8917. * Currently this module only manages information about the support of jingle
  8918. * DTMF of the members. Other fields, as well as accessor methods are meant to
  8919. * be added as needed.
  8920. */
  8921. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8922. var Events = require("../../service/members/Events");
  8923. var EventEmitter = require("events");
  8924. var eventEmitter = new EventEmitter();
  8925. /**
  8926. * The actual container.
  8927. */
  8928. var members = {};
  8929. /**
  8930. * There is at least one member that supports DTMF (i.e. is jigasi).
  8931. */
  8932. var atLeastOneDtmf = false;
  8933. function registerListeners() {
  8934. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  8935. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  8936. }
  8937. /**
  8938. * Handles a new member joining the MUC.
  8939. */
  8940. function onMucMemberJoined(jid, id, displayName) {
  8941. var member = {
  8942. displayName: displayName
  8943. };
  8944. APP.xmpp.getConnection().disco.info(
  8945. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  8946. members[jid] = member;
  8947. }
  8948. /**
  8949. * Handles a member leaving the MUC.
  8950. */
  8951. function onMucMemberLeft(jid) {
  8952. delete members[jid];
  8953. updateAtLeastOneDtmf();
  8954. }
  8955. /**
  8956. * Handles the reception of a disco#info packet from a particular JID.
  8957. * @param jid the JID sending the packet.
  8958. * @param iq the packet.
  8959. */
  8960. function onDiscoInfoReceived(jid, iq) {
  8961. if (!members[jid])
  8962. return;
  8963. var supportsDtmf
  8964. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  8965. updateDtmf(jid, supportsDtmf);
  8966. }
  8967. /**
  8968. * Updates the 'supportsDtmf' field for a member.
  8969. * @param jid the jid of the member.
  8970. * @param newValue the new value for the 'supportsDtmf' field.
  8971. */
  8972. function updateDtmf(jid, newValue) {
  8973. var oldValue = members[jid].supportsDtmf;
  8974. members[jid].supportsDtmf = newValue;
  8975. if (newValue != oldValue) {
  8976. updateAtLeastOneDtmf();
  8977. }
  8978. }
  8979. /**
  8980. * Checks each member's 'supportsDtmf' field and updates
  8981. * 'atLastOneSupportsDtmf'.
  8982. */
  8983. function updateAtLeastOneDtmf(){
  8984. var newAtLeastOneDtmf = false;
  8985. for (var key in members) {
  8986. if (typeof members[key].supportsDtmf !== 'undefined'
  8987. && members[key].supportsDtmf) {
  8988. newAtLeastOneDtmf= true;
  8989. break;
  8990. }
  8991. }
  8992. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  8993. atLeastOneDtmf = newAtLeastOneDtmf;
  8994. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  8995. }
  8996. }
  8997. /**
  8998. * Exported interface.
  8999. */
  9000. var Members = {
  9001. start: function(){
  9002. registerListeners();
  9003. },
  9004. addListener: function(type, listener)
  9005. {
  9006. eventEmitter.on(type, listener);
  9007. },
  9008. removeListener: function (type, listener) {
  9009. eventEmitter.removeListener(type, listener);
  9010. },
  9011. size: function () {
  9012. return Object.keys(members).length;
  9013. },
  9014. getMembers: function () {
  9015. return members;
  9016. }
  9017. };
  9018. module.exports = Members;
  9019. },{"../../service/members/Events":107,"../../service/xmpp/XMPPEvents":109,"events":1}],47:[function(require,module,exports){
  9020. var email = '';
  9021. var displayName = '';
  9022. var userId;
  9023. var language = null;
  9024. function supportsLocalStorage() {
  9025. try {
  9026. return 'localStorage' in window && window.localStorage !== null;
  9027. } catch (e) {
  9028. console.log("localstorage is not supported");
  9029. return false;
  9030. }
  9031. }
  9032. function generateUniqueId() {
  9033. function _p8() {
  9034. return (Math.random().toString(16) + "000000000").substr(2, 8);
  9035. }
  9036. return _p8() + _p8() + _p8() + _p8();
  9037. }
  9038. if (supportsLocalStorage()) {
  9039. if (!window.localStorage.jitsiMeetId) {
  9040. window.localStorage.jitsiMeetId = generateUniqueId();
  9041. console.log("generated id", window.localStorage.jitsiMeetId);
  9042. }
  9043. userId = window.localStorage.jitsiMeetId || '';
  9044. email = window.localStorage.email || '';
  9045. displayName = window.localStorage.displayname || '';
  9046. language = window.localStorage.language;
  9047. } else {
  9048. console.log("local storage is not supported");
  9049. userId = generateUniqueId();
  9050. }
  9051. var Settings =
  9052. {
  9053. setDisplayName: function (newDisplayName) {
  9054. displayName = newDisplayName;
  9055. window.localStorage.displayname = displayName;
  9056. return displayName;
  9057. },
  9058. setEmail: function (newEmail)
  9059. {
  9060. email = newEmail;
  9061. window.localStorage.email = newEmail;
  9062. return email;
  9063. },
  9064. getSettings: function () {
  9065. return {
  9066. email: email,
  9067. displayName: displayName,
  9068. uid: userId,
  9069. language: language
  9070. };
  9071. },
  9072. setLanguage: function (lang) {
  9073. language = lang;
  9074. window.localStorage.language = lang;
  9075. }
  9076. };
  9077. module.exports = Settings;
  9078. },{}],48:[function(require,module,exports){
  9079. /**
  9080. * Provides statistics for the local stream.
  9081. */
  9082. /**
  9083. * Size of the webaudio analizer buffer.
  9084. * @type {number}
  9085. */
  9086. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9087. /**
  9088. * Value of the webaudio analizer smoothing time parameter.
  9089. * @type {number}
  9090. */
  9091. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9092. /**
  9093. * Converts time domain data array to audio level.
  9094. * @param array the time domain data array.
  9095. * @returns {number} the audio level
  9096. */
  9097. function timeDomainDataToAudioLevel(samples) {
  9098. var maxVolume = 0;
  9099. var length = samples.length;
  9100. for (var i = 0; i < length; i++) {
  9101. if (maxVolume < samples[i])
  9102. maxVolume = samples[i];
  9103. }
  9104. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9105. };
  9106. /**
  9107. * Animates audio level change
  9108. * @param newLevel the new audio level
  9109. * @param lastLevel the last audio level
  9110. * @returns {Number} the audio level to be set
  9111. */
  9112. function animateLevel(newLevel, lastLevel)
  9113. {
  9114. var value = 0;
  9115. var diff = lastLevel - newLevel;
  9116. if(diff > 0.2)
  9117. {
  9118. value = lastLevel - 0.2;
  9119. }
  9120. else if(diff < -0.4)
  9121. {
  9122. value = lastLevel + 0.4;
  9123. }
  9124. else
  9125. {
  9126. value = newLevel;
  9127. }
  9128. return parseFloat(value.toFixed(3));
  9129. }
  9130. /**
  9131. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9132. *
  9133. * @param stream the local stream
  9134. * @param interval stats refresh interval given in ms.
  9135. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9136. * update.
  9137. * @constructor
  9138. */
  9139. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9140. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9141. this.stream = stream;
  9142. this.intervalId = null;
  9143. this.intervalMilis = interval;
  9144. this.eventEmitter = eventEmitter;
  9145. this.audioLevel = 0;
  9146. this.statisticsService = statisticsService;
  9147. }
  9148. /**
  9149. * Starts the collecting the statistics.
  9150. */
  9151. LocalStatsCollector.prototype.start = function () {
  9152. if (config.disableAudioLevels || !window.AudioContext)
  9153. return;
  9154. var context = new AudioContext();
  9155. var analyser = context.createAnalyser();
  9156. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9157. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9158. var source = context.createMediaStreamSource(this.stream);
  9159. source.connect(analyser);
  9160. var self = this;
  9161. this.intervalId = setInterval(
  9162. function () {
  9163. var array = new Uint8Array(analyser.frequencyBinCount);
  9164. analyser.getByteTimeDomainData(array);
  9165. var audioLevel = timeDomainDataToAudioLevel(array);
  9166. if(audioLevel != self.audioLevel) {
  9167. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9168. self.eventEmitter.emit(
  9169. "statistics.audioLevel",
  9170. self.statisticsService.LOCAL_JID,
  9171. self.audioLevel);
  9172. }
  9173. },
  9174. this.intervalMilis
  9175. );
  9176. };
  9177. /**
  9178. * Stops collecting the statistics.
  9179. */
  9180. LocalStatsCollector.prototype.stop = function () {
  9181. if (this.intervalId) {
  9182. clearInterval(this.intervalId);
  9183. this.intervalId = null;
  9184. }
  9185. };
  9186. module.exports = LocalStatsCollector;
  9187. },{}],49:[function(require,module,exports){
  9188. /* global ssrc2jid */
  9189. /* jshint -W117 */
  9190. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9191. /**
  9192. * Calculates packet lost percent using the number of lost packets and the
  9193. * number of all packet.
  9194. * @param lostPackets the number of lost packets
  9195. * @param totalPackets the number of all packets.
  9196. * @returns {number} packet loss percent
  9197. */
  9198. function calculatePacketLoss(lostPackets, totalPackets) {
  9199. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9200. return 0;
  9201. return Math.round((lostPackets/totalPackets)*100);
  9202. }
  9203. function getStatValue(item, name) {
  9204. if(!keyMap[APP.RTC.getBrowserType()][name])
  9205. throw "The property isn't supported!";
  9206. var key = keyMap[APP.RTC.getBrowserType()][name];
  9207. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9208. }
  9209. /**
  9210. * Peer statistics data holder.
  9211. * @constructor
  9212. */
  9213. function PeerStats()
  9214. {
  9215. this.ssrc2Loss = {};
  9216. this.ssrc2AudioLevel = {};
  9217. this.ssrc2bitrate = {};
  9218. this.ssrc2resolution = {};
  9219. }
  9220. /**
  9221. * The bandwidth
  9222. * @type {{}}
  9223. */
  9224. PeerStats.bandwidth = {};
  9225. /**
  9226. * The bit rate
  9227. * @type {{}}
  9228. */
  9229. PeerStats.bitrate = {};
  9230. /**
  9231. * The packet loss rate
  9232. * @type {{}}
  9233. */
  9234. PeerStats.packetLoss = null;
  9235. /**
  9236. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9237. * represented by this instance.
  9238. * @param ssrc audio or video RTP stream SSRC.
  9239. * @param lossRate new packet loss rate value to be set.
  9240. */
  9241. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9242. {
  9243. this.ssrc2Loss[ssrc] = lossRate;
  9244. };
  9245. /**
  9246. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9247. * represented by this instance.
  9248. * @param ssrc audio or video RTP stream SSRC.
  9249. * @param resolution new resolution value to be set.
  9250. */
  9251. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9252. {
  9253. if(resolution === null && this.ssrc2resolution[ssrc])
  9254. {
  9255. delete this.ssrc2resolution[ssrc];
  9256. }
  9257. else if(resolution !== null)
  9258. this.ssrc2resolution[ssrc] = resolution;
  9259. };
  9260. /**
  9261. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9262. * represented by this instance.
  9263. * @param ssrc audio or video RTP stream SSRC.
  9264. * @param bitrate new bitrate value to be set.
  9265. */
  9266. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9267. {
  9268. if(this.ssrc2bitrate[ssrc])
  9269. {
  9270. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9271. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9272. }
  9273. else {
  9274. this.ssrc2bitrate[ssrc] = bitrate;
  9275. }
  9276. };
  9277. /**
  9278. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9279. * the stream which belongs to the peer represented by this instance.
  9280. * @param ssrc RTP stream SSRC for which current audio level value will be
  9281. * updated.
  9282. * @param audioLevel the new audio level value to be set. Value is truncated to
  9283. * fit the range from 0 to 1.
  9284. */
  9285. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9286. {
  9287. // Range limit 0 - 1
  9288. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9289. };
  9290. function formatAudioLevel(audioLevel) {
  9291. return Math.min(Math.max(audioLevel, 0), 1);
  9292. }
  9293. /**
  9294. * Array with the transport information.
  9295. * @type {Array}
  9296. */
  9297. PeerStats.transport = [];
  9298. /**
  9299. * <tt>StatsCollector</tt> registers for stats updates of given
  9300. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9301. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9302. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9303. * instance as an event source.
  9304. *
  9305. * @param peerconnection webRTC peer connection object.
  9306. * @param interval stats refresh interval given in ms.
  9307. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9308. * called on stats update.
  9309. * @constructor
  9310. */
  9311. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9312. {
  9313. this.peerconnection = peerconnection;
  9314. this.baselineAudioLevelsReport = null;
  9315. this.currentAudioLevelsReport = null;
  9316. this.currentStatsReport = null;
  9317. this.baselineStatsReport = null;
  9318. this.audioLevelsIntervalId = null;
  9319. this.eventEmitter = eventEmitter;
  9320. /**
  9321. * Gather PeerConnection stats once every this many milliseconds.
  9322. */
  9323. this.GATHER_INTERVAL = 15000;
  9324. /**
  9325. * Log stats via the focus once every this many milliseconds.
  9326. */
  9327. this.LOG_INTERVAL = 60000;
  9328. /**
  9329. * Gather stats and store them in this.statsToBeLogged.
  9330. */
  9331. this.gatherStatsIntervalId = null;
  9332. /**
  9333. * Send the stats already saved in this.statsToBeLogged to be logged via
  9334. * the focus.
  9335. */
  9336. this.logStatsIntervalId = null;
  9337. /**
  9338. * Stores the statistics which will be send to the focus to be logged.
  9339. */
  9340. this.statsToBeLogged =
  9341. {
  9342. timestamps: [],
  9343. stats: {}
  9344. };
  9345. // Updates stats interval
  9346. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9347. this.statsIntervalId = null;
  9348. this.statsIntervalMilis = statsInterval;
  9349. // Map of jids to PeerStats
  9350. this.jid2stats = {};
  9351. }
  9352. module.exports = StatsCollector;
  9353. /**
  9354. * Stops stats updates.
  9355. */
  9356. StatsCollector.prototype.stop = function () {
  9357. if (this.audioLevelsIntervalId) {
  9358. clearInterval(this.audioLevelsIntervalId);
  9359. this.audioLevelsIntervalId = null;
  9360. }
  9361. if (this.statsIntervalId)
  9362. {
  9363. clearInterval(this.statsIntervalId);
  9364. this.statsIntervalId = null;
  9365. }
  9366. if(this.logStatsIntervalId)
  9367. {
  9368. clearInterval(this.logStatsIntervalId);
  9369. this.logStatsIntervalId = null;
  9370. }
  9371. if(this.gatherStatsIntervalId)
  9372. {
  9373. clearInterval(this.gatherStatsIntervalId);
  9374. this.gatherStatsIntervalId = null;
  9375. }
  9376. };
  9377. /**
  9378. * Callback passed to <tt>getStats</tt> method.
  9379. * @param error an error that occurred on <tt>getStats</tt> call.
  9380. */
  9381. StatsCollector.prototype.errorCallback = function (error)
  9382. {
  9383. console.error("Get stats error", error);
  9384. this.stop();
  9385. };
  9386. /**
  9387. * Starts stats updates.
  9388. */
  9389. StatsCollector.prototype.start = function ()
  9390. {
  9391. var self = this;
  9392. if(!config.disableAudioLevels) {
  9393. this.audioLevelsIntervalId = setInterval(
  9394. function () {
  9395. // Interval updates
  9396. self.peerconnection.getStats(
  9397. function (report) {
  9398. var results = null;
  9399. if (!report || !report.result ||
  9400. typeof report.result != 'function') {
  9401. results = report;
  9402. }
  9403. else {
  9404. results = report.result();
  9405. }
  9406. //console.error("Got interval report", results);
  9407. self.currentAudioLevelsReport = results;
  9408. self.processAudioLevelReport();
  9409. self.baselineAudioLevelsReport =
  9410. self.currentAudioLevelsReport;
  9411. },
  9412. self.errorCallback
  9413. );
  9414. },
  9415. self.audioLevelsIntervalMilis
  9416. );
  9417. }
  9418. if(!config.disableStats && !navigator.mozGetUserMedia) {
  9419. this.statsIntervalId = setInterval(
  9420. function () {
  9421. // Interval updates
  9422. self.peerconnection.getStats(
  9423. function (report) {
  9424. var results = null;
  9425. if (!report || !report.result ||
  9426. typeof report.result != 'function') {
  9427. //firefox
  9428. results = report;
  9429. }
  9430. else {
  9431. //chrome
  9432. results = report.result();
  9433. }
  9434. //console.error("Got interval report", results);
  9435. self.currentStatsReport = results;
  9436. try {
  9437. self.processStatsReport();
  9438. }
  9439. catch (e) {
  9440. console.error("Unsupported key:" + e, e);
  9441. }
  9442. self.baselineStatsReport = self.currentStatsReport;
  9443. },
  9444. self.errorCallback
  9445. );
  9446. },
  9447. self.statsIntervalMilis
  9448. );
  9449. }
  9450. if (config.logStats && !navigator.mozGetUserMedia) {
  9451. this.gatherStatsIntervalId = setInterval(
  9452. function () {
  9453. self.peerconnection.getStats(
  9454. function (report) {
  9455. self.addStatsToBeLogged(report.result());
  9456. },
  9457. function () {
  9458. }
  9459. );
  9460. },
  9461. this.GATHER_INTERVAL
  9462. );
  9463. this.logStatsIntervalId = setInterval(
  9464. function() { self.logStats(); },
  9465. this.LOG_INTERVAL);
  9466. }
  9467. };
  9468. /**
  9469. * Checks whether a certain record should be included in the logged statistics.
  9470. */
  9471. function acceptStat(reportId, reportType, statName) {
  9472. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9473. return false;
  9474. if (reportType == "ssrc") {
  9475. if (statName == "googTrackId" ||
  9476. statName == "transportId" ||
  9477. statName == "ssrc")
  9478. return false;
  9479. }
  9480. return true;
  9481. }
  9482. /**
  9483. * Checks whether a certain record should be included in the logged statistics.
  9484. */
  9485. function acceptReport(id, type) {
  9486. if (id.substring(0, 15) == "googCertificate" ||
  9487. id.substring(0, 9) == "googTrack" ||
  9488. id.substring(0, 20) == "googLibjingleSession")
  9489. return false;
  9490. if (type == "googComponent")
  9491. return false;
  9492. return true;
  9493. }
  9494. /**
  9495. * Converts the stats to the format used for logging, and saves the data in
  9496. * this.statsToBeLogged.
  9497. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9498. */
  9499. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9500. var self = this;
  9501. var num_records = this.statsToBeLogged.timestamps.length;
  9502. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9503. reports.map(function (report) {
  9504. if (!acceptReport(report.id, report.type))
  9505. return;
  9506. var stat = self.statsToBeLogged.stats[report.id];
  9507. if (!stat) {
  9508. stat = self.statsToBeLogged.stats[report.id] = {};
  9509. }
  9510. stat.type = report.type;
  9511. report.names().map(function (name) {
  9512. if (!acceptStat(report.id, report.type, name))
  9513. return;
  9514. var values = stat[name];
  9515. if (!values) {
  9516. values = stat[name] = [];
  9517. }
  9518. while (values.length < num_records) {
  9519. values.push(null);
  9520. }
  9521. values.push(report.stat(name));
  9522. });
  9523. });
  9524. };
  9525. StatsCollector.prototype.logStats = function () {
  9526. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9527. return;
  9528. // Reset the stats
  9529. this.statsToBeLogged.stats = {};
  9530. this.statsToBeLogged.timestamps = [];
  9531. };
  9532. var keyMap = {};
  9533. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9534. "ssrc": "ssrc",
  9535. "packetsReceived": "packetsReceived",
  9536. "packetsLost": "packetsLost",
  9537. "packetsSent": "packetsSent",
  9538. "bytesReceived": "bytesReceived",
  9539. "bytesSent": "bytesSent"
  9540. };
  9541. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9542. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9543. "sendBandwidth": "googAvailableSendBandwidth",
  9544. "remoteAddress": "googRemoteAddress",
  9545. "transportType": "googTransportType",
  9546. "localAddress": "googLocalAddress",
  9547. "activeConnection": "googActiveConnection",
  9548. "ssrc": "ssrc",
  9549. "packetsReceived": "packetsReceived",
  9550. "packetsSent": "packetsSent",
  9551. "packetsLost": "packetsLost",
  9552. "bytesReceived": "bytesReceived",
  9553. "bytesSent": "bytesSent",
  9554. "googFrameHeightReceived": "googFrameHeightReceived",
  9555. "googFrameWidthReceived": "googFrameWidthReceived",
  9556. "googFrameHeightSent": "googFrameHeightSent",
  9557. "googFrameWidthSent": "googFrameWidthSent",
  9558. "audioInputLevel": "audioInputLevel",
  9559. "audioOutputLevel": "audioOutputLevel"
  9560. };
  9561. /**
  9562. * Stats processing logic.
  9563. */
  9564. StatsCollector.prototype.processStatsReport = function () {
  9565. if (!this.baselineStatsReport) {
  9566. return;
  9567. }
  9568. for (var idx in this.currentStatsReport) {
  9569. var now = this.currentStatsReport[idx];
  9570. try {
  9571. if (getStatValue(now, 'receiveBandwidth') ||
  9572. getStatValue(now, 'sendBandwidth')) {
  9573. PeerStats.bandwidth = {
  9574. "download": Math.round(
  9575. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9576. "upload": Math.round(
  9577. (getStatValue(now, 'sendBandwidth')) / 1000)
  9578. };
  9579. }
  9580. }
  9581. catch(e){/*not supported*/}
  9582. if(now.type == 'googCandidatePair')
  9583. {
  9584. var ip, type, localIP, active;
  9585. try {
  9586. ip = getStatValue(now, 'remoteAddress');
  9587. type = getStatValue(now, "transportType");
  9588. localIP = getStatValue(now, "localAddress");
  9589. active = getStatValue(now, "activeConnection");
  9590. }
  9591. catch(e){/*not supported*/}
  9592. if(!ip || !type || !localIP || active != "true")
  9593. continue;
  9594. var addressSaved = false;
  9595. for(var i = 0; i < PeerStats.transport.length; i++)
  9596. {
  9597. if(PeerStats.transport[i].ip == ip &&
  9598. PeerStats.transport[i].type == type &&
  9599. PeerStats.transport[i].localip == localIP)
  9600. {
  9601. addressSaved = true;
  9602. }
  9603. }
  9604. if(addressSaved)
  9605. continue;
  9606. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9607. continue;
  9608. }
  9609. if(now.type == "candidatepair")
  9610. {
  9611. if(now.state == "succeeded")
  9612. continue;
  9613. var local = this.currentStatsReport[now.localCandidateId];
  9614. var remote = this.currentStatsReport[now.remoteCandidateId];
  9615. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9616. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9617. }
  9618. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9619. now.type != "inboundrtp") {
  9620. continue;
  9621. }
  9622. var before = this.baselineStatsReport[idx];
  9623. if (!before) {
  9624. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9625. continue;
  9626. }
  9627. var ssrc = getStatValue(now, 'ssrc');
  9628. if(!ssrc)
  9629. continue;
  9630. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9631. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9632. console.warn("No jid for ssrc: " + ssrc);
  9633. continue;
  9634. }
  9635. var jidStats = this.jid2stats[jid];
  9636. if (!jidStats) {
  9637. jidStats = new PeerStats();
  9638. this.jid2stats[jid] = jidStats;
  9639. }
  9640. var isDownloadStream = true;
  9641. var key = 'packetsReceived';
  9642. if (!getStatValue(now, key))
  9643. {
  9644. isDownloadStream = false;
  9645. key = 'packetsSent';
  9646. if (!getStatValue(now, key))
  9647. {
  9648. console.warn("No packetsReceived nor packetSent stat found");
  9649. continue;
  9650. }
  9651. }
  9652. var packetsNow = getStatValue(now, key);
  9653. if(!packetsNow || packetsNow < 0)
  9654. packetsNow = 0;
  9655. var packetsBefore = getStatValue(before, key);
  9656. if(!packetsBefore || packetsBefore < 0)
  9657. packetsBefore = 0;
  9658. var packetRate = packetsNow - packetsBefore;
  9659. if(!packetRate || packetRate < 0)
  9660. packetRate = 0;
  9661. var currentLoss = getStatValue(now, 'packetsLost');
  9662. if(!currentLoss || currentLoss < 0)
  9663. currentLoss = 0;
  9664. var previousLoss = getStatValue(before, 'packetsLost');
  9665. if(!previousLoss || previousLoss < 0)
  9666. previousLoss = 0;
  9667. var lossRate = currentLoss - previousLoss;
  9668. if(!lossRate || lossRate < 0)
  9669. lossRate = 0;
  9670. var packetsTotal = (packetRate + lossRate);
  9671. jidStats.setSsrcLoss(ssrc,
  9672. {"packetsTotal": packetsTotal,
  9673. "packetsLost": lossRate,
  9674. "isDownloadStream": isDownloadStream});
  9675. var bytesReceived = 0, bytesSent = 0;
  9676. if(getStatValue(now, "bytesReceived"))
  9677. {
  9678. bytesReceived = getStatValue(now, "bytesReceived") -
  9679. getStatValue(before, "bytesReceived");
  9680. }
  9681. if(getStatValue(now, "bytesSent"))
  9682. {
  9683. bytesSent = getStatValue(now, "bytesSent") -
  9684. getStatValue(before, "bytesSent");
  9685. }
  9686. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9687. if(bytesReceived <= 0 || time <= 0)
  9688. {
  9689. bytesReceived = 0;
  9690. }
  9691. else
  9692. {
  9693. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9694. }
  9695. if(bytesSent <= 0 || time <= 0)
  9696. {
  9697. bytesSent = 0;
  9698. }
  9699. else
  9700. {
  9701. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9702. }
  9703. jidStats.setSsrcBitrate(ssrc, {
  9704. "download": bytesReceived,
  9705. "upload": bytesSent});
  9706. var resolution = {height: null, width: null};
  9707. try {
  9708. if (getStatValue(now, "googFrameHeightReceived") &&
  9709. getStatValue(now, "googFrameWidthReceived")) {
  9710. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9711. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9712. }
  9713. else if (getStatValue(now, "googFrameHeightSent") &&
  9714. getStatValue(now, "googFrameWidthSent")) {
  9715. resolution.height = getStatValue(now, "googFrameHeightSent");
  9716. resolution.width = getStatValue(now, "googFrameWidthSent");
  9717. }
  9718. }
  9719. catch(e){/*not supported*/}
  9720. if(resolution.height && resolution.width)
  9721. {
  9722. jidStats.setSsrcResolution(ssrc, resolution);
  9723. }
  9724. else
  9725. {
  9726. jidStats.setSsrcResolution(ssrc, null);
  9727. }
  9728. }
  9729. var self = this;
  9730. // Jid stats
  9731. var totalPackets = {download: 0, upload: 0};
  9732. var lostPackets = {download: 0, upload: 0};
  9733. var bitrateDownload = 0;
  9734. var bitrateUpload = 0;
  9735. var resolutions = {};
  9736. Object.keys(this.jid2stats).forEach(
  9737. function (jid)
  9738. {
  9739. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9740. function (ssrc)
  9741. {
  9742. var type = "upload";
  9743. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9744. type = "download";
  9745. totalPackets[type] +=
  9746. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9747. lostPackets[type] +=
  9748. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9749. }
  9750. );
  9751. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9752. function (ssrc) {
  9753. bitrateDownload +=
  9754. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9755. bitrateUpload +=
  9756. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9757. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9758. }
  9759. );
  9760. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9761. }
  9762. );
  9763. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9764. PeerStats.packetLoss = {
  9765. total:
  9766. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9767. totalPackets.download + totalPackets.upload),
  9768. download:
  9769. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9770. upload:
  9771. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9772. };
  9773. this.eventEmitter.emit("statistics.connectionstats",
  9774. {
  9775. "bitrate": PeerStats.bitrate,
  9776. "packetLoss": PeerStats.packetLoss,
  9777. "bandwidth": PeerStats.bandwidth,
  9778. "resolution": resolutions,
  9779. "transport": PeerStats.transport
  9780. });
  9781. PeerStats.transport = [];
  9782. };
  9783. /**
  9784. * Stats processing logic.
  9785. */
  9786. StatsCollector.prototype.processAudioLevelReport = function ()
  9787. {
  9788. if (!this.baselineAudioLevelsReport)
  9789. {
  9790. return;
  9791. }
  9792. for (var idx in this.currentAudioLevelsReport)
  9793. {
  9794. var now = this.currentAudioLevelsReport[idx];
  9795. if (now.type != 'ssrc')
  9796. {
  9797. continue;
  9798. }
  9799. var before = this.baselineAudioLevelsReport[idx];
  9800. if (!before)
  9801. {
  9802. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9803. continue;
  9804. }
  9805. var ssrc = getStatValue(now, 'ssrc');
  9806. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9807. if (!jid)
  9808. {
  9809. if((Date.now() - now.timestamp) < 3000)
  9810. console.warn("No jid for ssrc: " + ssrc);
  9811. continue;
  9812. }
  9813. var jidStats = this.jid2stats[jid];
  9814. if (!jidStats)
  9815. {
  9816. jidStats = new PeerStats();
  9817. this.jid2stats[jid] = jidStats;
  9818. }
  9819. // Audio level
  9820. var audioLevel = null;
  9821. try {
  9822. audioLevel = getStatValue(now, 'audioInputLevel');
  9823. if (!audioLevel)
  9824. audioLevel = getStatValue(now, 'audioOutputLevel');
  9825. }
  9826. catch(e) {/*not supported*/
  9827. console.warn("Audio Levels are not available in the statistics.");
  9828. clearInterval(this.audioLevelsIntervalId);
  9829. return;
  9830. }
  9831. if (audioLevel)
  9832. {
  9833. // TODO: can't find specs about what this value really is,
  9834. // but it seems to vary between 0 and around 32k.
  9835. audioLevel = audioLevel / 32767;
  9836. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  9837. if(jid != APP.xmpp.myJid())
  9838. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  9839. }
  9840. }
  9841. };
  9842. },{"../../service/RTC/RTCBrowserType":99}],50:[function(require,module,exports){
  9843. var callStats = null;
  9844. function initCallback (err, msg) {
  9845. console.log("Initializing Status: err="+err+" msg="+msg);
  9846. }
  9847. var CallStats = {
  9848. init: function (jingleSession) {
  9849. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  9850. return;
  9851. callStats = new callstats($,io,jsSHA);
  9852. this.session = jingleSession;
  9853. this.peerconnection = jingleSession.peerconnection.peerconnection;
  9854. this.userID = APP.xmpp.myResource();
  9855. var roomJid = APP.UI.getRoomName();
  9856. this.confID = roomJid? Strophe.getNodeFromJid(roomJid) : null;
  9857. //userID is generated or given by the origin server
  9858. callStats.initialize(config.callStatsID,
  9859. config.callStatsSecret,
  9860. this.userID,
  9861. initCallback);
  9862. var usage = callStats.fabricUsage.unbundled;
  9863. if(config.useBundle)
  9864. usage = callStats.fabricUsage.multiplex;
  9865. callStats.addNewFabric(this.peerconnection,
  9866. Strophe.getResourceFromJid(jingleSession.peerjid),
  9867. usage,
  9868. this.confID,
  9869. this.pcCallback.bind(this));
  9870. },
  9871. pcCallback: function (err, msg) {
  9872. if(!callStats)
  9873. return;
  9874. console.log("Monitoring status: "+ err + " msg: " + msg);
  9875. callStats.sendFabricEvent(this.peerconnection,
  9876. callStats.fabricEvent.fabricSetup, this.confID);
  9877. },
  9878. sendMuteEvent: function (mute, type) {
  9879. if(!callStats)
  9880. return;
  9881. var event = null;
  9882. if(type === "video")
  9883. {
  9884. event = (mute? callStats.fabricEvent.videoPause :
  9885. callStats.fabricEvent.videoResume);
  9886. }
  9887. else
  9888. {
  9889. event = (mute? callStats.fabricEvent.audioMute :
  9890. callStats.fabricEvent.audioUnmute);
  9891. }
  9892. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  9893. },
  9894. sendTerminateEvent: function () {
  9895. if(!callStats)
  9896. return;
  9897. callStats.sendFabricEvent(this.peerconnection,
  9898. callStats.fabricEvent.fabricTerminated, this.confID);
  9899. },
  9900. sendSetupFailedEvent: function () {
  9901. if(!callStats)
  9902. return;
  9903. callStats.sendFabricEvent(this.peerconnection,
  9904. callStats.fabricEvent.fabricSetupFailed, this.confID);
  9905. }
  9906. };
  9907. module.exports = CallStats;
  9908. },{}],51:[function(require,module,exports){
  9909. /**
  9910. * Created by hristo on 8/4/14.
  9911. */
  9912. var LocalStats = require("./LocalStatsCollector.js");
  9913. var RTPStats = require("./RTPStatsCollector.js");
  9914. var EventEmitter = require("events");
  9915. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  9916. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9917. var CallStats = require("./callstats");
  9918. var RTCEvents = require("../../service/RTC/RTCEvents");
  9919. var eventEmitter = new EventEmitter();
  9920. var localStats = null;
  9921. var rtpStats = null;
  9922. function stopLocal()
  9923. {
  9924. if(localStats)
  9925. {
  9926. localStats.stop();
  9927. localStats = null;
  9928. }
  9929. }
  9930. function stopRemote()
  9931. {
  9932. if(rtpStats)
  9933. {
  9934. rtpStats.stop();
  9935. eventEmitter.emit("statistics.stop");
  9936. rtpStats = null;
  9937. }
  9938. }
  9939. function startRemoteStats (peerconnection) {
  9940. if(rtpStats)
  9941. {
  9942. rtpStats.stop();
  9943. rtpStats = null;
  9944. }
  9945. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  9946. rtpStats.start();
  9947. }
  9948. function onStreamCreated(stream)
  9949. {
  9950. if(stream.getOriginalStream().getAudioTracks().length === 0)
  9951. return;
  9952. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  9953. eventEmitter);
  9954. localStats.start();
  9955. }
  9956. function onDisposeConference(onUnload) {
  9957. CallStats.sendTerminateEvent();
  9958. stopRemote();
  9959. if(onUnload) {
  9960. stopLocal();
  9961. eventEmitter.removeAllListeners();
  9962. }
  9963. }
  9964. var statistics =
  9965. {
  9966. /**
  9967. * Indicates that this audio level is for local jid.
  9968. * @type {string}
  9969. */
  9970. LOCAL_JID: 'local',
  9971. addAudioLevelListener: function(listener)
  9972. {
  9973. eventEmitter.on("statistics.audioLevel", listener);
  9974. },
  9975. removeAudioLevelListener: function(listener)
  9976. {
  9977. eventEmitter.removeListener("statistics.audioLevel", listener);
  9978. },
  9979. addConnectionStatsListener: function(listener)
  9980. {
  9981. eventEmitter.on("statistics.connectionstats", listener);
  9982. },
  9983. removeConnectionStatsListener: function(listener)
  9984. {
  9985. eventEmitter.removeListener("statistics.connectionstats", listener);
  9986. },
  9987. addRemoteStatsStopListener: function(listener)
  9988. {
  9989. eventEmitter.on("statistics.stop", listener);
  9990. },
  9991. removeRemoteStatsStopListener: function(listener)
  9992. {
  9993. eventEmitter.removeListener("statistics.stop", listener);
  9994. },
  9995. stop: function () {
  9996. stopLocal();
  9997. stopRemote();
  9998. if(eventEmitter)
  9999. {
  10000. eventEmitter.removeAllListeners();
  10001. }
  10002. },
  10003. stopRemoteStatistics: function()
  10004. {
  10005. stopRemote();
  10006. },
  10007. start: function () {
  10008. APP.RTC.addStreamListener(onStreamCreated,
  10009. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10010. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10011. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  10012. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10013. startRemoteStats(event.peerconnection);
  10014. // CallStats.init(event);
  10015. });
  10016. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  10017. CallStats.init(session);
  10018. })
  10019. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  10020. CallStats.sendMuteEvent(mute, "audio");
  10021. });
  10022. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  10023. CallStats.sendSetupFailedEvent();
  10024. })
  10025. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  10026. CallStats.sendMuteEvent(mute, "video");
  10027. });
  10028. }
  10029. };
  10030. module.exports = statistics;
  10031. },{"../../service/RTC/RTCEvents":100,"../../service/RTC/StreamEventTypes.js":102,"../../service/xmpp/XMPPEvents":109,"./LocalStatsCollector.js":48,"./RTPStatsCollector.js":49,"./callstats":50,"events":1}],52:[function(require,module,exports){
  10032. var i18n = require("i18next-client");
  10033. var languages = require("../../service/translation/languages");
  10034. var Settings = require("../settings/Settings");
  10035. var DEFAULT_LANG = languages.EN;
  10036. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10037. return value.replace("__app__", interfaceConfig.APP_NAME);
  10038. });
  10039. var defaultOptions = {
  10040. detectLngQS: "lang",
  10041. useCookie: false,
  10042. fallbackLng: DEFAULT_LANG,
  10043. load: "unspecific",
  10044. resGetPath: 'lang/__ns__-__lng__.json',
  10045. ns: {
  10046. namespaces: ['main', 'languages'],
  10047. defaultNs: 'main'
  10048. },
  10049. lngWhitelist : languages.getLanguages(),
  10050. fallbackOnNull: true,
  10051. fallbackOnEmpty: true,
  10052. useDataAttrOptions: true,
  10053. defaultValueFromContent: false,
  10054. app: interfaceConfig.APP_NAME,
  10055. getAsync: false,
  10056. defaultValueFromContent: false,
  10057. customLoad: function(lng, ns, options, done) {
  10058. var resPath = "lang/__ns__-__lng__.json";
  10059. if(lng === languages.EN)
  10060. resPath = "lang/__ns__.json";
  10061. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10062. i18n.functions.ajax({
  10063. url: url,
  10064. success: function(data, status, xhr) {
  10065. i18n.functions.log('loaded: ' + url);
  10066. done(null, data);
  10067. },
  10068. error : function(xhr, status, error) {
  10069. if ((status && status == 200) ||
  10070. (xhr && xhr.status && xhr.status == 200)) {
  10071. // file loaded but invalid json, stop waste time !
  10072. i18n.functions.error('There is a typo in: ' + url);
  10073. } else if ((status && status == 404) ||
  10074. (xhr && xhr.status && xhr.status == 404)) {
  10075. i18n.functions.log('Does not exist: ' + url);
  10076. } else {
  10077. var theStatus = status ? status :
  10078. ((xhr && xhr.status) ? xhr.status : null);
  10079. i18n.functions.log(theStatus + ' when loading ' + url);
  10080. }
  10081. done(error, {});
  10082. },
  10083. dataType: "json",
  10084. async : options.getAsync
  10085. });
  10086. }
  10087. // options for caching
  10088. // useLocalStorage: true,
  10089. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10090. };
  10091. function initCompleted(t)
  10092. {
  10093. $("[data-i18n]").i18n();
  10094. }
  10095. function checkForParameter() {
  10096. var query = window.location.search.substring(1);
  10097. var vars = query.split("&");
  10098. for (var i=0;i<vars.length;i++) {
  10099. var pair = vars[i].split("=");
  10100. if(pair[0] == "lang")
  10101. {
  10102. return pair[1];
  10103. }
  10104. }
  10105. return null;
  10106. }
  10107. module.exports = {
  10108. init: function (lang) {
  10109. var options = defaultOptions;
  10110. if(!lang)
  10111. {
  10112. lang = checkForParameter();
  10113. if(!lang)
  10114. {
  10115. var settings = Settings.getSettings();
  10116. if(settings)
  10117. lang = settings.language;
  10118. if(!lang && config.defaultLanguage)
  10119. {
  10120. lang = config.defaultLanguage;
  10121. }
  10122. }
  10123. }
  10124. if(lang) {
  10125. options.lng = lang;
  10126. }
  10127. i18n.init(options, initCompleted);
  10128. },
  10129. translateString: function (key, options) {
  10130. return i18n.t(key, options);
  10131. },
  10132. setLanguage: function (lang) {
  10133. if(!lang)
  10134. lang = DEFAULT_LANG;
  10135. i18n.setLng(lang, defaultOptions, initCompleted);
  10136. },
  10137. getCurrentLanguage: function () {
  10138. return i18n.lng();
  10139. },
  10140. translateElement: function (selector) {
  10141. selector.i18n();
  10142. },
  10143. generateTranslationHTML: function (key, options) {
  10144. var str = "<span data-i18n=\"" + key + "\"";
  10145. if(options)
  10146. {
  10147. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10148. }
  10149. str += ">";
  10150. str += this.translateString(key, options);
  10151. str += "</span>";
  10152. return str;
  10153. }
  10154. };
  10155. },{"../../service/translation/languages":108,"../settings/Settings":47,"i18next-client":68}],53:[function(require,module,exports){
  10156. /* jshint -W117 */
  10157. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10158. var SDPDiffer = require("./SDPDiffer");
  10159. var SDPUtil = require("./SDPUtil");
  10160. var SDP = require("./SDP");
  10161. var async = require("async");
  10162. var transform = require("sdp-transform");
  10163. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10164. // Jingle stuff
  10165. function JingleSession(me, sid, connection, service, eventEmitter) {
  10166. this.me = me;
  10167. this.sid = sid;
  10168. this.connection = connection;
  10169. this.initiator = null;
  10170. this.responder = null;
  10171. this.isInitiator = null;
  10172. this.peerjid = null;
  10173. this.state = null;
  10174. this.localSDP = null;
  10175. this.remoteSDP = null;
  10176. this.relayedStreams = [];
  10177. this.startTime = null;
  10178. this.stopTime = null;
  10179. this.media_constraints = null;
  10180. this.pc_constraints = null;
  10181. this.ice_config = {};
  10182. this.drip_container = [];
  10183. this.service = service;
  10184. this.usetrickle = true;
  10185. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10186. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10187. this.hadstuncandidate = false;
  10188. this.hadturncandidate = false;
  10189. this.lasticecandidate = false;
  10190. this.statsinterval = null;
  10191. this.reason = null;
  10192. this.addssrc = [];
  10193. this.removessrc = [];
  10194. this.pendingop = null;
  10195. this.switchstreams = false;
  10196. this.wait = true;
  10197. this.localStreamsSSRC = null;
  10198. this.eventEmitter = eventEmitter;
  10199. /**
  10200. * The indicator which determines whether the (local) video has been muted
  10201. * in response to a user command in contrast to an automatic decision made
  10202. * by the application logic.
  10203. */
  10204. this.videoMuteByUser = false;
  10205. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  10206. // We start with the queue paused. We resume it when the signaling state is
  10207. // stable and the ice connection state is connected.
  10208. this.modifySourcesQueue.pause();
  10209. }
  10210. JingleSession.prototype.updateModifySourcesQueue = function() {
  10211. var signalingState = this.peerconnection.signalingState;
  10212. var iceConnectionState = this.peerconnection.iceConnectionState;
  10213. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  10214. this.modifySourcesQueue.resume();
  10215. } else {
  10216. this.modifySourcesQueue.pause();
  10217. }
  10218. };
  10219. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10220. var self = this;
  10221. if (this.state !== null) {
  10222. console.error('attempt to initiate on session ' + this.sid +
  10223. 'in state ' + this.state);
  10224. return;
  10225. }
  10226. this.isInitiator = isInitiator;
  10227. this.state = 'pending';
  10228. this.initiator = isInitiator ? this.me : peerjid;
  10229. this.responder = !isInitiator ? this.me : peerjid;
  10230. this.peerjid = peerjid;
  10231. this.hadstuncandidate = false;
  10232. this.hadturncandidate = false;
  10233. this.lasticecandidate = false;
  10234. this.peerconnection
  10235. = new TraceablePeerConnection(
  10236. this.connection.jingle.ice_config,
  10237. this.connection.jingle.pc_constraints,
  10238. this);
  10239. this.peerconnection.onicecandidate = function (event) {
  10240. self.sendIceCandidate(event.candidate);
  10241. };
  10242. this.peerconnection.onaddstream = function (event) {
  10243. if (event.stream.id !== 'default') {
  10244. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10245. self.remoteStreamAdded(event);
  10246. } else {
  10247. // This is a recvonly stream. Clients that implement Unified Plan,
  10248. // such as Firefox use recvonly "streams/channels/tracks" for
  10249. // receiving remote stream/tracks, as opposed to Plan B where there
  10250. // are only 3 channels: audio, video and data.
  10251. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  10252. }
  10253. };
  10254. this.peerconnection.onremovestream = function (event) {
  10255. // Remove the stream from remoteStreams
  10256. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10257. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10258. };
  10259. this.peerconnection.onsignalingstatechange = function (event) {
  10260. if (!(self && self.peerconnection)) return;
  10261. self.updateModifySourcesQueue();
  10262. };
  10263. this.peerconnection.oniceconnectionstatechange = function (event) {
  10264. if (!(self && self.peerconnection)) return;
  10265. self.updateModifySourcesQueue();
  10266. switch (self.peerconnection.iceConnectionState) {
  10267. case 'connected':
  10268. this.startTime = new Date();
  10269. break;
  10270. case 'disconnected':
  10271. this.stopTime = new Date();
  10272. break;
  10273. case 'failed':
  10274. self.eventEmitter(XMPPEvents.CONFERENCE_SETUP_FAILED);
  10275. break;
  10276. }
  10277. onIceConnectionStateChange(self.sid, self);
  10278. };
  10279. this.peerconnection.onnegotiationneeded = function (event) {
  10280. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  10281. };
  10282. // add any local and relayed stream
  10283. APP.RTC.localStreams.forEach(function(stream) {
  10284. self.peerconnection.addStream(stream.getOriginalStream());
  10285. });
  10286. this.relayedStreams.forEach(function(stream) {
  10287. self.peerconnection.addStream(stream);
  10288. });
  10289. };
  10290. function onIceConnectionStateChange(sid, session) {
  10291. switch (session.peerconnection.iceConnectionState) {
  10292. case 'checking':
  10293. session.timeChecking = (new Date()).getTime();
  10294. session.firstconnect = true;
  10295. break;
  10296. case 'completed': // on caller side
  10297. case 'connected':
  10298. if (session.firstconnect) {
  10299. session.firstconnect = false;
  10300. var metadata = {};
  10301. metadata.setupTime
  10302. = (new Date()).getTime() - session.timeChecking;
  10303. session.peerconnection.getStats(function (res) {
  10304. if(res && res.result) {
  10305. res.result().forEach(function (report) {
  10306. if (report.type == 'googCandidatePair' &&
  10307. report.stat('googActiveConnection') == 'true') {
  10308. metadata.localCandidateType
  10309. = report.stat('googLocalCandidateType');
  10310. metadata.remoteCandidateType
  10311. = report.stat('googRemoteCandidateType');
  10312. // log pair as well so we can get nice pie
  10313. // charts
  10314. metadata.candidatePair
  10315. = report.stat('googLocalCandidateType') +
  10316. ';' +
  10317. report.stat('googRemoteCandidateType');
  10318. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10319. {
  10320. metadata.ipv6 = true;
  10321. }
  10322. }
  10323. });
  10324. }
  10325. });
  10326. }
  10327. break;
  10328. }
  10329. }
  10330. JingleSession.prototype.accept = function () {
  10331. var self = this;
  10332. this.state = 'active';
  10333. var pranswer = this.peerconnection.localDescription;
  10334. if (!pranswer || pranswer.type != 'pranswer') {
  10335. return;
  10336. }
  10337. console.log('going from pranswer to answer');
  10338. if (this.usetrickle) {
  10339. // remove candidates already sent from session-accept
  10340. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10341. for (var i = 0; i < lines.length; i++) {
  10342. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10343. }
  10344. }
  10345. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10346. // FIXME: change any inactive to sendrecv or whatever they were originally
  10347. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10348. }
  10349. var prsdp = new SDP(pranswer.sdp);
  10350. var accept = $iq({to: this.peerjid,
  10351. type: 'set'})
  10352. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10353. action: 'session-accept',
  10354. initiator: this.initiator,
  10355. responder: this.responder,
  10356. sid: this.sid });
  10357. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10358. var sdp = this.peerconnection.localDescription.sdp;
  10359. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10360. // FIXME: change any inactive to sendrecv or whatever they were originally
  10361. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10362. }
  10363. var self = this;
  10364. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10365. function () {
  10366. //console.log('setLocalDescription success');
  10367. self.setLocalDescription();
  10368. self.connection.sendIQ(accept,
  10369. function () {
  10370. var ack = {};
  10371. ack.source = 'answer';
  10372. $(document).trigger('ack.jingle', [self.sid, ack]);
  10373. },
  10374. function (stanza) {
  10375. var error = ($(stanza).find('error').length) ? {
  10376. code: $(stanza).find('error').attr('code'),
  10377. reason: $(stanza).find('error :first')[0].tagName
  10378. }:{};
  10379. error.source = 'answer';
  10380. JingleSession.onJingleError(self.sid, error);
  10381. },
  10382. 10000);
  10383. },
  10384. function (e) {
  10385. console.error('setLocalDescription failed', e);
  10386. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  10387. }
  10388. );
  10389. };
  10390. JingleSession.prototype.terminate = function (reason) {
  10391. this.state = 'ended';
  10392. this.reason = reason;
  10393. this.peerconnection.close();
  10394. if (this.statsinterval !== null) {
  10395. window.clearInterval(this.statsinterval);
  10396. this.statsinterval = null;
  10397. }
  10398. };
  10399. JingleSession.prototype.active = function () {
  10400. return this.state == 'active';
  10401. };
  10402. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10403. var self = this;
  10404. if (candidate && !this.lasticecandidate) {
  10405. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10406. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10407. if (!(ice && jcand)) {
  10408. console.error('failed to get ice && jcand');
  10409. return;
  10410. }
  10411. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10412. if (jcand.type === 'srflx') {
  10413. this.hadstuncandidate = true;
  10414. } else if (jcand.type === 'relay') {
  10415. this.hadturncandidate = true;
  10416. }
  10417. if (this.usetrickle) {
  10418. if (this.usedrip) {
  10419. if (this.drip_container.length === 0) {
  10420. // start 20ms callout
  10421. window.setTimeout(function () {
  10422. if (self.drip_container.length === 0) return;
  10423. self.sendIceCandidates(self.drip_container);
  10424. self.drip_container = [];
  10425. }, 20);
  10426. }
  10427. this.drip_container.push(candidate);
  10428. return;
  10429. } else {
  10430. self.sendIceCandidate([candidate]);
  10431. }
  10432. }
  10433. } else {
  10434. //console.log('sendIceCandidate: last candidate.');
  10435. if (!this.usetrickle) {
  10436. //console.log('should send full offer now...');
  10437. var init = $iq({to: this.peerjid,
  10438. type: 'set'})
  10439. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10440. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10441. initiator: this.initiator,
  10442. sid: this.sid});
  10443. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10444. var self = this;
  10445. var sendJingle = function (ssrc) {
  10446. if(!ssrc)
  10447. ssrc = {};
  10448. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10449. self.connection.sendIQ(init,
  10450. function () {
  10451. //console.log('session initiate ack');
  10452. var ack = {};
  10453. ack.source = 'offer';
  10454. $(document).trigger('ack.jingle', [self.sid, ack]);
  10455. },
  10456. function (stanza) {
  10457. self.state = 'error';
  10458. self.peerconnection.close();
  10459. var error = ($(stanza).find('error').length) ? {
  10460. code: $(stanza).find('error').attr('code'),
  10461. reason: $(stanza).find('error :first')[0].tagName,
  10462. }:{};
  10463. error.source = 'offer';
  10464. JingleSession.onJingleError(self.sid, error);
  10465. },
  10466. 10000);
  10467. }
  10468. sendJingle();
  10469. }
  10470. this.lasticecandidate = true;
  10471. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10472. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10473. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10474. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10475. }
  10476. }
  10477. };
  10478. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10479. console.log('sendIceCandidates', candidates);
  10480. var cand = $iq({to: this.peerjid, type: 'set'})
  10481. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10482. action: 'transport-info',
  10483. initiator: this.initiator,
  10484. sid: this.sid});
  10485. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10486. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10487. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10488. if (cands.length > 0) {
  10489. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10490. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10491. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10492. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10493. }).c('transport', ice);
  10494. for (var i = 0; i < cands.length; i++) {
  10495. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10496. }
  10497. // add fingerprint
  10498. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10499. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10500. tmp.required = true;
  10501. cand.c(
  10502. 'fingerprint',
  10503. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10504. .t(tmp.fingerprint);
  10505. delete tmp.fingerprint;
  10506. cand.attrs(tmp);
  10507. cand.up();
  10508. }
  10509. cand.up(); // transport
  10510. cand.up(); // content
  10511. }
  10512. }
  10513. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10514. //console.log('was this the last candidate', this.lasticecandidate);
  10515. this.connection.sendIQ(cand,
  10516. function () {
  10517. var ack = {};
  10518. ack.source = 'transportinfo';
  10519. $(document).trigger('ack.jingle', [this.sid, ack]);
  10520. },
  10521. function (stanza) {
  10522. var error = ($(stanza).find('error').length) ? {
  10523. code: $(stanza).find('error').attr('code'),
  10524. reason: $(stanza).find('error :first')[0].tagName,
  10525. }:{};
  10526. error.source = 'transportinfo';
  10527. JingleSession.onJingleError(this.sid, error);
  10528. },
  10529. 10000);
  10530. };
  10531. JingleSession.prototype.sendOffer = function () {
  10532. //console.log('sendOffer...');
  10533. var self = this;
  10534. this.peerconnection.createOffer(function (sdp) {
  10535. self.createdOffer(sdp);
  10536. },
  10537. function (e) {
  10538. console.error('createOffer failed', e);
  10539. },
  10540. this.media_constraints
  10541. );
  10542. };
  10543. JingleSession.prototype.createdOffer = function (sdp) {
  10544. //console.log('createdOffer', sdp);
  10545. var self = this;
  10546. this.localSDP = new SDP(sdp.sdp);
  10547. //this.localSDP.mangle();
  10548. var sendJingle = function () {
  10549. var init = $iq({to: this.peerjid,
  10550. type: 'set'})
  10551. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10552. action: 'session-initiate',
  10553. initiator: this.initiator,
  10554. sid: this.sid});
  10555. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10556. self.connection.sendIQ(init,
  10557. function () {
  10558. var ack = {};
  10559. ack.source = 'offer';
  10560. $(document).trigger('ack.jingle', [self.sid, ack]);
  10561. },
  10562. function (stanza) {
  10563. self.state = 'error';
  10564. self.peerconnection.close();
  10565. var error = ($(stanza).find('error').length) ? {
  10566. code: $(stanza).find('error').attr('code'),
  10567. reason: $(stanza).find('error :first')[0].tagName,
  10568. }:{};
  10569. error.source = 'offer';
  10570. JingleSession.onJingleError(self.sid, error);
  10571. },
  10572. 10000);
  10573. }
  10574. sdp.sdp = this.localSDP.raw;
  10575. this.peerconnection.setLocalDescription(sdp,
  10576. function () {
  10577. if(self.usetrickle)
  10578. {
  10579. sendJingle();
  10580. }
  10581. self.setLocalDescription();
  10582. //console.log('setLocalDescription success');
  10583. },
  10584. function (e) {
  10585. console.error('setLocalDescription failed', e);
  10586. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  10587. }
  10588. );
  10589. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10590. for (var i = 0; i < cands.length; i++) {
  10591. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10592. if (cand.type == 'srflx') {
  10593. this.hadstuncandidate = true;
  10594. } else if (cand.type == 'relay') {
  10595. this.hadturncandidate = true;
  10596. }
  10597. }
  10598. };
  10599. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10600. //console.log('setting remote description... ', desctype);
  10601. this.remoteSDP = new SDP('');
  10602. this.remoteSDP.fromJingle(elem);
  10603. if (this.peerconnection.remoteDescription !== null) {
  10604. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10605. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10606. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10607. for (var i = 0; i < pranswer.media.length; i++) {
  10608. // make sure we have ice ufrag and pwd
  10609. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10610. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10611. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10612. } else {
  10613. console.warn('no ice ufrag?');
  10614. }
  10615. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10616. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10617. } else {
  10618. console.warn('no ice pwd?');
  10619. }
  10620. }
  10621. // copy over candidates
  10622. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10623. for (var j = 0; j < lines.length; j++) {
  10624. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10625. }
  10626. }
  10627. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10628. }
  10629. }
  10630. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10631. this.peerconnection.setRemoteDescription(remotedesc,
  10632. function () {
  10633. //console.log('setRemoteDescription success');
  10634. },
  10635. function (e) {
  10636. console.error('setRemoteDescription error', e);
  10637. JingleSession.onJingleFatalError(self, e);
  10638. }
  10639. );
  10640. };
  10641. JingleSession.prototype.addIceCandidate = function (elem) {
  10642. var self = this;
  10643. if (this.peerconnection.signalingState == 'closed') {
  10644. return;
  10645. }
  10646. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10647. console.log('trickle ice candidate arriving before session accept...');
  10648. // create a PRANSWER for setRemoteDescription
  10649. if (!this.remoteSDP) {
  10650. var cobbled = 'v=0\r\n' +
  10651. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10652. 's=-\r\n' +
  10653. 't=0 0\r\n';
  10654. // first, take some things from the local description
  10655. for (var i = 0; i < this.localSDP.media.length; i++) {
  10656. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10657. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10658. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10659. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10660. }
  10661. cobbled += 'a=inactive\r\n';
  10662. }
  10663. this.remoteSDP = new SDP(cobbled);
  10664. }
  10665. // then add things like ice and dtls from remote candidate
  10666. elem.each(function () {
  10667. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10668. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10669. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10670. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10671. var tmp = $(this).find('transport');
  10672. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10673. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10674. tmp = $(this).find('transport>fingerprint');
  10675. if (tmp.length) {
  10676. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10677. } else {
  10678. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10679. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10680. }
  10681. break;
  10682. }
  10683. }
  10684. }
  10685. });
  10686. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10687. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10688. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10689. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10690. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10691. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10692. }).length == this.remoteSDP.media.length;
  10693. if (iscomplete) {
  10694. console.log('setting pranswer');
  10695. try {
  10696. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10697. function() {
  10698. },
  10699. function(e) {
  10700. console.log('setRemoteDescription pranswer failed', e.toString());
  10701. });
  10702. } catch (e) {
  10703. console.error('setting pranswer failed', e);
  10704. }
  10705. } else {
  10706. //console.log('not yet setting pranswer');
  10707. }
  10708. }
  10709. // operate on each content element
  10710. elem.each(function () {
  10711. // would love to deactivate this, but firefox still requires it
  10712. var idx = -1;
  10713. var i;
  10714. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10715. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10716. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10717. idx = i;
  10718. break;
  10719. }
  10720. }
  10721. if (idx == -1) { // fall back to localdescription
  10722. for (i = 0; i < self.localSDP.media.length; i++) {
  10723. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10724. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10725. idx = i;
  10726. break;
  10727. }
  10728. }
  10729. }
  10730. var name = $(this).attr('name');
  10731. // TODO: check ice-pwd and ice-ufrag?
  10732. $(this).find('transport>candidate').each(function () {
  10733. var line, candidate;
  10734. line = SDPUtil.candidateFromJingle(this);
  10735. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10736. sdpMid: name,
  10737. candidate: line});
  10738. try {
  10739. self.peerconnection.addIceCandidate(candidate);
  10740. } catch (e) {
  10741. console.error('addIceCandidate failed', e.toString(), line);
  10742. }
  10743. });
  10744. });
  10745. };
  10746. JingleSession.prototype.sendAnswer = function (provisional) {
  10747. //console.log('createAnswer', provisional);
  10748. var self = this;
  10749. this.peerconnection.createAnswer(
  10750. function (sdp) {
  10751. self.createdAnswer(sdp, provisional);
  10752. },
  10753. function (e) {
  10754. console.error('createAnswer failed', e);
  10755. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  10756. },
  10757. this.media_constraints
  10758. );
  10759. };
  10760. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10761. //console.log('createAnswer callback');
  10762. var self = this;
  10763. this.localSDP = new SDP(sdp.sdp);
  10764. //this.localSDP.mangle();
  10765. this.usepranswer = provisional === true;
  10766. if (this.usetrickle) {
  10767. if (this.usepranswer) {
  10768. sdp.type = 'pranswer';
  10769. for (var i = 0; i < this.localSDP.media.length; i++) {
  10770. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10771. }
  10772. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10773. }
  10774. }
  10775. var self = this;
  10776. var sendJingle = function (ssrcs) {
  10777. var accept = $iq({to: self.peerjid,
  10778. type: 'set'})
  10779. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10780. action: 'session-accept',
  10781. initiator: self.initiator,
  10782. responder: self.responder,
  10783. sid: self.sid });
  10784. self.localSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10785. self.connection.sendIQ(accept,
  10786. function () {
  10787. var ack = {};
  10788. ack.source = 'answer';
  10789. $(document).trigger('ack.jingle', [self.sid, ack]);
  10790. },
  10791. function (stanza) {
  10792. var error = ($(stanza).find('error').length) ? {
  10793. code: $(stanza).find('error').attr('code'),
  10794. reason: $(stanza).find('error :first')[0].tagName,
  10795. }:{};
  10796. error.source = 'answer';
  10797. JingleSession.onJingleError(self.sid, error);
  10798. },
  10799. 10000);
  10800. }
  10801. sdp.sdp = this.localSDP.raw;
  10802. this.peerconnection.setLocalDescription(sdp,
  10803. function () {
  10804. //console.log('setLocalDescription success');
  10805. if (self.usetrickle && !self.usepranswer) {
  10806. sendJingle();
  10807. }
  10808. self.setLocalDescription();
  10809. },
  10810. function (e) {
  10811. console.error('setLocalDescription failed', e);
  10812. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  10813. }
  10814. );
  10815. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10816. for (var j = 0; j < cands.length; j++) {
  10817. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10818. if (cand.type == 'srflx') {
  10819. this.hadstuncandidate = true;
  10820. } else if (cand.type == 'relay') {
  10821. this.hadturncandidate = true;
  10822. }
  10823. }
  10824. };
  10825. JingleSession.prototype.sendTerminate = function (reason, text) {
  10826. var self = this,
  10827. term = $iq({to: this.peerjid,
  10828. type: 'set'})
  10829. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10830. action: 'session-terminate',
  10831. initiator: this.initiator,
  10832. sid: this.sid})
  10833. .c('reason')
  10834. .c(reason || 'success');
  10835. if (text) {
  10836. term.up().c('text').t(text);
  10837. }
  10838. this.connection.sendIQ(term,
  10839. function () {
  10840. self.peerconnection.close();
  10841. self.peerconnection = null;
  10842. self.terminate();
  10843. var ack = {};
  10844. ack.source = 'terminate';
  10845. $(document).trigger('ack.jingle', [self.sid, ack]);
  10846. },
  10847. function (stanza) {
  10848. var error = ($(stanza).find('error').length) ? {
  10849. code: $(stanza).find('error').attr('code'),
  10850. reason: $(stanza).find('error :first')[0].tagName,
  10851. }:{};
  10852. $(document).trigger('ack.jingle', [self.sid, error]);
  10853. },
  10854. 10000);
  10855. if (this.statsinterval !== null) {
  10856. window.clearInterval(this.statsinterval);
  10857. this.statsinterval = null;
  10858. }
  10859. };
  10860. JingleSession.prototype.addSource = function (elem, fromJid) {
  10861. var self = this;
  10862. // FIXME: dirty waiting
  10863. if (!this.peerconnection.localDescription)
  10864. {
  10865. console.warn("addSource - localDescription not ready yet")
  10866. setTimeout(function()
  10867. {
  10868. self.addSource(elem, fromJid);
  10869. },
  10870. 200
  10871. );
  10872. return;
  10873. }
  10874. console.log('addssrc', new Date().getTime());
  10875. console.log('ice', this.peerconnection.iceConnectionState);
  10876. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10877. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10878. $(elem).each(function (idx, content) {
  10879. var name = $(content).attr('name');
  10880. var lines = '';
  10881. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10882. var semantics = this.getAttribute('semantics');
  10883. var ssrcs = $(this).find('>source').map(function () {
  10884. return this.getAttribute('ssrc');
  10885. }).get();
  10886. if (ssrcs.length != 0) {
  10887. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10888. }
  10889. });
  10890. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10891. tmp.each(function () {
  10892. var ssrc = $(this).attr('ssrc');
  10893. if(mySdp.containsSSRC(ssrc)){
  10894. /**
  10895. * This happens when multiple participants change their streams at the same time and
  10896. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10897. * addssrc are scheduled for update IQ. See
  10898. */
  10899. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10900. return;
  10901. }
  10902. $(this).find('>parameter').each(function () {
  10903. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10904. if ($(this).attr('value') && $(this).attr('value').length)
  10905. lines += ':' + $(this).attr('value');
  10906. lines += '\r\n';
  10907. });
  10908. });
  10909. sdp.media.forEach(function(media, idx) {
  10910. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10911. return;
  10912. sdp.media[idx] += lines;
  10913. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10914. self.addssrc[idx] += lines;
  10915. });
  10916. sdp.raw = sdp.session + sdp.media.join('');
  10917. });
  10918. this.modifySourcesQueue.push(function() {
  10919. // When a source is added and if this is FF, a new channel is allocated
  10920. // for receiving the added source. We need to diffuse the SSRC of this
  10921. // new recvonly channel to the rest of the peers.
  10922. console.log('modify sources done');
  10923. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  10924. console.log("SDPs", mySdp, newSdp);
  10925. self.notifyMySSRCUpdate(mySdp, newSdp);
  10926. });
  10927. };
  10928. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10929. var self = this;
  10930. // FIXME: dirty waiting
  10931. if (!this.peerconnection.localDescription)
  10932. {
  10933. console.warn("removeSource - localDescription not ready yet")
  10934. setTimeout(function()
  10935. {
  10936. self.removeSource(elem, fromJid);
  10937. },
  10938. 200
  10939. );
  10940. return;
  10941. }
  10942. console.log('removessrc', new Date().getTime());
  10943. console.log('ice', this.peerconnection.iceConnectionState);
  10944. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10945. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10946. $(elem).each(function (idx, content) {
  10947. var name = $(content).attr('name');
  10948. var lines = '';
  10949. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10950. var semantics = this.getAttribute('semantics');
  10951. var ssrcs = $(this).find('>source').map(function () {
  10952. return this.getAttribute('ssrc');
  10953. }).get();
  10954. if (ssrcs.length != 0) {
  10955. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10956. }
  10957. });
  10958. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10959. tmp.each(function () {
  10960. var ssrc = $(this).attr('ssrc');
  10961. // This should never happen, but can be useful for bug detection
  10962. if(mySdp.containsSSRC(ssrc)){
  10963. console.error("Got remove stream request for my own ssrc: "+ssrc);
  10964. return;
  10965. }
  10966. $(this).find('>parameter').each(function () {
  10967. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10968. if ($(this).attr('value') && $(this).attr('value').length)
  10969. lines += ':' + $(this).attr('value');
  10970. lines += '\r\n';
  10971. });
  10972. });
  10973. sdp.media.forEach(function(media, idx) {
  10974. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10975. return;
  10976. sdp.media[idx] += lines;
  10977. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  10978. self.removessrc[idx] += lines;
  10979. });
  10980. sdp.raw = sdp.session + sdp.media.join('');
  10981. });
  10982. this.modifySourcesQueue.push(function() {
  10983. // When a source is removed and if this is FF, the recvonly channel that
  10984. // receives the remote stream is deactivated . We need to diffuse the
  10985. // recvonly SSRC removal to the rest of the peers.
  10986. console.log('modify sources done');
  10987. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  10988. console.log("SDPs", mySdp, newSdp);
  10989. self.notifyMySSRCUpdate(mySdp, newSdp);
  10990. });
  10991. };
  10992. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  10993. var self = this;
  10994. if (this.peerconnection.signalingState == 'closed') return;
  10995. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  10996. // There is nothing to do since scheduled job might have been executed by another succeeding call
  10997. this.setLocalDescription();
  10998. if(successCallback){
  10999. successCallback();
  11000. }
  11001. queueCallback();
  11002. return;
  11003. }
  11004. // Reset switch streams flag
  11005. this.switchstreams = false;
  11006. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11007. // add sources
  11008. this.addssrc.forEach(function(lines, idx) {
  11009. sdp.media[idx] += lines;
  11010. });
  11011. this.addssrc = [];
  11012. // remove sources
  11013. this.removessrc.forEach(function(lines, idx) {
  11014. lines = lines.split('\r\n');
  11015. lines.pop(); // remove empty last element;
  11016. lines.forEach(function(line) {
  11017. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11018. });
  11019. });
  11020. this.removessrc = [];
  11021. // FIXME:
  11022. // this was a hack for the situation when only one peer exists
  11023. // in the conference.
  11024. // check if still required and remove
  11025. if (sdp.media[0])
  11026. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11027. if (sdp.media[1])
  11028. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11029. sdp.raw = sdp.session + sdp.media.join('');
  11030. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11031. function() {
  11032. if(self.signalingState == 'closed') {
  11033. console.error("createAnswer attempt on closed state");
  11034. queueCallback("createAnswer attempt on closed state");
  11035. return;
  11036. }
  11037. self.peerconnection.createAnswer(
  11038. function(modifiedAnswer) {
  11039. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11040. if (self.pendingop !== null) {
  11041. var sdp = new SDP(modifiedAnswer.sdp);
  11042. if (sdp.media.length > 1) {
  11043. switch(self.pendingop) {
  11044. case 'mute':
  11045. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11046. break;
  11047. case 'unmute':
  11048. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11049. break;
  11050. }
  11051. sdp.raw = sdp.session + sdp.media.join('');
  11052. modifiedAnswer.sdp = sdp.raw;
  11053. }
  11054. self.pendingop = null;
  11055. }
  11056. // FIXME: pushing down an answer while ice connection state
  11057. // is still checking is bad...
  11058. //console.log(self.peerconnection.iceConnectionState);
  11059. // trying to work around another chrome bug
  11060. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11061. self.peerconnection.setLocalDescription(modifiedAnswer,
  11062. function() {
  11063. //console.log('modified setLocalDescription ok');
  11064. self.setLocalDescription();
  11065. if(successCallback){
  11066. successCallback();
  11067. }
  11068. queueCallback();
  11069. },
  11070. function(error) {
  11071. console.error('modified setLocalDescription failed', error);
  11072. queueCallback(error);
  11073. }
  11074. );
  11075. },
  11076. function(error) {
  11077. console.error('modified answer failed', error);
  11078. queueCallback(error);
  11079. }
  11080. );
  11081. },
  11082. function(error) {
  11083. console.error('modify failed', error);
  11084. queueCallback(error);
  11085. }
  11086. );
  11087. };
  11088. /**
  11089. * Switches video streams.
  11090. * @param new_stream new stream that will be used as video of this session.
  11091. * @param oldStream old video stream of this session.
  11092. * @param success_callback callback executed after successful stream switch.
  11093. */
  11094. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  11095. var self = this;
  11096. // Remember SDP to figure out added/removed SSRCs
  11097. var oldSdp = null;
  11098. if(self.peerconnection) {
  11099. if(self.peerconnection.localDescription) {
  11100. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11101. }
  11102. self.peerconnection.removeStream(oldStream, true);
  11103. if(new_stream)
  11104. self.peerconnection.addStream(new_stream);
  11105. }
  11106. // Conference is not active
  11107. if(!oldSdp || !self.peerconnection) {
  11108. success_callback();
  11109. return;
  11110. }
  11111. self.switchstreams = true;
  11112. self.modifySourcesQueue.push(function() {
  11113. console.log('modify sources done');
  11114. success_callback();
  11115. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11116. console.log("SDPs", oldSdp, newSdp);
  11117. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11118. });
  11119. };
  11120. /**
  11121. * Figures out added/removed ssrcs and send update IQs.
  11122. * @param old_sdp SDP object for old description.
  11123. * @param new_sdp SDP object for new description.
  11124. */
  11125. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11126. if (!(this.peerconnection.signalingState == 'stable' &&
  11127. this.peerconnection.iceConnectionState == 'connected')){
  11128. console.log("Too early to send updates");
  11129. return;
  11130. }
  11131. // send source-remove IQ.
  11132. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11133. var remove = $iq({to: this.peerjid, type: 'set'})
  11134. .c('jingle', {
  11135. xmlns: 'urn:xmpp:jingle:1',
  11136. action: 'source-remove',
  11137. initiator: this.initiator,
  11138. sid: this.sid
  11139. }
  11140. );
  11141. var removed = sdpDiffer.toJingle(remove);
  11142. if (removed) {
  11143. this.connection.sendIQ(remove,
  11144. function (res) {
  11145. console.info('got remove result', res);
  11146. },
  11147. function (err) {
  11148. console.error('got remove error', err);
  11149. }
  11150. );
  11151. } else {
  11152. console.log('removal not necessary');
  11153. }
  11154. // send source-add IQ.
  11155. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11156. var add = $iq({to: this.peerjid, type: 'set'})
  11157. .c('jingle', {
  11158. xmlns: 'urn:xmpp:jingle:1',
  11159. action: 'source-add',
  11160. initiator: this.initiator,
  11161. sid: this.sid
  11162. }
  11163. );
  11164. var added = sdpDiffer.toJingle(add);
  11165. if (added) {
  11166. this.connection.sendIQ(add,
  11167. function (res) {
  11168. console.info('got add result', res);
  11169. },
  11170. function (err) {
  11171. console.error('got add error', err);
  11172. }
  11173. );
  11174. } else {
  11175. console.log('addition not necessary');
  11176. }
  11177. };
  11178. /**
  11179. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11180. *
  11181. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11182. * tracks; otherwise, <tt>false</tt>
  11183. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11184. * tracks have been enabled/disabled. The function may, optionally, return
  11185. * another function which is to be invoked after the whole mute/unmute operation
  11186. * has completed successfully.
  11187. * @param options an object which specifies optional arguments such as the
  11188. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11189. * specifies whether the method was initiated in response to a user command (in
  11190. * contrast to an automatic decision made by the application logic)
  11191. */
  11192. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11193. var byUser;
  11194. if (options) {
  11195. byUser = options.byUser;
  11196. if (typeof byUser === 'undefined') {
  11197. byUser = true;
  11198. }
  11199. } else {
  11200. byUser = true;
  11201. }
  11202. // The user's command to mute the (local) video takes precedence over any
  11203. // automatic decision made by the application logic.
  11204. if (byUser) {
  11205. this.videoMuteByUser = mute;
  11206. } else if (this.videoMuteByUser) {
  11207. return;
  11208. }
  11209. this.hardMuteVideo(mute);
  11210. var self = this;
  11211. var oldSdp = null;
  11212. if(self.peerconnection) {
  11213. if(self.peerconnection.localDescription) {
  11214. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11215. }
  11216. }
  11217. this.modifySourcesQueue.push(function() {
  11218. console.log('modify sources done');
  11219. callback(mute);
  11220. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11221. console.log("SDPs", oldSdp, newSdp);
  11222. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11223. });
  11224. };
  11225. JingleSession.prototype.hardMuteVideo = function (muted) {
  11226. this.pendingop = muted ? 'mute' : 'unmute';
  11227. };
  11228. JingleSession.prototype.sendMute = function (muted, content) {
  11229. var info = $iq({to: this.peerjid,
  11230. type: 'set'})
  11231. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11232. action: 'session-info',
  11233. initiator: this.initiator,
  11234. sid: this.sid });
  11235. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11236. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11237. if (content) {
  11238. info.attrs({'name': content});
  11239. }
  11240. this.connection.send(info);
  11241. };
  11242. JingleSession.prototype.sendRinging = function () {
  11243. var info = $iq({to: this.peerjid,
  11244. type: 'set'})
  11245. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11246. action: 'session-info',
  11247. initiator: this.initiator,
  11248. sid: this.sid });
  11249. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11250. this.connection.send(info);
  11251. };
  11252. JingleSession.prototype.getStats = function (interval) {
  11253. var self = this;
  11254. var recv = {audio: 0, video: 0};
  11255. var lost = {audio: 0, video: 0};
  11256. var lastrecv = {audio: 0, video: 0};
  11257. var lastlost = {audio: 0, video: 0};
  11258. var loss = {audio: 0, video: 0};
  11259. var delta = {audio: 0, video: 0};
  11260. this.statsinterval = window.setInterval(function () {
  11261. if (self && self.peerconnection && self.peerconnection.getStats) {
  11262. self.peerconnection.getStats(function (stats) {
  11263. var results = stats.result();
  11264. // TODO: there are so much statistics you can get from this..
  11265. for (var i = 0; i < results.length; ++i) {
  11266. if (results[i].type == 'ssrc') {
  11267. var packetsrecv = results[i].stat('packetsReceived');
  11268. var packetslost = results[i].stat('packetsLost');
  11269. if (packetsrecv && packetslost) {
  11270. packetsrecv = parseInt(packetsrecv, 10);
  11271. packetslost = parseInt(packetslost, 10);
  11272. if (results[i].stat('googFrameRateReceived')) {
  11273. lastlost.video = lost.video;
  11274. lastrecv.video = recv.video;
  11275. recv.video = packetsrecv;
  11276. lost.video = packetslost;
  11277. } else {
  11278. lastlost.audio = lost.audio;
  11279. lastrecv.audio = recv.audio;
  11280. recv.audio = packetsrecv;
  11281. lost.audio = packetslost;
  11282. }
  11283. }
  11284. }
  11285. }
  11286. delta.audio = recv.audio - lastrecv.audio;
  11287. delta.video = recv.video - lastrecv.video;
  11288. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11289. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11290. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11291. });
  11292. }
  11293. }, interval || 3000);
  11294. return this.statsinterval;
  11295. };
  11296. JingleSession.onJingleError = function (session, error)
  11297. {
  11298. console.error("Jingle error", error);
  11299. }
  11300. JingleSession.onJingleFatalError = function (session, error)
  11301. {
  11302. this.service.sessionTerminated = true;
  11303. this.connection.emuc.doLeave();
  11304. APP.UI.messageHandler.showError("dialog.sorry",
  11305. "dialog.internalError");
  11306. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11307. }
  11308. JingleSession.prototype.setLocalDescription = function () {
  11309. // put our ssrcs into presence so other clients can identify our stream
  11310. var newssrcs = [];
  11311. var session = transform.parse(this.peerconnection.localDescription.sdp);
  11312. session.media.forEach(function (media) {
  11313. if (media.ssrcs != null && media.ssrcs.length > 0) {
  11314. // TODO(gp) maybe exclude FID streams?
  11315. media.ssrcs.forEach(function (ssrc) {
  11316. if (ssrc.attribute !== 'cname') {
  11317. return;
  11318. }
  11319. newssrcs.push({
  11320. 'ssrc': ssrc.id,
  11321. 'type': media.type,
  11322. 'direction': media.direction
  11323. });
  11324. });
  11325. }
  11326. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11327. {
  11328. newssrcs.push({
  11329. 'ssrc': this.localStreamsSSRC[media.type],
  11330. 'type': media.type,
  11331. 'direction': media.direction
  11332. });
  11333. }
  11334. });
  11335. console.log('new ssrcs', newssrcs);
  11336. // Have to clear presence map to get rid of removed streams
  11337. this.connection.emuc.clearPresenceMedia();
  11338. if (newssrcs.length > 0) {
  11339. for (var i = 1; i <= newssrcs.length; i ++) {
  11340. // Change video type to screen
  11341. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11342. newssrcs[i-1].type = 'screen';
  11343. }
  11344. this.connection.emuc.addMediaToPresence(i,
  11345. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11346. }
  11347. this.connection.emuc.sendPresence();
  11348. }
  11349. }
  11350. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11351. function sendKeyframe(pc) {
  11352. console.log('sendkeyframe', pc.iceConnectionState);
  11353. if (pc.iceConnectionState !== 'connected') return; // safe...
  11354. var self = this;
  11355. pc.setRemoteDescription(
  11356. pc.remoteDescription,
  11357. function () {
  11358. pc.createAnswer(
  11359. function (modifiedAnswer) {
  11360. pc.setLocalDescription(
  11361. modifiedAnswer,
  11362. function () {
  11363. // noop
  11364. },
  11365. function (error) {
  11366. console.log('triggerKeyframe setLocalDescription failed', error);
  11367. APP.UI.messageHandler.showError();
  11368. }
  11369. );
  11370. },
  11371. function (error) {
  11372. console.log('triggerKeyframe createAnswer failed', error);
  11373. APP.UI.messageHandler.showError();
  11374. }
  11375. );
  11376. },
  11377. function (error) {
  11378. console.log('triggerKeyframe setRemoteDescription failed', error);
  11379. APP.UI.messageHandler.showError();
  11380. }
  11381. );
  11382. }
  11383. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11384. var self = this;
  11385. var thessrc;
  11386. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11387. // look up an associated JID for a stream id
  11388. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11389. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11390. var ssrclines
  11391. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11392. ssrclines = ssrclines.filter(function (line) {
  11393. // NOTE(gp) previously we filtered on the mslabel, but that property
  11394. // is not always present.
  11395. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11396. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11397. });
  11398. if (ssrclines.length) {
  11399. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11400. // We signal our streams (through Jingle to the focus) before we set
  11401. // our presence (through which peers associate remote streams to
  11402. // jids). So, it might arrive that a remote stream is added but
  11403. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11404. // successfully set. Here we wait for up to a second for the
  11405. // presence to arrive.
  11406. if (!ssrc2jid[thessrc]) {
  11407. if (typeof times === 'undefined')
  11408. {
  11409. times = 0;
  11410. }
  11411. if (times > 10)
  11412. {
  11413. console.warning('Waiting for jid timed out', thessrc);
  11414. }
  11415. else
  11416. {
  11417. setTimeout(function(d) {
  11418. return function() {
  11419. self.remoteStreamAdded(d, times++);
  11420. }
  11421. }(data), 250);
  11422. }
  11423. return;
  11424. }
  11425. // ok to overwrite the one from focus? might save work in colibri.js
  11426. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11427. if (ssrc2jid[thessrc]) {
  11428. data.peerjid = ssrc2jid[thessrc];
  11429. }
  11430. }
  11431. }
  11432. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11433. var isVideo = data.stream.getVideoTracks().length > 0;
  11434. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11435. if (isVideo &&
  11436. data.peerjid && this.peerjid === data.peerjid &&
  11437. data.stream.getVideoTracks().length === 0 &&
  11438. APP.RTC.localVideo.getTracks().length > 0) {
  11439. window.setTimeout(function () {
  11440. sendKeyframe(self.peerconnection);
  11441. }, 3000);
  11442. }
  11443. }
  11444. module.exports = JingleSession;
  11445. },{"../../service/xmpp/XMPPEvents":109,"./SDP":54,"./SDPDiffer":55,"./SDPUtil":56,"./TraceablePeerConnection":57,"async":67,"sdp-transform":95}],54:[function(require,module,exports){
  11446. /* jshint -W117 */
  11447. var SDPUtil = require("./SDPUtil");
  11448. // SDP STUFF
  11449. function SDP(sdp) {
  11450. this.media = sdp.split('\r\nm=');
  11451. for (var i = 1; i < this.media.length; i++) {
  11452. this.media[i] = 'm=' + this.media[i];
  11453. if (i != this.media.length - 1) {
  11454. this.media[i] += '\r\n';
  11455. }
  11456. }
  11457. this.session = this.media.shift() + '\r\n';
  11458. this.raw = this.session + this.media.join('');
  11459. }
  11460. /**
  11461. * Returns map of MediaChannel mapped per channel idx.
  11462. */
  11463. SDP.prototype.getMediaSsrcMap = function() {
  11464. var self = this;
  11465. var media_ssrcs = {};
  11466. var tmp;
  11467. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11468. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11469. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11470. var media = {
  11471. mediaindex: mediaindex,
  11472. mid: mid,
  11473. ssrcs: {},
  11474. ssrcGroups: []
  11475. };
  11476. media_ssrcs[mediaindex] = media;
  11477. tmp.forEach(function (line) {
  11478. var linessrc = line.substring(7).split(' ')[0];
  11479. // allocate new ChannelSsrc
  11480. if(!media.ssrcs[linessrc]) {
  11481. media.ssrcs[linessrc] = {
  11482. ssrc: linessrc,
  11483. lines: []
  11484. };
  11485. }
  11486. media.ssrcs[linessrc].lines.push(line);
  11487. });
  11488. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11489. tmp.forEach(function(line){
  11490. var semantics = line.substr(0, idx).substr(13);
  11491. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11492. if (ssrcs.length != 0) {
  11493. media.ssrcGroups.push({
  11494. semantics: semantics,
  11495. ssrcs: ssrcs
  11496. });
  11497. }
  11498. });
  11499. }
  11500. return media_ssrcs;
  11501. };
  11502. /**
  11503. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11504. * @param ssrc the ssrc to check.
  11505. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11506. */
  11507. SDP.prototype.containsSSRC = function(ssrc) {
  11508. var medias = this.getMediaSsrcMap();
  11509. var contains = false;
  11510. Object.keys(medias).forEach(function(mediaindex){
  11511. var media = medias[mediaindex];
  11512. //console.log("Check", channel, ssrc);
  11513. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11514. contains = true;
  11515. }
  11516. });
  11517. return contains;
  11518. };
  11519. // remove iSAC and CN from SDP
  11520. SDP.prototype.mangle = function () {
  11521. var i, j, mline, lines, rtpmap, newdesc;
  11522. for (i = 0; i < this.media.length; i++) {
  11523. lines = this.media[i].split('\r\n');
  11524. lines.pop(); // remove empty last element
  11525. mline = SDPUtil.parse_mline(lines.shift());
  11526. if (mline.media != 'audio')
  11527. continue;
  11528. newdesc = '';
  11529. mline.fmt.length = 0;
  11530. for (j = 0; j < lines.length; j++) {
  11531. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11532. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11533. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11534. continue;
  11535. mline.fmt.push(rtpmap.id);
  11536. newdesc += lines[j] + '\r\n';
  11537. } else {
  11538. newdesc += lines[j] + '\r\n';
  11539. }
  11540. }
  11541. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11542. this.media[i] += newdesc;
  11543. }
  11544. this.raw = this.session + this.media.join('');
  11545. };
  11546. // remove lines matching prefix from session section
  11547. SDP.prototype.removeSessionLines = function(prefix) {
  11548. var self = this;
  11549. var lines = SDPUtil.find_lines(this.session, prefix);
  11550. lines.forEach(function(line) {
  11551. self.session = self.session.replace(line + '\r\n', '');
  11552. });
  11553. this.raw = this.session + this.media.join('');
  11554. return lines;
  11555. }
  11556. // remove lines matching prefix from a media section specified by mediaindex
  11557. // TODO: non-numeric mediaindex could match mid
  11558. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11559. var self = this;
  11560. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11561. lines.forEach(function(line) {
  11562. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11563. });
  11564. this.raw = this.session + this.media.join('');
  11565. return lines;
  11566. }
  11567. // add content's to a jingle element
  11568. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11569. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11570. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11571. var self = this;
  11572. // new bundle plan
  11573. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11574. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11575. for (i = 0; i < lines.length; i++) {
  11576. tmp = lines[i].split(' ');
  11577. var semantics = tmp.shift().substr(8);
  11578. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11579. for (j = 0; j < tmp.length; j++) {
  11580. elem.c('content', {name: tmp[j]}).up();
  11581. }
  11582. elem.up();
  11583. }
  11584. }
  11585. for (i = 0; i < this.media.length; i++) {
  11586. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11587. if (!(mline.media === 'audio' ||
  11588. mline.media === 'video' ||
  11589. mline.media === 'application'))
  11590. {
  11591. continue;
  11592. }
  11593. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11594. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11595. } else {
  11596. if(ssrcs && ssrcs[mline.media])
  11597. {
  11598. ssrc = ssrcs[mline.media];
  11599. }
  11600. else
  11601. ssrc = false;
  11602. }
  11603. elem.c('content', {creator: thecreator, name: mline.media});
  11604. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11605. // prefer identifier from a=mid if present
  11606. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11607. elem.attrs({ name: mid });
  11608. }
  11609. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11610. {
  11611. elem.c('description',
  11612. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11613. media: mline.media });
  11614. if (ssrc) {
  11615. elem.attrs({ssrc: ssrc});
  11616. }
  11617. for (j = 0; j < mline.fmt.length; j++) {
  11618. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11619. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11620. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11621. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11622. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11623. for (k = 0; k < tmp.length; k++) {
  11624. elem.c('parameter', tmp[k]).up();
  11625. }
  11626. }
  11627. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11628. elem.up();
  11629. }
  11630. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11631. elem.c('encryption', {required: 1});
  11632. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11633. crypto.forEach(function(line) {
  11634. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11635. });
  11636. elem.up(); // end of encryption
  11637. }
  11638. if (ssrc) {
  11639. // new style mapping
  11640. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11641. // FIXME: group by ssrc and support multiple different ssrcs
  11642. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11643. if(ssrclines.length > 0) {
  11644. ssrclines.forEach(function (line) {
  11645. idx = line.indexOf(' ');
  11646. var linessrc = line.substr(0, idx).substr(7);
  11647. if (linessrc != ssrc) {
  11648. elem.up();
  11649. ssrc = linessrc;
  11650. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11651. }
  11652. var kv = line.substr(idx + 1);
  11653. elem.c('parameter');
  11654. if (kv.indexOf(':') == -1) {
  11655. elem.attrs({ name: kv });
  11656. } else {
  11657. elem.attrs({ name: kv.split(':', 2)[0] });
  11658. elem.attrs({ value: kv.split(':', 2)[1] });
  11659. }
  11660. elem.up();
  11661. });
  11662. elem.up();
  11663. }
  11664. else
  11665. {
  11666. elem.up();
  11667. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11668. elem.c('parameter');
  11669. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11670. elem.up();
  11671. var msid = null;
  11672. if(mline.media == "audio")
  11673. {
  11674. msid = APP.RTC.localAudio.getId();
  11675. }
  11676. else
  11677. {
  11678. msid = APP.RTC.localVideo.getId();
  11679. }
  11680. if(msid != null)
  11681. {
  11682. msid = msid.replace(/[\{,\}]/g,"");
  11683. elem.c('parameter');
  11684. elem.attrs({name: "msid", value:msid});
  11685. elem.up();
  11686. elem.c('parameter');
  11687. elem.attrs({name: "mslabel", value:msid});
  11688. elem.up();
  11689. elem.c('parameter');
  11690. elem.attrs({name: "label", value:msid});
  11691. elem.up();
  11692. elem.up();
  11693. }
  11694. }
  11695. // XEP-0339 handle ssrc-group attributes
  11696. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11697. ssrc_group_lines.forEach(function(line) {
  11698. idx = line.indexOf(' ');
  11699. var semantics = line.substr(0, idx).substr(13);
  11700. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11701. if (ssrcs.length != 0) {
  11702. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11703. ssrcs.forEach(function(ssrc) {
  11704. elem.c('source', { ssrc: ssrc })
  11705. .up();
  11706. });
  11707. elem.up();
  11708. }
  11709. });
  11710. }
  11711. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11712. elem.c('rtcp-mux').up();
  11713. }
  11714. // XEP-0293 -- map a=rtcp-fb:*
  11715. this.RtcpFbToJingle(i, elem, '*');
  11716. // XEP-0294
  11717. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11718. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11719. for (j = 0; j < lines.length; j++) {
  11720. tmp = SDPUtil.parse_extmap(lines[j]);
  11721. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11722. uri: tmp.uri,
  11723. id: tmp.value });
  11724. if (tmp.hasOwnProperty('direction')) {
  11725. switch (tmp.direction) {
  11726. case 'sendonly':
  11727. elem.attrs({senders: 'responder'});
  11728. break;
  11729. case 'recvonly':
  11730. elem.attrs({senders: 'initiator'});
  11731. break;
  11732. case 'sendrecv':
  11733. elem.attrs({senders: 'both'});
  11734. break;
  11735. case 'inactive':
  11736. elem.attrs({senders: 'none'});
  11737. break;
  11738. }
  11739. }
  11740. // TODO: handle params
  11741. elem.up();
  11742. }
  11743. }
  11744. elem.up(); // end of description
  11745. }
  11746. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11747. this.TransportToJingle(i, elem);
  11748. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11749. elem.attrs({senders: 'both'});
  11750. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11751. elem.attrs({senders: 'initiator'});
  11752. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11753. elem.attrs({senders: 'responder'});
  11754. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11755. elem.attrs({senders: 'none'});
  11756. }
  11757. if (mline.port == '0') {
  11758. // estos hack to reject an m-line
  11759. elem.attrs({senders: 'rejected'});
  11760. }
  11761. elem.up(); // end of content
  11762. }
  11763. elem.up();
  11764. return elem;
  11765. };
  11766. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11767. var i = mediaindex;
  11768. var tmp;
  11769. var self = this;
  11770. elem.c('transport');
  11771. // XEP-0343 DTLS/SCTP
  11772. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11773. {
  11774. var sctpmap = SDPUtil.find_line(
  11775. this.media[i], 'a=sctpmap:', self.session);
  11776. if (sctpmap)
  11777. {
  11778. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11779. elem.c('sctpmap',
  11780. {
  11781. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11782. number: sctpAttrs[0], /* SCTP port */
  11783. protocol: sctpAttrs[1], /* protocol */
  11784. });
  11785. // Optional stream count attribute
  11786. if (sctpAttrs.length > 2)
  11787. elem.attrs({ streams: sctpAttrs[2]});
  11788. elem.up();
  11789. }
  11790. }
  11791. // XEP-0320
  11792. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11793. fingerprints.forEach(function(line) {
  11794. tmp = SDPUtil.parse_fingerprint(line);
  11795. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11796. elem.c('fingerprint').t(tmp.fingerprint);
  11797. delete tmp.fingerprint;
  11798. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11799. if (line) {
  11800. tmp.setup = line.substr(8);
  11801. }
  11802. elem.attrs(tmp);
  11803. elem.up(); // end of fingerprint
  11804. });
  11805. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11806. if (tmp) {
  11807. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11808. elem.attrs(tmp);
  11809. // XEP-0176
  11810. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11811. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11812. lines.forEach(function (line) {
  11813. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11814. });
  11815. }
  11816. }
  11817. elem.up(); // end of transport
  11818. }
  11819. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11820. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11821. lines.forEach(function (line) {
  11822. var tmp = SDPUtil.parse_rtcpfb(line);
  11823. if (tmp.type == 'trr-int') {
  11824. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11825. elem.up();
  11826. } else {
  11827. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11828. if (tmp.params.length > 0) {
  11829. elem.attrs({'subtype': tmp.params[0]});
  11830. }
  11831. elem.up();
  11832. }
  11833. });
  11834. };
  11835. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11836. var media = '';
  11837. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11838. if (tmp.length) {
  11839. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11840. if (tmp.attr('value')) {
  11841. media += tmp.attr('value');
  11842. } else {
  11843. media += '0';
  11844. }
  11845. media += '\r\n';
  11846. }
  11847. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11848. tmp.each(function () {
  11849. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11850. if ($(this).attr('subtype')) {
  11851. media += ' ' + $(this).attr('subtype');
  11852. }
  11853. media += '\r\n';
  11854. });
  11855. return media;
  11856. };
  11857. // construct an SDP from a jingle stanza
  11858. SDP.prototype.fromJingle = function (jingle) {
  11859. var self = this;
  11860. this.raw = 'v=0\r\n' +
  11861. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11862. 's=-\r\n' +
  11863. 't=0 0\r\n';
  11864. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11865. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11866. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11867. var contents = $(group).find('>content').map(function (idx, content) {
  11868. return content.getAttribute('name');
  11869. }).get();
  11870. if (contents.length > 0) {
  11871. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11872. }
  11873. });
  11874. }
  11875. this.session = this.raw;
  11876. jingle.find('>content').each(function () {
  11877. var m = self.jingle2media($(this));
  11878. self.media.push(m);
  11879. });
  11880. // reconstruct msid-semantic -- apparently not necessary
  11881. /*
  11882. var msid = SDPUtil.parse_ssrc(this.raw);
  11883. if (msid.hasOwnProperty('mslabel')) {
  11884. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11885. }
  11886. */
  11887. this.raw = this.session + this.media.join('');
  11888. };
  11889. // translate a jingle content element into an an SDP media part
  11890. SDP.prototype.jingle2media = function (content) {
  11891. var media = '',
  11892. desc = content.find('description'),
  11893. ssrc = desc.attr('ssrc'),
  11894. self = this,
  11895. tmp;
  11896. var sctp = content.find(
  11897. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11898. tmp = { media: desc.attr('media') };
  11899. tmp.port = '1';
  11900. if (content.attr('senders') == 'rejected') {
  11901. // estos hack to reject an m-line.
  11902. tmp.port = '0';
  11903. }
  11904. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11905. if (sctp.length)
  11906. tmp.proto = 'DTLS/SCTP';
  11907. else
  11908. tmp.proto = 'RTP/SAVPF';
  11909. } else {
  11910. tmp.proto = 'RTP/AVPF';
  11911. }
  11912. if (!sctp.length)
  11913. {
  11914. tmp.fmt = desc.find('payload-type').map(
  11915. function () { return this.getAttribute('id'); }).get();
  11916. media += SDPUtil.build_mline(tmp) + '\r\n';
  11917. }
  11918. else
  11919. {
  11920. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11921. media += 'a=sctpmap:' + sctp.attr('number') +
  11922. ' ' + sctp.attr('protocol');
  11923. var streamCount = sctp.attr('streams');
  11924. if (streamCount)
  11925. media += ' ' + streamCount + '\r\n';
  11926. else
  11927. media += '\r\n';
  11928. }
  11929. media += 'c=IN IP4 0.0.0.0\r\n';
  11930. if (!sctp.length)
  11931. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  11932. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  11933. if (tmp.length) {
  11934. if (tmp.attr('ufrag')) {
  11935. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  11936. }
  11937. if (tmp.attr('pwd')) {
  11938. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  11939. }
  11940. tmp.find('>fingerprint').each(function () {
  11941. // FIXME: check namespace at some point
  11942. media += 'a=fingerprint:' + this.getAttribute('hash');
  11943. media += ' ' + $(this).text();
  11944. media += '\r\n';
  11945. if (this.getAttribute('setup')) {
  11946. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  11947. }
  11948. });
  11949. }
  11950. switch (content.attr('senders')) {
  11951. case 'initiator':
  11952. media += 'a=sendonly\r\n';
  11953. break;
  11954. case 'responder':
  11955. media += 'a=recvonly\r\n';
  11956. break;
  11957. case 'none':
  11958. media += 'a=inactive\r\n';
  11959. break;
  11960. case 'both':
  11961. media += 'a=sendrecv\r\n';
  11962. break;
  11963. }
  11964. media += 'a=mid:' + content.attr('name') + '\r\n';
  11965. // <description><rtcp-mux/></description>
  11966. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  11967. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  11968. if (desc.find('rtcp-mux').length) {
  11969. media += 'a=rtcp-mux\r\n';
  11970. }
  11971. if (desc.find('encryption').length) {
  11972. desc.find('encryption>crypto').each(function () {
  11973. media += 'a=crypto:' + this.getAttribute('tag');
  11974. media += ' ' + this.getAttribute('crypto-suite');
  11975. media += ' ' + this.getAttribute('key-params');
  11976. if (this.getAttribute('session-params')) {
  11977. media += ' ' + this.getAttribute('session-params');
  11978. }
  11979. media += '\r\n';
  11980. });
  11981. }
  11982. desc.find('payload-type').each(function () {
  11983. media += SDPUtil.build_rtpmap(this) + '\r\n';
  11984. if ($(this).find('>parameter').length) {
  11985. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  11986. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  11987. media += '\r\n';
  11988. }
  11989. // xep-0293
  11990. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  11991. });
  11992. // xep-0293
  11993. media += self.RtcpFbFromJingle(desc, '*');
  11994. // xep-0294
  11995. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  11996. tmp.each(function () {
  11997. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  11998. });
  11999. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12000. media += SDPUtil.candidateFromJingle(this);
  12001. });
  12002. // XEP-0339 handle ssrc-group attributes
  12003. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12004. var semantics = this.getAttribute('semantics');
  12005. var ssrcs = $(this).find('>source').map(function() {
  12006. return this.getAttribute('ssrc');
  12007. }).get();
  12008. if (ssrcs.length != 0) {
  12009. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12010. }
  12011. });
  12012. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12013. tmp.each(function () {
  12014. var ssrc = this.getAttribute('ssrc');
  12015. $(this).find('>parameter').each(function () {
  12016. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12017. if (this.getAttribute('value') && this.getAttribute('value').length)
  12018. media += ':' + this.getAttribute('value');
  12019. media += '\r\n';
  12020. });
  12021. });
  12022. return media;
  12023. };
  12024. module.exports = SDP;
  12025. },{"./SDPUtil":56}],55:[function(require,module,exports){
  12026. function SDPDiffer(mySDP, otherSDP) {
  12027. this.mySDP = mySDP;
  12028. this.otherSDP = otherSDP;
  12029. }
  12030. /**
  12031. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12032. * @param otherSdp the other SDP to check ssrc with.
  12033. */
  12034. SDPDiffer.prototype.getNewMedia = function() {
  12035. // this could be useful in Array.prototype.
  12036. function arrayEquals(array) {
  12037. // if the other array is a falsy value, return
  12038. if (!array)
  12039. return false;
  12040. // compare lengths - can save a lot of time
  12041. if (this.length != array.length)
  12042. return false;
  12043. for (var i = 0, l=this.length; i < l; i++) {
  12044. // Check if we have nested arrays
  12045. if (this[i] instanceof Array && array[i] instanceof Array) {
  12046. // recurse into the nested arrays
  12047. if (!this[i].equals(array[i]))
  12048. return false;
  12049. }
  12050. else if (this[i] != array[i]) {
  12051. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12052. return false;
  12053. }
  12054. }
  12055. return true;
  12056. }
  12057. var myMedias = this.mySDP.getMediaSsrcMap();
  12058. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12059. var newMedia = {};
  12060. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12061. var myMedia = myMedias[othersMediaIdx];
  12062. var othersMedia = othersMedias[othersMediaIdx];
  12063. if(!myMedia && othersMedia) {
  12064. // Add whole channel
  12065. newMedia[othersMediaIdx] = othersMedia;
  12066. return;
  12067. }
  12068. // Look for new ssrcs accross the channel
  12069. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12070. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12071. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12072. if(!newMedia[othersMediaIdx]){
  12073. newMedia[othersMediaIdx] = {
  12074. mediaindex: othersMedia.mediaindex,
  12075. mid: othersMedia.mid,
  12076. ssrcs: {},
  12077. ssrcGroups: []
  12078. };
  12079. }
  12080. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12081. }
  12082. });
  12083. // Look for new ssrc groups across the channels
  12084. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12085. // try to match the other ssrc-group with an ssrc-group of ours
  12086. var matched = false;
  12087. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12088. var mySsrcGroup = myMedia.ssrcGroups[i];
  12089. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12090. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12091. matched = true;
  12092. break;
  12093. }
  12094. }
  12095. if (!matched) {
  12096. // Allocate channel if we've found an ssrc-group that doesn't
  12097. // exist in our channel
  12098. if(!newMedia[othersMediaIdx]){
  12099. newMedia[othersMediaIdx] = {
  12100. mediaindex: othersMedia.mediaindex,
  12101. mid: othersMedia.mid,
  12102. ssrcs: {},
  12103. ssrcGroups: []
  12104. };
  12105. }
  12106. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12107. }
  12108. });
  12109. });
  12110. return newMedia;
  12111. };
  12112. /**
  12113. * Sends SSRC update IQ.
  12114. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12115. * @param sid session identifier that will be put into the IQ.
  12116. * @param initiator initiator identifier.
  12117. * @param toJid destination Jid
  12118. * @param isAdd indicates if this is remove or add operation.
  12119. */
  12120. SDPDiffer.prototype.toJingle = function(modify) {
  12121. var sdpMediaSsrcs = this.getNewMedia();
  12122. var self = this;
  12123. // FIXME: only announce video ssrcs since we mix audio and dont need
  12124. // the audio ssrcs therefore
  12125. var modified = false;
  12126. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12127. modified = true;
  12128. var media = sdpMediaSsrcs[mediaindex];
  12129. modify.c('content', {name: media.mid});
  12130. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12131. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12132. // generate sources from lines
  12133. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12134. var mediaSsrc = media.ssrcs[ssrcNum];
  12135. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12136. modify.attrs({ssrc: mediaSsrc.ssrc});
  12137. // iterate over ssrc lines
  12138. mediaSsrc.lines.forEach(function (line) {
  12139. var idx = line.indexOf(' ');
  12140. var kv = line.substr(idx + 1);
  12141. modify.c('parameter');
  12142. if (kv.indexOf(':') == -1) {
  12143. modify.attrs({ name: kv });
  12144. } else {
  12145. modify.attrs({ name: kv.split(':', 2)[0] });
  12146. modify.attrs({ value: kv.split(':', 2)[1] });
  12147. }
  12148. modify.up(); // end of parameter
  12149. });
  12150. modify.up(); // end of source
  12151. });
  12152. // generate source groups from lines
  12153. media.ssrcGroups.forEach(function(ssrcGroup) {
  12154. if (ssrcGroup.ssrcs.length != 0) {
  12155. modify.c('ssrc-group', {
  12156. semantics: ssrcGroup.semantics,
  12157. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12158. });
  12159. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12160. modify.c('source', { ssrc: ssrc })
  12161. .up(); // end of source
  12162. });
  12163. modify.up(); // end of ssrc-group
  12164. }
  12165. });
  12166. modify.up(); // end of description
  12167. modify.up(); // end of content
  12168. });
  12169. return modified;
  12170. };
  12171. module.exports = SDPDiffer;
  12172. },{}],56:[function(require,module,exports){
  12173. SDPUtil = {
  12174. iceparams: function (mediadesc, sessiondesc) {
  12175. var data = null;
  12176. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12177. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12178. data = {
  12179. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12180. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12181. };
  12182. }
  12183. return data;
  12184. },
  12185. parse_iceufrag: function (line) {
  12186. return line.substring(12);
  12187. },
  12188. build_iceufrag: function (frag) {
  12189. return 'a=ice-ufrag:' + frag;
  12190. },
  12191. parse_icepwd: function (line) {
  12192. return line.substring(10);
  12193. },
  12194. build_icepwd: function (pwd) {
  12195. return 'a=ice-pwd:' + pwd;
  12196. },
  12197. parse_mid: function (line) {
  12198. return line.substring(6);
  12199. },
  12200. parse_mline: function (line) {
  12201. var parts = line.substring(2).split(' '),
  12202. data = {};
  12203. data.media = parts.shift();
  12204. data.port = parts.shift();
  12205. data.proto = parts.shift();
  12206. if (parts[parts.length - 1] === '') { // trailing whitespace
  12207. parts.pop();
  12208. }
  12209. data.fmt = parts;
  12210. return data;
  12211. },
  12212. build_mline: function (mline) {
  12213. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12214. },
  12215. parse_rtpmap: function (line) {
  12216. var parts = line.substring(9).split(' '),
  12217. data = {};
  12218. data.id = parts.shift();
  12219. parts = parts[0].split('/');
  12220. data.name = parts.shift();
  12221. data.clockrate = parts.shift();
  12222. data.channels = parts.length ? parts.shift() : '1';
  12223. return data;
  12224. },
  12225. /**
  12226. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12227. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12228. * @returns [SCTP port number, protocol, streams]
  12229. */
  12230. parse_sctpmap: function (line)
  12231. {
  12232. var parts = line.substring(10).split(' ');
  12233. var sctpPort = parts[0];
  12234. var protocol = parts[1];
  12235. // Stream count is optional
  12236. var streamCount = parts.length > 2 ? parts[2] : null;
  12237. return [sctpPort, protocol, streamCount];// SCTP port
  12238. },
  12239. build_rtpmap: function (el) {
  12240. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12241. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12242. line += '/' + el.getAttribute('channels');
  12243. }
  12244. return line;
  12245. },
  12246. parse_crypto: function (line) {
  12247. var parts = line.substring(9).split(' '),
  12248. data = {};
  12249. data.tag = parts.shift();
  12250. data['crypto-suite'] = parts.shift();
  12251. data['key-params'] = parts.shift();
  12252. if (parts.length) {
  12253. data['session-params'] = parts.join(' ');
  12254. }
  12255. return data;
  12256. },
  12257. parse_fingerprint: function (line) { // RFC 4572
  12258. var parts = line.substring(14).split(' '),
  12259. data = {};
  12260. data.hash = parts.shift();
  12261. data.fingerprint = parts.shift();
  12262. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12263. return data;
  12264. },
  12265. parse_fmtp: function (line) {
  12266. var parts = line.split(' '),
  12267. i, key, value,
  12268. data = [];
  12269. parts.shift();
  12270. parts = parts.join(' ').split(';');
  12271. for (i = 0; i < parts.length; i++) {
  12272. key = parts[i].split('=')[0];
  12273. while (key.length && key[0] == ' ') {
  12274. key = key.substring(1);
  12275. }
  12276. value = parts[i].split('=')[1];
  12277. if (key && value) {
  12278. data.push({name: key, value: value});
  12279. } else if (key) {
  12280. // rfc 4733 (DTMF) style stuff
  12281. data.push({name: '', value: key});
  12282. }
  12283. }
  12284. return data;
  12285. },
  12286. parse_icecandidate: function (line) {
  12287. var candidate = {},
  12288. elems = line.split(' ');
  12289. candidate.foundation = elems[0].substring(12);
  12290. candidate.component = elems[1];
  12291. candidate.protocol = elems[2].toLowerCase();
  12292. candidate.priority = elems[3];
  12293. candidate.ip = elems[4];
  12294. candidate.port = elems[5];
  12295. // elems[6] => "typ"
  12296. candidate.type = elems[7];
  12297. candidate.generation = 0; // default value, may be overwritten below
  12298. for (var i = 8; i < elems.length; i += 2) {
  12299. switch (elems[i]) {
  12300. case 'raddr':
  12301. candidate['rel-addr'] = elems[i + 1];
  12302. break;
  12303. case 'rport':
  12304. candidate['rel-port'] = elems[i + 1];
  12305. break;
  12306. case 'generation':
  12307. candidate.generation = elems[i + 1];
  12308. break;
  12309. case 'tcptype':
  12310. candidate.tcptype = elems[i + 1];
  12311. break;
  12312. default: // TODO
  12313. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12314. }
  12315. }
  12316. candidate.network = '1';
  12317. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12318. return candidate;
  12319. },
  12320. build_icecandidate: function (cand) {
  12321. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12322. line += ' ';
  12323. switch (cand.type) {
  12324. case 'srflx':
  12325. case 'prflx':
  12326. case 'relay':
  12327. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12328. line += 'raddr';
  12329. line += ' ';
  12330. line += cand['rel-addr'];
  12331. line += ' ';
  12332. line += 'rport';
  12333. line += ' ';
  12334. line += cand['rel-port'];
  12335. line += ' ';
  12336. }
  12337. break;
  12338. }
  12339. if (cand.hasOwnAttribute('tcptype')) {
  12340. line += 'tcptype';
  12341. line += ' ';
  12342. line += cand.tcptype;
  12343. line += ' ';
  12344. }
  12345. line += 'generation';
  12346. line += ' ';
  12347. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12348. return line;
  12349. },
  12350. parse_ssrc: function (desc) {
  12351. // proprietary mapping of a=ssrc lines
  12352. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12353. // and parse according to that
  12354. var lines = desc.split('\r\n'),
  12355. data = {};
  12356. for (var i = 0; i < lines.length; i++) {
  12357. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12358. var idx = lines[i].indexOf(' ');
  12359. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12360. }
  12361. }
  12362. return data;
  12363. },
  12364. parse_rtcpfb: function (line) {
  12365. var parts = line.substr(10).split(' ');
  12366. var data = {};
  12367. data.pt = parts.shift();
  12368. data.type = parts.shift();
  12369. data.params = parts;
  12370. return data;
  12371. },
  12372. parse_extmap: function (line) {
  12373. var parts = line.substr(9).split(' ');
  12374. var data = {};
  12375. data.value = parts.shift();
  12376. if (data.value.indexOf('/') != -1) {
  12377. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12378. data.value = data.value.substr(0, data.value.indexOf('/'));
  12379. } else {
  12380. data.direction = 'both';
  12381. }
  12382. data.uri = parts.shift();
  12383. data.params = parts;
  12384. return data;
  12385. },
  12386. find_line: function (haystack, needle, sessionpart) {
  12387. var lines = haystack.split('\r\n');
  12388. for (var i = 0; i < lines.length; i++) {
  12389. if (lines[i].substring(0, needle.length) == needle) {
  12390. return lines[i];
  12391. }
  12392. }
  12393. if (!sessionpart) {
  12394. return false;
  12395. }
  12396. // search session part
  12397. lines = sessionpart.split('\r\n');
  12398. for (var j = 0; j < lines.length; j++) {
  12399. if (lines[j].substring(0, needle.length) == needle) {
  12400. return lines[j];
  12401. }
  12402. }
  12403. return false;
  12404. },
  12405. find_lines: function (haystack, needle, sessionpart) {
  12406. var lines = haystack.split('\r\n'),
  12407. needles = [];
  12408. for (var i = 0; i < lines.length; i++) {
  12409. if (lines[i].substring(0, needle.length) == needle)
  12410. needles.push(lines[i]);
  12411. }
  12412. if (needles.length || !sessionpart) {
  12413. return needles;
  12414. }
  12415. // search session part
  12416. lines = sessionpart.split('\r\n');
  12417. for (var j = 0; j < lines.length; j++) {
  12418. if (lines[j].substring(0, needle.length) == needle) {
  12419. needles.push(lines[j]);
  12420. }
  12421. }
  12422. return needles;
  12423. },
  12424. candidateToJingle: function (line) {
  12425. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12426. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12427. if (line.indexOf('candidate:') === 0) {
  12428. line = 'a=' + line;
  12429. } else if (line.substring(0, 12) != 'a=candidate:') {
  12430. console.log('parseCandidate called with a line that is not a candidate line');
  12431. console.log(line);
  12432. return null;
  12433. }
  12434. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12435. line = line.substring(0, line.length - 2);
  12436. var candidate = {},
  12437. elems = line.split(' '),
  12438. i;
  12439. if (elems[6] != 'typ') {
  12440. console.log('did not find typ in the right place');
  12441. console.log(line);
  12442. return null;
  12443. }
  12444. candidate.foundation = elems[0].substring(12);
  12445. candidate.component = elems[1];
  12446. candidate.protocol = elems[2].toLowerCase();
  12447. candidate.priority = elems[3];
  12448. candidate.ip = elems[4];
  12449. candidate.port = elems[5];
  12450. // elems[6] => "typ"
  12451. candidate.type = elems[7];
  12452. candidate.generation = '0'; // default, may be overwritten below
  12453. for (i = 8; i < elems.length; i += 2) {
  12454. switch (elems[i]) {
  12455. case 'raddr':
  12456. candidate['rel-addr'] = elems[i + 1];
  12457. break;
  12458. case 'rport':
  12459. candidate['rel-port'] = elems[i + 1];
  12460. break;
  12461. case 'generation':
  12462. candidate.generation = elems[i + 1];
  12463. break;
  12464. case 'tcptype':
  12465. candidate.tcptype = elems[i + 1];
  12466. break;
  12467. default: // TODO
  12468. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12469. }
  12470. }
  12471. candidate.network = '1';
  12472. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12473. return candidate;
  12474. },
  12475. candidateFromJingle: function (cand) {
  12476. var line = 'a=candidate:';
  12477. line += cand.getAttribute('foundation');
  12478. line += ' ';
  12479. line += cand.getAttribute('component');
  12480. line += ' ';
  12481. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12482. line += ' ';
  12483. line += cand.getAttribute('priority');
  12484. line += ' ';
  12485. line += cand.getAttribute('ip');
  12486. line += ' ';
  12487. line += cand.getAttribute('port');
  12488. line += ' ';
  12489. line += 'typ';
  12490. line += ' ' + cand.getAttribute('type');
  12491. line += ' ';
  12492. switch (cand.getAttribute('type')) {
  12493. case 'srflx':
  12494. case 'prflx':
  12495. case 'relay':
  12496. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12497. line += 'raddr';
  12498. line += ' ';
  12499. line += cand.getAttribute('rel-addr');
  12500. line += ' ';
  12501. line += 'rport';
  12502. line += ' ';
  12503. line += cand.getAttribute('rel-port');
  12504. line += ' ';
  12505. }
  12506. break;
  12507. }
  12508. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12509. line += 'tcptype';
  12510. line += ' ';
  12511. line += cand.getAttribute('tcptype');
  12512. line += ' ';
  12513. }
  12514. line += 'generation';
  12515. line += ' ';
  12516. line += cand.getAttribute('generation') || '0';
  12517. return line + '\r\n';
  12518. }
  12519. };
  12520. module.exports = SDPUtil;
  12521. },{}],57:[function(require,module,exports){
  12522. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12523. function TraceablePeerConnection(ice_config, constraints, session) {
  12524. var self = this;
  12525. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12526. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12527. this.updateLog = [];
  12528. this.stats = {};
  12529. this.statsinterval = null;
  12530. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12531. var Interop = require('sdp-interop').Interop;
  12532. this.interop = new Interop();
  12533. var Simulcast = require('sdp-simulcast');
  12534. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  12535. // override as desired
  12536. this.trace = function (what, info) {
  12537. //console.warn('WTRACE', what, info);
  12538. self.updateLog.push({
  12539. time: new Date(),
  12540. type: what,
  12541. value: info || ""
  12542. });
  12543. };
  12544. this.onicecandidate = null;
  12545. this.peerconnection.onicecandidate = function (event) {
  12546. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12547. if (self.onicecandidate !== null) {
  12548. self.onicecandidate(event);
  12549. }
  12550. };
  12551. this.onaddstream = null;
  12552. this.peerconnection.onaddstream = function (event) {
  12553. self.trace('onaddstream', event.stream.id);
  12554. if (self.onaddstream !== null) {
  12555. self.onaddstream(event);
  12556. }
  12557. };
  12558. this.onremovestream = null;
  12559. this.peerconnection.onremovestream = function (event) {
  12560. self.trace('onremovestream', event.stream.id);
  12561. if (self.onremovestream !== null) {
  12562. self.onremovestream(event);
  12563. }
  12564. };
  12565. this.onsignalingstatechange = null;
  12566. this.peerconnection.onsignalingstatechange = function (event) {
  12567. self.trace('onsignalingstatechange', self.signalingState);
  12568. if (self.onsignalingstatechange !== null) {
  12569. self.onsignalingstatechange(event);
  12570. }
  12571. };
  12572. this.oniceconnectionstatechange = null;
  12573. this.peerconnection.oniceconnectionstatechange = function (event) {
  12574. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12575. if (self.oniceconnectionstatechange !== null) {
  12576. self.oniceconnectionstatechange(event);
  12577. }
  12578. };
  12579. this.onnegotiationneeded = null;
  12580. this.peerconnection.onnegotiationneeded = function (event) {
  12581. self.trace('onnegotiationneeded');
  12582. if (self.onnegotiationneeded !== null) {
  12583. self.onnegotiationneeded(event);
  12584. }
  12585. };
  12586. self.ondatachannel = null;
  12587. this.peerconnection.ondatachannel = function (event) {
  12588. self.trace('ondatachannel', event);
  12589. if (self.ondatachannel !== null) {
  12590. self.ondatachannel(event);
  12591. }
  12592. };
  12593. if (!navigator.mozGetUserMedia && this.maxstats) {
  12594. this.statsinterval = window.setInterval(function() {
  12595. self.peerconnection.getStats(function(stats) {
  12596. var results = stats.result();
  12597. for (var i = 0; i < results.length; ++i) {
  12598. //console.log(results[i].type, results[i].id, results[i].names())
  12599. var now = new Date();
  12600. results[i].names().forEach(function (name) {
  12601. var id = results[i].id + '-' + name;
  12602. if (!self.stats[id]) {
  12603. self.stats[id] = {
  12604. startTime: now,
  12605. endTime: now,
  12606. values: [],
  12607. times: []
  12608. };
  12609. }
  12610. self.stats[id].values.push(results[i].stat(name));
  12611. self.stats[id].times.push(now.getTime());
  12612. if (self.stats[id].values.length > self.maxstats) {
  12613. self.stats[id].values.shift();
  12614. self.stats[id].times.shift();
  12615. }
  12616. self.stats[id].endTime = now;
  12617. });
  12618. }
  12619. });
  12620. }, 1000);
  12621. }
  12622. };
  12623. dumpSDP = function(description) {
  12624. if (typeof description === 'undefined' || description == null) {
  12625. return '';
  12626. }
  12627. return 'type: ' + description.type + '\r\n' + description.sdp;
  12628. };
  12629. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12630. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12631. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12632. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12633. var desc = this.peerconnection.localDescription;
  12634. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  12635. // if we're running on FF, transform to Plan B first.
  12636. if (navigator.mozGetUserMedia) {
  12637. desc = this.interop.toPlanB(desc);
  12638. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12639. }
  12640. return desc;
  12641. });
  12642. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12643. var desc = this.peerconnection.remoteDescription;
  12644. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  12645. // if we're running on FF, transform to Plan B first.
  12646. if (navigator.mozGetUserMedia) {
  12647. desc = this.interop.toPlanB(desc);
  12648. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  12649. }
  12650. return desc;
  12651. });
  12652. }
  12653. TraceablePeerConnection.prototype.addStream = function (stream) {
  12654. this.trace('addStream', stream.id);
  12655. try
  12656. {
  12657. this.peerconnection.addStream(stream);
  12658. }
  12659. catch (e)
  12660. {
  12661. console.error(e);
  12662. return;
  12663. }
  12664. };
  12665. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12666. this.trace('removeStream', stream.id);
  12667. if(stopStreams) {
  12668. stream.getAudioTracks().forEach(function (track) {
  12669. track.stop();
  12670. });
  12671. stream.getVideoTracks().forEach(function (track) {
  12672. track.stop();
  12673. });
  12674. }
  12675. try {
  12676. // FF doesn't support this yet.
  12677. this.peerconnection.removeStream(stream);
  12678. } catch (e) {
  12679. console.error(e);
  12680. }
  12681. };
  12682. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12683. this.trace('createDataChannel', label, opts);
  12684. return this.peerconnection.createDataChannel(label, opts);
  12685. };
  12686. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12687. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  12688. // if we're running on FF, transform to Plan A first.
  12689. if (navigator.mozGetUserMedia) {
  12690. description = this.interop.toUnifiedPlan(description);
  12691. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  12692. }
  12693. var self = this;
  12694. this.peerconnection.setLocalDescription(description,
  12695. function () {
  12696. self.trace('setLocalDescriptionOnSuccess');
  12697. successCallback();
  12698. },
  12699. function (err) {
  12700. self.trace('setLocalDescriptionOnFailure', err);
  12701. failureCallback(err);
  12702. }
  12703. );
  12704. /*
  12705. if (this.statsinterval === null && this.maxstats > 0) {
  12706. // start gathering stats
  12707. }
  12708. */
  12709. };
  12710. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12711. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  12712. // TODO the focus should squeze or explode the remote simulcast
  12713. description = this.simulcast.mungeRemoteDescription(description);
  12714. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  12715. // if we're running on FF, transform to Plan A first.
  12716. if (navigator.mozGetUserMedia) {
  12717. description = this.interop.toUnifiedPlan(description);
  12718. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  12719. }
  12720. var self = this;
  12721. this.peerconnection.setRemoteDescription(description,
  12722. function () {
  12723. self.trace('setRemoteDescriptionOnSuccess');
  12724. successCallback();
  12725. },
  12726. function (err) {
  12727. self.trace('setRemoteDescriptionOnFailure', err);
  12728. failureCallback(err);
  12729. }
  12730. );
  12731. /*
  12732. if (this.statsinterval === null && this.maxstats > 0) {
  12733. // start gathering stats
  12734. }
  12735. */
  12736. };
  12737. TraceablePeerConnection.prototype.close = function () {
  12738. this.trace('stop');
  12739. if (this.statsinterval !== null) {
  12740. window.clearInterval(this.statsinterval);
  12741. this.statsinterval = null;
  12742. }
  12743. this.peerconnection.close();
  12744. };
  12745. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12746. var self = this;
  12747. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12748. this.peerconnection.createOffer(
  12749. function (offer) {
  12750. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  12751. // if we're running on FF, transform to Plan B first.
  12752. // NOTE this is not tested because in meet the focus generates the
  12753. // offer.
  12754. if (navigator.mozGetUserMedia) {
  12755. offer = self.interop.toPlanB(offer);
  12756. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  12757. }
  12758. if (config.enableSimulcast && self.simulcast.isSupported()) {
  12759. offer = self.simulcast.mungeLocalDescription(offer);
  12760. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  12761. }
  12762. successCallback(offer);
  12763. },
  12764. function(err) {
  12765. self.trace('createOfferOnFailure', err);
  12766. failureCallback(err);
  12767. },
  12768. constraints
  12769. );
  12770. };
  12771. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12772. var self = this;
  12773. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12774. this.peerconnection.createAnswer(
  12775. function (answer) {
  12776. self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
  12777. // if we're running on FF, transform to Plan A first.
  12778. if (navigator.mozGetUserMedia) {
  12779. answer = self.interop.toPlanB(answer);
  12780. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  12781. }
  12782. if (config.enableSimulcast && self.simulcast.isSupported()) {
  12783. answer = self.simulcast.mungeLocalDescription(answer);
  12784. self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
  12785. }
  12786. successCallback(answer);
  12787. },
  12788. function(err) {
  12789. self.trace('createAnswerOnFailure', err);
  12790. failureCallback(err);
  12791. },
  12792. constraints
  12793. );
  12794. };
  12795. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12796. var self = this;
  12797. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12798. this.peerconnection.addIceCandidate(candidate);
  12799. /* maybe later
  12800. this.peerconnection.addIceCandidate(candidate,
  12801. function () {
  12802. self.trace('addIceCandidateOnSuccess');
  12803. successCallback();
  12804. },
  12805. function (err) {
  12806. self.trace('addIceCandidateOnFailure', err);
  12807. failureCallback(err);
  12808. }
  12809. );
  12810. */
  12811. };
  12812. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12813. if (navigator.mozGetUserMedia) {
  12814. // ignore for now...
  12815. if(!errback)
  12816. errback = function () {
  12817. }
  12818. this.peerconnection.getStats(null,callback,errback);
  12819. } else {
  12820. this.peerconnection.getStats(callback);
  12821. }
  12822. };
  12823. module.exports = TraceablePeerConnection;
  12824. },{"../../service/xmpp/XMPPEvents":109,"sdp-interop":89,"sdp-simulcast":92}],58:[function(require,module,exports){
  12825. /* global $, $iq, APP, config, connection, UI, messageHandler,
  12826. roomName, sessionTerminated, Strophe, Util */
  12827. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12828. var Settings = require("../settings/Settings");
  12829. var AuthenticationEvents
  12830. = require("../../service/authentication/AuthenticationEvents");
  12831. /**
  12832. * Contains logic responsible for enabling/disabling functionality available
  12833. * only to moderator users.
  12834. */
  12835. var connection = null;
  12836. var focusUserJid;
  12837. function createExpBackoffTimer(step) {
  12838. var count = 1;
  12839. return function (reset) {
  12840. // Reset call
  12841. if (reset) {
  12842. count = 1;
  12843. return;
  12844. }
  12845. // Calculate next timeout
  12846. var timeout = Math.pow(2, count - 1);
  12847. count += 1;
  12848. return timeout * step;
  12849. };
  12850. }
  12851. var getNextTimeout = createExpBackoffTimer(1000);
  12852. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12853. // External authentication stuff
  12854. var externalAuthEnabled = false;
  12855. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12856. // it will be enabled automatically if focus detects the component through
  12857. // service discovery.
  12858. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12859. var eventEmitter = null;
  12860. var Moderator = {
  12861. isModerator: function () {
  12862. return connection && connection.emuc.isModerator();
  12863. },
  12864. isPeerModerator: function (peerJid) {
  12865. return connection &&
  12866. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12867. },
  12868. isExternalAuthEnabled: function () {
  12869. return externalAuthEnabled;
  12870. },
  12871. isSipGatewayEnabled: function () {
  12872. return sipGatewayEnabled;
  12873. },
  12874. setConnection: function (con) {
  12875. connection = con;
  12876. },
  12877. init: function (xmpp, emitter) {
  12878. this.xmppService = xmpp;
  12879. eventEmitter = emitter;
  12880. // Message listener that talks to POPUP window
  12881. function listener(event) {
  12882. if (event.data && event.data.sessionId) {
  12883. if (event.origin !== window.location.origin) {
  12884. console.warn(
  12885. "Ignoring sessionId from different origin: " + event.origin);
  12886. return;
  12887. }
  12888. localStorage.setItem('sessionId', event.data.sessionId);
  12889. // After popup is closed we will authenticate
  12890. }
  12891. }
  12892. // Register
  12893. if (window.addEventListener) {
  12894. window.addEventListener("message", listener, false);
  12895. } else {
  12896. window.attachEvent("onmessage", listener);
  12897. }
  12898. },
  12899. onMucMemberLeft: function (jid) {
  12900. console.info("Someone left is it focus ? " + jid);
  12901. var resource = Strophe.getResourceFromJid(jid);
  12902. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12903. console.info(
  12904. "Focus has left the room - leaving conference");
  12905. //hangUp();
  12906. // We'd rather reload to have everything re-initialized
  12907. // FIXME: show some message before reload
  12908. location.reload();
  12909. }
  12910. },
  12911. setFocusUserJid: function (focusJid) {
  12912. if (!focusUserJid) {
  12913. focusUserJid = focusJid;
  12914. console.info("Focus jid set to: " + focusUserJid);
  12915. }
  12916. },
  12917. getFocusUserJid: function () {
  12918. return focusUserJid;
  12919. },
  12920. getFocusComponent: function () {
  12921. // Get focus component address
  12922. var focusComponent = config.hosts.focus;
  12923. // If not specified use default: 'focus.domain'
  12924. if (!focusComponent) {
  12925. focusComponent = 'focus.' + config.hosts.domain;
  12926. }
  12927. return focusComponent;
  12928. },
  12929. createConferenceIq: function (roomName) {
  12930. // Generate create conference IQ
  12931. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12932. // Session Id used for authentication
  12933. var sessionId = localStorage.getItem('sessionId');
  12934. var machineUID = Settings.getSettings().uid;
  12935. console.info(
  12936. "Session ID: " + sessionId + " machine UID: " + machineUID);
  12937. elem.c('conference', {
  12938. xmlns: 'http://jitsi.org/protocol/focus',
  12939. room: roomName,
  12940. 'machine-uid': machineUID
  12941. });
  12942. if (sessionId) {
  12943. elem.attrs({ 'session-id': sessionId});
  12944. }
  12945. if (config.hosts.bridge !== undefined) {
  12946. elem.c(
  12947. 'property',
  12948. { name: 'bridge', value: config.hosts.bridge})
  12949. .up();
  12950. }
  12951. // Tell the focus we have Jigasi configured
  12952. if (config.hosts.call_control !== undefined) {
  12953. elem.c(
  12954. 'property',
  12955. { name: 'call_control', value: config.hosts.call_control})
  12956. .up();
  12957. }
  12958. if (config.channelLastN !== undefined) {
  12959. elem.c(
  12960. 'property',
  12961. { name: 'channelLastN', value: config.channelLastN})
  12962. .up();
  12963. }
  12964. if (config.adaptiveLastN !== undefined) {
  12965. elem.c(
  12966. 'property',
  12967. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12968. .up();
  12969. }
  12970. if (config.adaptiveSimulcast !== undefined) {
  12971. elem.c(
  12972. 'property',
  12973. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12974. .up();
  12975. }
  12976. if (config.openSctp !== undefined) {
  12977. elem.c(
  12978. 'property',
  12979. { name: 'openSctp', value: config.openSctp})
  12980. .up();
  12981. }
  12982. if(config.startAudioMuted !== undefined)
  12983. {
  12984. elem.c(
  12985. 'property',
  12986. { name: 'startAudioMuted', value: config.startAudioMuted})
  12987. .up();
  12988. }
  12989. if(config.startVideoMuted !== undefined)
  12990. {
  12991. elem.c(
  12992. 'property',
  12993. { name: 'startVideoMuted', value: config.startVideoMuted})
  12994. .up();
  12995. }
  12996. elem.c(
  12997. 'property',
  12998. { name: 'simulcastMode', value: 'rewriting'})
  12999. .up();
  13000. elem.up();
  13001. return elem;
  13002. },
  13003. parseSessionId: function (resultIq) {
  13004. var sessionId = $(resultIq).find('conference').attr('session-id');
  13005. if (sessionId) {
  13006. console.info('Received sessionId: ' + sessionId);
  13007. localStorage.setItem('sessionId', sessionId);
  13008. }
  13009. },
  13010. parseConfigOptions: function (resultIq) {
  13011. Moderator.setFocusUserJid(
  13012. $(resultIq).find('conference').attr('focusjid'));
  13013. var authenticationEnabled
  13014. = $(resultIq).find(
  13015. '>conference>property' +
  13016. '[name=\'authentication\'][value=\'true\']').length > 0;
  13017. console.info("Authentication enabled: " + authenticationEnabled);
  13018. externalAuthEnabled
  13019. = $(resultIq).find(
  13020. '>conference>property' +
  13021. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13022. console.info('External authentication enabled: ' + externalAuthEnabled);
  13023. if (!externalAuthEnabled) {
  13024. // We expect to receive sessionId in 'internal' authentication mode
  13025. Moderator.parseSessionId(resultIq);
  13026. }
  13027. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13028. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13029. authenticationEnabled, authIdentity);
  13030. // Check if focus has auto-detected Jigasi component(this will be also
  13031. // included if we have passed our host from the config)
  13032. if ($(resultIq).find(
  13033. '>conference>property' +
  13034. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13035. sipGatewayEnabled = true;
  13036. }
  13037. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13038. },
  13039. // FIXME: we need to show the fact that we're waiting for the focus
  13040. // to the user(or that focus is not available)
  13041. allocateConferenceFocus: function (roomName, callback) {
  13042. // Try to use focus user JID from the config
  13043. Moderator.setFocusUserJid(config.focusUserJid);
  13044. // Send create conference IQ
  13045. var iq = Moderator.createConferenceIq(roomName);
  13046. var self = this;
  13047. connection.sendIQ(
  13048. iq,
  13049. function (result) {
  13050. // Setup config options
  13051. Moderator.parseConfigOptions(result);
  13052. if ('true' === $(result).find('conference').attr('ready')) {
  13053. // Reset both timers
  13054. getNextTimeout(true);
  13055. getNextErrorTimeout(true);
  13056. // Exec callback
  13057. callback();
  13058. } else {
  13059. var waitMs = getNextTimeout();
  13060. console.info("Waiting for the focus... " + waitMs);
  13061. // Reset error timeout
  13062. getNextErrorTimeout(true);
  13063. window.setTimeout(
  13064. function () {
  13065. Moderator.allocateConferenceFocus(
  13066. roomName, callback);
  13067. }, waitMs);
  13068. }
  13069. },
  13070. function (error) {
  13071. // Invalid session ? remove and try again
  13072. // without session ID to get a new one
  13073. var invalidSession
  13074. = $(error).find('>error>session-invalid').length;
  13075. if (invalidSession) {
  13076. console.info("Session expired! - removing");
  13077. localStorage.removeItem("sessionId");
  13078. }
  13079. if ($(error).find('>error>graceful-shutdown').length) {
  13080. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13081. return;
  13082. }
  13083. // Check for error returned by the reservation system
  13084. var reservationErr = $(error).find('>error>reservation-error');
  13085. if (reservationErr.length) {
  13086. // Trigger error event
  13087. var errorCode = reservationErr.attr('error-code');
  13088. var errorMsg;
  13089. if ($(error).find('>error>text')) {
  13090. errorMsg = $(error).find('>error>text').text();
  13091. }
  13092. eventEmitter.emit(
  13093. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13094. return;
  13095. }
  13096. // Not authorized to create new room
  13097. if ($(error).find('>error>not-authorized').length) {
  13098. console.warn("Unauthorized to start the conference", error);
  13099. var toDomain
  13100. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13101. if (toDomain !== config.hosts.anonymousdomain) {
  13102. // FIXME: "is external" should come either from
  13103. // the focus or config.js
  13104. externalAuthEnabled = true;
  13105. }
  13106. eventEmitter.emit(
  13107. XMPPEvents.AUTHENTICATION_REQUIRED,
  13108. function () {
  13109. Moderator.allocateConferenceFocus(
  13110. roomName, callback);
  13111. });
  13112. return;
  13113. }
  13114. var waitMs = getNextErrorTimeout();
  13115. console.error("Focus error, retry after " + waitMs, error);
  13116. // Show message
  13117. var focusComponent = Moderator.getFocusComponent();
  13118. var retrySec = waitMs / 1000;
  13119. // FIXME: message is duplicated ?
  13120. // Do not show in case of session invalid
  13121. // which means just a retry
  13122. if (!invalidSession) {
  13123. APP.UI.messageHandler.notify(
  13124. null, "notify.focus",
  13125. 'disconnected', "notify.focusFail",
  13126. {component: focusComponent, ms: retrySec});
  13127. }
  13128. // Reset response timeout
  13129. getNextTimeout(true);
  13130. window.setTimeout(
  13131. function () {
  13132. Moderator.allocateConferenceFocus(roomName, callback);
  13133. }, waitMs);
  13134. }
  13135. );
  13136. },
  13137. getLoginUrl: function (roomName, urlCallback) {
  13138. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13139. iq.c('login-url', {
  13140. xmlns: 'http://jitsi.org/protocol/focus',
  13141. room: roomName,
  13142. 'machine-uid': Settings.getSettings().uid
  13143. });
  13144. connection.sendIQ(
  13145. iq,
  13146. function (result) {
  13147. var url = $(result).find('login-url').attr('url');
  13148. url = url = decodeURIComponent(url);
  13149. if (url) {
  13150. console.info("Got auth url: " + url);
  13151. urlCallback(url);
  13152. } else {
  13153. console.error(
  13154. "Failed to get auth url from the focus", result);
  13155. }
  13156. },
  13157. function (error) {
  13158. console.error("Get auth url error", error);
  13159. }
  13160. );
  13161. },
  13162. getPopupLoginUrl: function (roomName, urlCallback) {
  13163. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13164. iq.c('login-url', {
  13165. xmlns: 'http://jitsi.org/protocol/focus',
  13166. room: roomName,
  13167. 'machine-uid': Settings.getSettings().uid,
  13168. popup: true
  13169. });
  13170. connection.sendIQ(
  13171. iq,
  13172. function (result) {
  13173. var url = $(result).find('login-url').attr('url');
  13174. url = url = decodeURIComponent(url);
  13175. if (url) {
  13176. console.info("Got POPUP auth url: " + url);
  13177. urlCallback(url);
  13178. } else {
  13179. console.error(
  13180. "Failed to get POPUP auth url from the focus", result);
  13181. }
  13182. },
  13183. function (error) {
  13184. console.error('Get POPUP auth url error', error);
  13185. }
  13186. );
  13187. },
  13188. logout: function (callback) {
  13189. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13190. var sessionId = localStorage.getItem('sessionId');
  13191. if (!sessionId) {
  13192. callback();
  13193. return;
  13194. }
  13195. iq.c('logout', {
  13196. xmlns: 'http://jitsi.org/protocol/focus',
  13197. 'session-id': sessionId
  13198. });
  13199. connection.sendIQ(
  13200. iq,
  13201. function (result) {
  13202. var logoutUrl = $(result).find('logout').attr('logout-url');
  13203. if (logoutUrl) {
  13204. logoutUrl = decodeURIComponent(logoutUrl);
  13205. }
  13206. console.info("Log out OK, url: " + logoutUrl, result);
  13207. localStorage.removeItem('sessionId');
  13208. callback(logoutUrl);
  13209. },
  13210. function (error) {
  13211. console.error("Logout error", error);
  13212. }
  13213. );
  13214. }
  13215. };
  13216. module.exports = Moderator;
  13217. },{"../../service/authentication/AuthenticationEvents":104,"../../service/xmpp/XMPPEvents":109,"../settings/Settings":47}],59:[function(require,module,exports){
  13218. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13219. Toolbar, Util */
  13220. var Moderator = require("./moderator");
  13221. var recordingToken = null;
  13222. var recordingEnabled;
  13223. /**
  13224. * Whether to use a jirecon component for recording, or use the videobridge
  13225. * through COLIBRI.
  13226. */
  13227. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13228. /**
  13229. * The ID of the jirecon recording session. Jirecon generates it when we
  13230. * initially start recording, and it needs to be used in subsequent requests
  13231. * to jirecon.
  13232. */
  13233. var jireconRid = null;
  13234. function setRecordingToken(token) {
  13235. recordingToken = token;
  13236. }
  13237. function setRecording(state, token, callback, connection) {
  13238. if (useJirecon){
  13239. setRecordingJirecon(state, token, callback, connection);
  13240. } else {
  13241. setRecordingColibri(state, token, callback, connection);
  13242. }
  13243. }
  13244. function setRecordingJirecon(state, token, callback, connection) {
  13245. if (state == recordingEnabled){
  13246. return;
  13247. }
  13248. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13249. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13250. action: state ? 'start' : 'stop',
  13251. mucjid: connection.emuc.roomjid});
  13252. if (!state){
  13253. iq.attrs({rid: jireconRid});
  13254. }
  13255. console.log('Start recording');
  13256. connection.sendIQ(
  13257. iq,
  13258. function (result) {
  13259. // TODO wait for an IQ with the real status, since this is
  13260. // provisional?
  13261. jireconRid = $(result).find('recording').attr('rid');
  13262. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13263. '(jirecon)' + result);
  13264. recordingEnabled = state;
  13265. if (!state){
  13266. jireconRid = null;
  13267. }
  13268. callback(state);
  13269. },
  13270. function (error) {
  13271. console.log('Failed to start recording, error: ', error);
  13272. callback(recordingEnabled);
  13273. });
  13274. }
  13275. // Sends a COLIBRI message which enables or disables (according to 'state')
  13276. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13277. // with the new recording state, according to the IQ.
  13278. function setRecordingColibri(state, token, callback, connection) {
  13279. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13280. elem.c('conference', {
  13281. xmlns: 'http://jitsi.org/protocol/colibri'
  13282. });
  13283. elem.c('recording', {state: state, token: token});
  13284. connection.sendIQ(elem,
  13285. function (result) {
  13286. console.log('Set recording "', state, '". Result:', result);
  13287. var recordingElem = $(result).find('>conference>recording');
  13288. var newState = ('true' === recordingElem.attr('state'));
  13289. recordingEnabled = newState;
  13290. callback(newState);
  13291. },
  13292. function (error) {
  13293. console.warn(error);
  13294. callback(recordingEnabled);
  13295. }
  13296. );
  13297. }
  13298. var Recording = {
  13299. toggleRecording: function (tokenEmptyCallback,
  13300. startingCallback, startedCallback, connection) {
  13301. if (!Moderator.isModerator()) {
  13302. console.log(
  13303. 'non-focus, or conference not yet organized:' +
  13304. ' not enabling recording');
  13305. return;
  13306. }
  13307. var self = this;
  13308. // Jirecon does not (currently) support a token.
  13309. if (!recordingToken && !useJirecon) {
  13310. tokenEmptyCallback(function (value) {
  13311. setRecordingToken(value);
  13312. self.toggleRecording(tokenEmptyCallback,
  13313. startingCallback, startedCallback, connection);
  13314. });
  13315. return;
  13316. }
  13317. var oldState = recordingEnabled;
  13318. startingCallback(!oldState);
  13319. setRecording(!oldState,
  13320. recordingToken,
  13321. function (state) {
  13322. console.log("New recording state: ", state);
  13323. if (state === oldState) {
  13324. // FIXME: new focus:
  13325. // this will not work when moderator changes
  13326. // during active session. Then it will assume that
  13327. // recording status has changed to true, but it might have
  13328. // been already true(and we only received actual status from
  13329. // the focus).
  13330. //
  13331. // SO we start with status null, so that it is initialized
  13332. // here and will fail only after second click, so if invalid
  13333. // token was used we have to press the button twice before
  13334. // current status will be fetched and token will be reset.
  13335. //
  13336. // Reliable way would be to return authentication error.
  13337. // Or status update when moderator connects.
  13338. // Or we have to stop recording session when current
  13339. // moderator leaves the room.
  13340. // Failed to change, reset the token because it might
  13341. // have been wrong
  13342. setRecordingToken(null);
  13343. }
  13344. startedCallback(state);
  13345. },
  13346. connection
  13347. );
  13348. }
  13349. }
  13350. module.exports = Recording;
  13351. },{"./moderator":58}],60:[function(require,module,exports){
  13352. /* jshint -W117 */
  13353. /* a simple MUC connection plugin
  13354. * can only handle a single MUC room
  13355. */
  13356. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13357. var Moderator = require("./moderator");
  13358. var JingleSession = require("./JingleSession");
  13359. var bridgeIsDown = false;
  13360. module.exports = function(XMPP, eventEmitter) {
  13361. Strophe.addConnectionPlugin('emuc', {
  13362. connection: null,
  13363. roomjid: null,
  13364. myroomjid: null,
  13365. members: {},
  13366. list_members: [], // so we can elect a new focus
  13367. presMap: {},
  13368. preziMap: {},
  13369. joined: false,
  13370. isOwner: false,
  13371. role: null,
  13372. focusMucJid: null,
  13373. ssrc2jid: {},
  13374. init: function (conn) {
  13375. this.connection = conn;
  13376. },
  13377. initPresenceMap: function (myroomjid) {
  13378. this.presMap['to'] = myroomjid;
  13379. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13380. if(APP.RTC.localAudio.isMuted())
  13381. {
  13382. this.addAudioInfoToPresence(true);
  13383. }
  13384. if(APP.RTC.localVideo.isMuted())
  13385. {
  13386. this.addVideoInfoToPresence(true);
  13387. }
  13388. },
  13389. doJoin: function (jid, password) {
  13390. this.myroomjid = jid;
  13391. console.info("Joined MUC as " + this.myroomjid);
  13392. this.initPresenceMap(this.myroomjid);
  13393. if (!this.roomjid) {
  13394. this.roomjid = Strophe.getBareJidFromJid(jid);
  13395. // add handlers (just once)
  13396. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13397. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13398. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13399. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13400. }
  13401. if (password !== undefined) {
  13402. this.presMap['password'] = password;
  13403. }
  13404. this.sendPresence();
  13405. },
  13406. doLeave: function () {
  13407. console.log("do leave", this.myroomjid);
  13408. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13409. this.presMap.length = 0;
  13410. this.connection.send(pres);
  13411. },
  13412. createNonAnonymousRoom: function () {
  13413. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13414. var getForm = $iq({type: 'get', to: this.roomjid})
  13415. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13416. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13417. var self = this;
  13418. this.connection.sendIQ(getForm, function (form) {
  13419. if (!$(form).find(
  13420. '>query>x[xmlns="jabber:x:data"]' +
  13421. '>field[var="muc#roomconfig_whois"]').length) {
  13422. console.error('non-anonymous rooms not supported');
  13423. return;
  13424. }
  13425. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13426. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13427. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13428. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13429. .c('value')
  13430. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13431. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13432. .c('value').t('anyone').up().up();
  13433. self.connection.sendIQ(formSubmit);
  13434. }, function (error) {
  13435. console.error("Error getting room configuration form");
  13436. });
  13437. },
  13438. onPresence: function (pres) {
  13439. var from = pres.getAttribute('from');
  13440. // What is this for? A workaround for something?
  13441. if (pres.getAttribute('type')) {
  13442. return true;
  13443. }
  13444. // Parse etherpad tag.
  13445. var etherpad = $(pres).find('>etherpad');
  13446. if (etherpad.length) {
  13447. if (config.etherpad_base) {
  13448. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13449. }
  13450. }
  13451. // Parse prezi tag.
  13452. var presentation = $(pres).find('>prezi');
  13453. if (presentation.length) {
  13454. var url = presentation.attr('url');
  13455. var current = presentation.find('>current').text();
  13456. console.log('presentation info received from', from, url);
  13457. if (this.preziMap[from] == null) {
  13458. this.preziMap[from] = url;
  13459. $(document).trigger('presentationadded.muc', [from, url, current]);
  13460. }
  13461. else {
  13462. $(document).trigger('gotoslide.muc', [from, url, current]);
  13463. }
  13464. }
  13465. else if (this.preziMap[from] != null) {
  13466. var url = this.preziMap[from];
  13467. delete this.preziMap[from];
  13468. $(document).trigger('presentationremoved.muc', [from, url]);
  13469. }
  13470. // Parse audio info tag.
  13471. var audioMuted = $(pres).find('>audiomuted');
  13472. if (audioMuted.length) {
  13473. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  13474. from, (audioMuted.text() === "true"));
  13475. }
  13476. // Parse video info tag.
  13477. var videoMuted = $(pres).find('>videomuted');
  13478. if (videoMuted.length) {
  13479. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  13480. from, (videoMuted.text() === "true"));
  13481. }
  13482. var startMuted = $(pres).find('>startmuted');
  13483. if (startMuted.length)
  13484. {
  13485. eventEmitter.emit(XMPPEvents.START_MUTED,
  13486. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  13487. }
  13488. var devices = $(pres).find('>devices');
  13489. if(devices.length)
  13490. {
  13491. var audio = devices.find('>audio');
  13492. var video = devices.find('>video');
  13493. var devicesValues = {audio: false, video: false};
  13494. if(audio.length && audio.text() === "true")
  13495. {
  13496. devicesValues.audio = true;
  13497. }
  13498. if(video.length && video.text() === "true")
  13499. {
  13500. devicesValues.video = true;
  13501. }
  13502. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  13503. Strophe.getResourceFromJid(from), devicesValues);
  13504. }
  13505. var stats = $(pres).find('>stats');
  13506. if (stats.length) {
  13507. var statsObj = {};
  13508. Strophe.forEachChild(stats[0], "stat", function (el) {
  13509. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13510. });
  13511. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13512. }
  13513. // Parse status.
  13514. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13515. this.isOwner = true;
  13516. this.createNonAnonymousRoom();
  13517. }
  13518. // Parse roles.
  13519. var member = {};
  13520. member.show = $(pres).find('>show').text();
  13521. member.status = $(pres).find('>status').text();
  13522. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13523. member.affiliation = tmp.attr('affiliation');
  13524. member.role = tmp.attr('role');
  13525. // Focus recognition
  13526. member.jid = tmp.attr('jid');
  13527. member.isFocus = false;
  13528. if (member.jid
  13529. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13530. member.isFocus = true;
  13531. }
  13532. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13533. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13534. if (from == this.myroomjid) {
  13535. if (member.affiliation == 'owner') this.isOwner = true;
  13536. if (this.role !== member.role) {
  13537. this.role = member.role;
  13538. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  13539. from, member, pres, Moderator.isModerator());
  13540. }
  13541. if (!this.joined) {
  13542. this.joined = true;
  13543. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13544. this.list_members.push(from);
  13545. }
  13546. } else if (this.members[from] === undefined) {
  13547. // new participant
  13548. this.members[from] = member;
  13549. this.list_members.push(from);
  13550. console.log('entered', from, member);
  13551. if (member.isFocus) {
  13552. this.focusMucJid = from;
  13553. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13554. }
  13555. else {
  13556. var id = $(pres).find('>userId').text();
  13557. var email = $(pres).find('>email');
  13558. if (email.length > 0) {
  13559. id = email.text();
  13560. }
  13561. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  13562. }
  13563. } else {
  13564. // Presence update for existing participant
  13565. // Watch role change:
  13566. if (this.members[from].role != member.role) {
  13567. this.members[from].role = member.role;
  13568. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13569. member.role, member.displayName);
  13570. }
  13571. }
  13572. // Always trigger presence to update bindings
  13573. this.parsePresence(from, member, pres);
  13574. // Trigger status message update
  13575. if (member.status) {
  13576. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13577. }
  13578. return true;
  13579. },
  13580. onPresenceUnavailable: function (pres) {
  13581. var from = pres.getAttribute('from');
  13582. // room destroyed ?
  13583. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13584. '>destroy').length) {
  13585. var reason;
  13586. var reasonSelect = $(pres).find(
  13587. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13588. '>destroy>reason');
  13589. if (reasonSelect.length) {
  13590. reason = reasonSelect.text();
  13591. }
  13592. XMPP.disposeConference(false);
  13593. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13594. return true;
  13595. }
  13596. var self = this;
  13597. // Remove old ssrcs coming from the jid
  13598. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13599. if (self.ssrc2jid[ssrc] == from) {
  13600. delete self.ssrc2jid[ssrc];
  13601. }
  13602. });
  13603. // Status code 110 indicates that this notification is "self-presence".
  13604. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13605. delete this.members[from];
  13606. this.list_members.splice(this.list_members.indexOf(from), 1);
  13607. this.onParticipantLeft(from);
  13608. }
  13609. // If the status code is 110 this means we're leaving and we would like
  13610. // to remove everyone else from our view, so we trigger the event.
  13611. else if (this.list_members.length > 1) {
  13612. for (var i = 0; i < this.list_members.length; i++) {
  13613. var member = this.list_members[i];
  13614. delete this.members[i];
  13615. this.list_members.splice(i, 1);
  13616. this.onParticipantLeft(member);
  13617. }
  13618. }
  13619. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13620. $(document).trigger('kicked.muc', [from]);
  13621. if (this.myroomjid === from) {
  13622. XMPP.disposeConference(false);
  13623. eventEmitter.emit(XMPPEvents.KICKED);
  13624. }
  13625. }
  13626. return true;
  13627. },
  13628. onPresenceError: function (pres) {
  13629. var from = pres.getAttribute('from');
  13630. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13631. console.log('on password required', from);
  13632. var self = this;
  13633. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13634. self.doJoin(from, value);
  13635. });
  13636. } else if ($(pres).find(
  13637. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13638. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13639. if (toDomain === config.hosts.anonymousdomain) {
  13640. // enter the room by replying with 'not-authorized'. This would
  13641. // result in reconnection from authorized domain.
  13642. // We're either missing Jicofo/Prosody config for anonymous
  13643. // domains or something is wrong.
  13644. // XMPP.promptLogin();
  13645. APP.UI.messageHandler.openReportDialog(null,
  13646. "dialog.joinError", pres);
  13647. } else {
  13648. console.warn('onPresError ', pres);
  13649. APP.UI.messageHandler.openReportDialog(null,
  13650. "dialog.connectError",
  13651. pres);
  13652. }
  13653. } else {
  13654. console.warn('onPresError ', pres);
  13655. APP.UI.messageHandler.openReportDialog(null,
  13656. "dialog.connectError",
  13657. pres);
  13658. }
  13659. return true;
  13660. },
  13661. sendMessage: function (body, nickname) {
  13662. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13663. msg.c('body', body).up();
  13664. if (nickname) {
  13665. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13666. }
  13667. this.connection.send(msg);
  13668. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13669. },
  13670. setSubject: function (subject) {
  13671. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13672. msg.c('subject', subject);
  13673. this.connection.send(msg);
  13674. console.log("topic changed to " + subject);
  13675. },
  13676. onMessage: function (msg) {
  13677. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13678. var from = msg.getAttribute('from');
  13679. var nick =
  13680. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13681. .text() ||
  13682. Strophe.getResourceFromJid(from);
  13683. var txt = $(msg).find('>body').text();
  13684. var type = msg.getAttribute("type");
  13685. if (type == "error") {
  13686. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13687. $(msg).find('>text').text(), txt);
  13688. return true;
  13689. }
  13690. var subject = $(msg).find('>subject');
  13691. if (subject.length) {
  13692. var subjectText = subject.text();
  13693. if (subjectText || subjectText == "") {
  13694. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13695. console.log("Subject is changed to " + subjectText);
  13696. }
  13697. }
  13698. // xep-0203 delay
  13699. var stamp = $(msg).find('>delay').attr('stamp');
  13700. if (!stamp) {
  13701. // or xep-0091 delay, UTC timestamp
  13702. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  13703. if (stamp) {
  13704. // the format is CCYYMMDDThh:mm:ss
  13705. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  13706. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  13707. }
  13708. }
  13709. if (txt) {
  13710. console.log('chat', nick, txt);
  13711. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13712. from, nick, txt, this.myroomjid, stamp);
  13713. }
  13714. return true;
  13715. },
  13716. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13717. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13718. var ob = this;
  13719. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13720. function (res) {
  13721. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13722. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13723. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13724. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13725. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13726. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13727. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13728. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13729. ob.connection.sendIQ(formsubmit,
  13730. onSuccess,
  13731. onError);
  13732. } else {
  13733. onNotSupported();
  13734. }
  13735. }, onError);
  13736. },
  13737. kick: function (jid) {
  13738. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13739. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13740. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13741. .c('reason').t('You have been kicked.').up().up().up();
  13742. this.connection.sendIQ(
  13743. kickIQ,
  13744. function (result) {
  13745. console.log('Kick participant with jid: ', jid, result);
  13746. },
  13747. function (error) {
  13748. console.log('Kick participant error: ', error);
  13749. });
  13750. },
  13751. sendPresence: function () {
  13752. if (!this.presMap['to']) {
  13753. // Too early to send presence - not initialized
  13754. return;
  13755. }
  13756. var pres = $pres({to: this.presMap['to'] });
  13757. pres.c('x', {xmlns: this.presMap['xns']});
  13758. if (this.presMap['password']) {
  13759. pres.c('password').t(this.presMap['password']).up();
  13760. }
  13761. pres.up();
  13762. // Send XEP-0115 'c' stanza that contains our capabilities info
  13763. if (this.connection.caps) {
  13764. this.connection.caps.node = config.clientNode;
  13765. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13766. }
  13767. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13768. .t(navigator.userAgent).up();
  13769. if (this.presMap['bridgeIsDown']) {
  13770. pres.c('bridgeIsDown').up();
  13771. }
  13772. if (this.presMap['email']) {
  13773. pres.c('email').t(this.presMap['email']).up();
  13774. }
  13775. if (this.presMap['userId']) {
  13776. pres.c('userId').t(this.presMap['userId']).up();
  13777. }
  13778. if (this.presMap['displayName']) {
  13779. // XEP-0172
  13780. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13781. .t(this.presMap['displayName']).up();
  13782. }
  13783. if(this.presMap["devices"])
  13784. {
  13785. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  13786. .c('video').t(this.presMap['devices'].video).up().up();
  13787. }
  13788. if (this.presMap['audions']) {
  13789. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13790. .t(this.presMap['audiomuted']).up();
  13791. }
  13792. if (this.presMap['videons']) {
  13793. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13794. .t(this.presMap['videomuted']).up();
  13795. }
  13796. if (this.presMap['statsns']) {
  13797. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13798. for (var stat in this.presMap["stats"])
  13799. if (this.presMap["stats"][stat] != null)
  13800. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13801. pres.up();
  13802. }
  13803. if (this.presMap['prezins']) {
  13804. pres.c('prezi',
  13805. {xmlns: this.presMap['prezins'],
  13806. 'url': this.presMap['preziurl']})
  13807. .c('current').t(this.presMap['prezicurrent']).up().up();
  13808. }
  13809. if (this.presMap['medians']) {
  13810. pres.c('media', {xmlns: this.presMap['medians']});
  13811. var sourceNumber = 0;
  13812. Object.keys(this.presMap).forEach(function (key) {
  13813. if (key.indexOf('source') >= 0) {
  13814. sourceNumber++;
  13815. }
  13816. });
  13817. if (sourceNumber > 0)
  13818. for (var i = 1; i <= sourceNumber / 3; i++) {
  13819. pres.c('source',
  13820. {type: this.presMap['source' + i + '_type'],
  13821. ssrc: this.presMap['source' + i + '_ssrc'],
  13822. direction: this.presMap['source' + i + '_direction']
  13823. || 'sendrecv' }
  13824. ).up();
  13825. }
  13826. pres.up();
  13827. }
  13828. if(this.presMap["startMuted"] !== undefined)
  13829. {
  13830. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  13831. video: this.presMap["startMuted"].video,
  13832. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  13833. delete this.presMap["startMuted"];
  13834. }
  13835. pres.up();
  13836. this.connection.send(pres);
  13837. },
  13838. addDisplayNameToPresence: function (displayName) {
  13839. this.presMap['displayName'] = displayName;
  13840. },
  13841. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13842. if (!this.presMap['medians'])
  13843. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13844. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13845. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13846. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13847. },
  13848. addDevicesToPresence: function (devices) {
  13849. this.presMap['devices'] = devices;
  13850. },
  13851. clearPresenceMedia: function () {
  13852. var self = this;
  13853. Object.keys(this.presMap).forEach(function (key) {
  13854. if (key.indexOf('source') != -1) {
  13855. delete self.presMap[key];
  13856. }
  13857. });
  13858. },
  13859. addPreziToPresence: function (url, currentSlide) {
  13860. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13861. this.presMap['preziurl'] = url;
  13862. this.presMap['prezicurrent'] = currentSlide;
  13863. },
  13864. removePreziFromPresence: function () {
  13865. delete this.presMap['prezins'];
  13866. delete this.presMap['preziurl'];
  13867. delete this.presMap['prezicurrent'];
  13868. },
  13869. addCurrentSlideToPresence: function (currentSlide) {
  13870. this.presMap['prezicurrent'] = currentSlide;
  13871. },
  13872. getPrezi: function (roomjid) {
  13873. return this.preziMap[roomjid];
  13874. },
  13875. addAudioInfoToPresence: function (isMuted) {
  13876. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13877. this.presMap['audiomuted'] = isMuted.toString();
  13878. },
  13879. addVideoInfoToPresence: function (isMuted) {
  13880. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13881. this.presMap['videomuted'] = isMuted.toString();
  13882. },
  13883. addConnectionInfoToPresence: function (stats) {
  13884. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13885. this.presMap['stats'] = stats;
  13886. },
  13887. findJidFromResource: function (resourceJid) {
  13888. if (resourceJid &&
  13889. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13890. return this.myroomjid;
  13891. }
  13892. var peerJid = null;
  13893. Object.keys(this.members).some(function (jid) {
  13894. peerJid = jid;
  13895. return Strophe.getResourceFromJid(jid) === resourceJid;
  13896. });
  13897. return peerJid;
  13898. },
  13899. addBridgeIsDownToPresence: function () {
  13900. this.presMap['bridgeIsDown'] = true;
  13901. },
  13902. addEmailToPresence: function (email) {
  13903. this.presMap['email'] = email;
  13904. },
  13905. addUserIdToPresence: function (userId) {
  13906. this.presMap['userId'] = userId;
  13907. },
  13908. addStartMutedToPresence: function (audio, video) {
  13909. this.presMap["startMuted"] = {audio: audio, video: video};
  13910. },
  13911. isModerator: function () {
  13912. return this.role === 'moderator';
  13913. },
  13914. getMemberRole: function (peerJid) {
  13915. if (this.members[peerJid]) {
  13916. return this.members[peerJid].role;
  13917. }
  13918. return null;
  13919. },
  13920. onParticipantLeft: function (jid) {
  13921. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  13922. this.connection.jingle.terminateByJid(jid);
  13923. if (this.getPrezi(jid)) {
  13924. $(document).trigger('presentationremoved.muc',
  13925. [jid, this.getPrezi(jid)]);
  13926. }
  13927. Moderator.onMucMemberLeft(jid);
  13928. },
  13929. parsePresence: function (from, memeber, pres) {
  13930. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13931. bridgeIsDown = true;
  13932. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13933. }
  13934. if(memeber.isFocus)
  13935. return;
  13936. var self = this;
  13937. // Remove old ssrcs coming from the jid
  13938. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13939. if (self.ssrc2jid[ssrc] == from) {
  13940. delete self.ssrc2jid[ssrc];
  13941. }
  13942. });
  13943. var changedStreams = [];
  13944. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13945. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13946. var ssrcV = ssrc.getAttribute('ssrc');
  13947. self.ssrc2jid[ssrcV] = from;
  13948. var type = ssrc.getAttribute('type');
  13949. var direction = ssrc.getAttribute('direction');
  13950. changedStreams.push({type: type, direction: direction});
  13951. });
  13952. eventEmitter.emit(XMPPEvents.STREAMS_CHANGED, from, changedStreams);
  13953. var displayName = !config.displayJids
  13954. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13955. if (displayName && displayName.length > 0)
  13956. {
  13957. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13958. }
  13959. var id = $(pres).find('>userID').text();
  13960. var email = $(pres).find('>email');
  13961. if(email.length > 0) {
  13962. id = email.text();
  13963. }
  13964. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13965. }
  13966. });
  13967. };
  13968. },{"../../service/xmpp/XMPPEvents":109,"./JingleSession":53,"./moderator":58}],61:[function(require,module,exports){
  13969. /* jshint -W117 */
  13970. var JingleSession = require("./JingleSession");
  13971. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13972. module.exports = function(XMPP, eventEmitter)
  13973. {
  13974. function CallIncomingJingle(sid, connection) {
  13975. var sess = connection.jingle.sessions[sid];
  13976. // TODO: do we check activecall == null?
  13977. connection.jingle.activecall = sess;
  13978. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13979. // TODO: check affiliation and/or role
  13980. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13981. sess.usedrip = true; // not-so-naive trickle ice
  13982. sess.sendAnswer();
  13983. sess.accept();
  13984. };
  13985. Strophe.addConnectionPlugin('jingle', {
  13986. connection: null,
  13987. sessions: {},
  13988. jid2session: {},
  13989. ice_config: {iceServers: []},
  13990. pc_constraints: {},
  13991. activecall: null,
  13992. media_constraints: {
  13993. mandatory: {
  13994. 'OfferToReceiveAudio': true,
  13995. 'OfferToReceiveVideo': true
  13996. }
  13997. // MozDontOfferDataChannel: true when this is firefox
  13998. },
  13999. init: function (conn) {
  14000. this.connection = conn;
  14001. if (this.connection.disco) {
  14002. // http://xmpp.org/extensions/xep-0167.html#support
  14003. // http://xmpp.org/extensions/xep-0176.html#support
  14004. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14005. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14006. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14007. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  14008. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14009. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14010. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14011. // this is dealt with by SDP O/A so we don't need to annouce this
  14012. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14013. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14014. if (config.useRtcpMux) {
  14015. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14016. }
  14017. if (config.useBundle) {
  14018. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14019. }
  14020. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14021. }
  14022. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14023. },
  14024. onJingle: function (iq) {
  14025. var sid = $(iq).find('jingle').attr('sid');
  14026. var action = $(iq).find('jingle').attr('action');
  14027. var fromJid = iq.getAttribute('from');
  14028. // send ack first
  14029. var ack = $iq({type: 'result',
  14030. to: fromJid,
  14031. id: iq.getAttribute('id')
  14032. });
  14033. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14034. var sess = this.sessions[sid];
  14035. if ('session-initiate' != action) {
  14036. if (sess === null) {
  14037. ack.type = 'error';
  14038. ack.c('error', {type: 'cancel'})
  14039. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14040. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14041. this.connection.send(ack);
  14042. return true;
  14043. }
  14044. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14045. // local jid is not checked
  14046. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14047. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14048. ack.type = 'error';
  14049. ack.c('error', {type: 'cancel'})
  14050. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14051. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14052. this.connection.send(ack);
  14053. return true;
  14054. }
  14055. } else if (sess !== undefined) {
  14056. // existing session with same session id
  14057. // this might be out-of-order if the sess.peerjid is the same as from
  14058. ack.type = 'error';
  14059. ack.c('error', {type: 'cancel'})
  14060. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14061. console.warn('duplicate session id', sid);
  14062. this.connection.send(ack);
  14063. return true;
  14064. }
  14065. // FIXME: check for a defined action
  14066. this.connection.send(ack);
  14067. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14068. switch (action) {
  14069. case 'session-initiate':
  14070. var startMuted = $(iq).find('jingle>startmuted');
  14071. if(startMuted && startMuted.length > 0)
  14072. {
  14073. var audioMuted = startMuted.attr("audio");
  14074. var videoMuted = startMuted.attr("video");
  14075. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  14076. (videoMuted === "true"));
  14077. }
  14078. sess = new JingleSession(
  14079. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14080. this.connection, XMPP, eventEmitter);
  14081. // configure session
  14082. sess.media_constraints = this.media_constraints;
  14083. sess.pc_constraints = this.pc_constraints;
  14084. sess.ice_config = this.ice_config;
  14085. sess.initiate(fromJid, false);
  14086. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14087. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14088. this.sessions[sess.sid] = sess;
  14089. this.jid2session[sess.peerjid] = sess;
  14090. // the callback should either
  14091. // .sendAnswer and .accept
  14092. // or .sendTerminate -- not necessarily synchronus
  14093. CallIncomingJingle(sess.sid, this.connection);
  14094. break;
  14095. case 'session-accept':
  14096. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14097. sess.accept();
  14098. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14099. break;
  14100. case 'session-terminate':
  14101. // If this is not the focus sending the terminate, we have
  14102. // nothing more to do here.
  14103. if (Object.keys(this.sessions).length < 1
  14104. || !(this.sessions[Object.keys(this.sessions)[0]]
  14105. instanceof JingleSession))
  14106. {
  14107. break;
  14108. }
  14109. console.log('terminating...', sess.sid);
  14110. sess.terminate();
  14111. this.terminate(sess.sid);
  14112. if ($(iq).find('>jingle>reason').length) {
  14113. $(document).trigger('callterminated.jingle', [
  14114. sess.sid,
  14115. sess.peerjid,
  14116. $(iq).find('>jingle>reason>:first')[0].tagName,
  14117. $(iq).find('>jingle>reason>text').text()
  14118. ]);
  14119. } else {
  14120. $(document).trigger('callterminated.jingle',
  14121. [sess.sid, sess.peerjid]);
  14122. }
  14123. break;
  14124. case 'transport-info':
  14125. sess.addIceCandidate($(iq).find('>jingle>content'));
  14126. break;
  14127. case 'session-info':
  14128. var affected;
  14129. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14130. $(document).trigger('ringing.jingle', [sess.sid]);
  14131. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14132. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14133. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14134. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14135. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14136. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14137. }
  14138. break;
  14139. case 'addsource': // FIXME: proprietary, un-jingleish
  14140. case 'source-add': // FIXME: proprietary
  14141. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14142. break;
  14143. case 'removesource': // FIXME: proprietary, un-jingleish
  14144. case 'source-remove': // FIXME: proprietary
  14145. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14146. break;
  14147. default:
  14148. console.warn('jingle action not implemented', action);
  14149. break;
  14150. }
  14151. return true;
  14152. },
  14153. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14154. var sess = new JingleSession(myjid || this.connection.jid,
  14155. Math.random().toString(36).substr(2, 12), // random string
  14156. this.connection, XMPP, eventEmitter);
  14157. // configure session
  14158. sess.media_constraints = this.media_constraints;
  14159. sess.pc_constraints = this.pc_constraints;
  14160. sess.ice_config = this.ice_config;
  14161. sess.initiate(peerjid, true);
  14162. this.sessions[sess.sid] = sess;
  14163. this.jid2session[sess.peerjid] = sess;
  14164. sess.sendOffer();
  14165. return sess;
  14166. },
  14167. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14168. if (sid === null || sid === undefined) {
  14169. for (sid in this.sessions) {
  14170. if (this.sessions[sid].state != 'ended') {
  14171. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14172. this.sessions[sid].terminate();
  14173. }
  14174. delete this.jid2session[this.sessions[sid].peerjid];
  14175. delete this.sessions[sid];
  14176. }
  14177. } else if (this.sessions.hasOwnProperty(sid)) {
  14178. if (this.sessions[sid].state != 'ended') {
  14179. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14180. this.sessions[sid].terminate();
  14181. }
  14182. delete this.jid2session[this.sessions[sid].peerjid];
  14183. delete this.sessions[sid];
  14184. }
  14185. },
  14186. // Used to terminate a session when an unavailable presence is received.
  14187. terminateByJid: function (jid) {
  14188. if (this.jid2session.hasOwnProperty(jid)) {
  14189. var sess = this.jid2session[jid];
  14190. if (sess) {
  14191. sess.terminate();
  14192. console.log('peer went away silently', jid);
  14193. delete this.sessions[sess.sid];
  14194. delete this.jid2session[jid];
  14195. $(document).trigger('callterminated.jingle',
  14196. [sess.sid, jid], 'gone');
  14197. }
  14198. }
  14199. },
  14200. terminateRemoteByJid: function (jid, reason) {
  14201. if (this.jid2session.hasOwnProperty(jid)) {
  14202. var sess = this.jid2session[jid];
  14203. if (sess) {
  14204. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14205. sess.terminate();
  14206. console.log('terminate peer with jid', sess.sid, jid);
  14207. delete this.sessions[sess.sid];
  14208. delete this.jid2session[jid];
  14209. $(document).trigger('callterminated.jingle',
  14210. [sess.sid, jid, 'kicked']);
  14211. }
  14212. }
  14213. },
  14214. getStunAndTurnCredentials: function () {
  14215. // get stun and turn configuration from server via xep-0215
  14216. // uses time-limited credentials as described in
  14217. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14218. //
  14219. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14220. // for a prosody module which implements this
  14221. //
  14222. // currently, this doesn't work with updateIce and therefore credentials with a long
  14223. // validity have to be fetched before creating the peerconnection
  14224. // TODO: implement refresh via updateIce as described in
  14225. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14226. var self = this;
  14227. this.connection.sendIQ(
  14228. $iq({type: 'get', to: this.connection.domain})
  14229. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14230. function (res) {
  14231. var iceservers = [];
  14232. $(res).find('>services>service').each(function (idx, el) {
  14233. el = $(el);
  14234. var dict = {};
  14235. var type = el.attr('type');
  14236. switch (type) {
  14237. case 'stun':
  14238. dict.url = 'stun:' + el.attr('host');
  14239. if (el.attr('port')) {
  14240. dict.url += ':' + el.attr('port');
  14241. }
  14242. iceservers.push(dict);
  14243. break;
  14244. case 'turn':
  14245. case 'turns':
  14246. dict.url = type + ':';
  14247. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14248. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14249. dict.url += el.attr('username') + '@';
  14250. } else {
  14251. dict.username = el.attr('username'); // only works in M28
  14252. }
  14253. }
  14254. dict.url += el.attr('host');
  14255. if (el.attr('port') && el.attr('port') != '3478') {
  14256. dict.url += ':' + el.attr('port');
  14257. }
  14258. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14259. dict.url += '?transport=' + el.attr('transport');
  14260. }
  14261. if (el.attr('password')) {
  14262. dict.credential = el.attr('password');
  14263. }
  14264. iceservers.push(dict);
  14265. break;
  14266. }
  14267. });
  14268. self.ice_config.iceServers = iceservers;
  14269. },
  14270. function (err) {
  14271. console.warn('getting turn credentials failed', err);
  14272. console.warn('is mod_turncredentials or similar installed?');
  14273. }
  14274. );
  14275. // implement push?
  14276. },
  14277. /**
  14278. * Populates the log data
  14279. */
  14280. populateData: function () {
  14281. var data = {};
  14282. var self = this;
  14283. Object.keys(this.sessions).forEach(function (sid) {
  14284. var session = self.sessions[sid];
  14285. if (session.peerconnection && session.peerconnection.updateLog) {
  14286. // FIXME: should probably be a .dump call
  14287. data["jingle_" + session.sid] = {
  14288. updateLog: session.peerconnection.updateLog,
  14289. stats: session.peerconnection.stats,
  14290. url: window.location.href
  14291. };
  14292. }
  14293. });
  14294. return data;
  14295. }
  14296. });
  14297. };
  14298. },{"../../service/xmpp/XMPPEvents":109,"./JingleSession":53}],62:[function(require,module,exports){
  14299. /* global Strophe */
  14300. module.exports = function () {
  14301. Strophe.addConnectionPlugin('logger', {
  14302. // logs raw stanzas and makes them available for download as JSON
  14303. connection: null,
  14304. log: [],
  14305. init: function (conn) {
  14306. this.connection = conn;
  14307. this.connection.rawInput = this.log_incoming.bind(this);
  14308. this.connection.rawOutput = this.log_outgoing.bind(this);
  14309. },
  14310. log_incoming: function (stanza) {
  14311. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14312. },
  14313. log_outgoing: function (stanza) {
  14314. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14315. }
  14316. });
  14317. };
  14318. },{}],63:[function(require,module,exports){
  14319. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14320. setAudioMuted, Strophe */
  14321. /**
  14322. * Moderate connection plugin.
  14323. */
  14324. module.exports = function (XMPP) {
  14325. Strophe.addConnectionPlugin('moderate', {
  14326. connection: null,
  14327. init: function (conn) {
  14328. this.connection = conn;
  14329. this.connection.addHandler(this.onMute.bind(this),
  14330. 'http://jitsi.org/jitmeet/audio',
  14331. 'iq',
  14332. 'set',
  14333. null,
  14334. null);
  14335. },
  14336. setMute: function (jid, mute) {
  14337. console.info("set mute", mute);
  14338. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14339. .c('mute', {
  14340. xmlns: 'http://jitsi.org/jitmeet/audio',
  14341. jid: jid
  14342. })
  14343. .t(mute.toString())
  14344. .up();
  14345. this.connection.sendIQ(
  14346. iqToFocus,
  14347. function (result) {
  14348. console.log('set mute', result);
  14349. },
  14350. function (error) {
  14351. console.log('set mute error', error);
  14352. });
  14353. },
  14354. onMute: function (iq) {
  14355. var from = iq.getAttribute('from');
  14356. if (from !== this.connection.emuc.focusMucJid) {
  14357. console.warn("Ignored mute from non focus peer");
  14358. return false;
  14359. }
  14360. var mute = $(iq).find('mute');
  14361. if (mute.length) {
  14362. var doMuteAudio = mute.text() === "true";
  14363. APP.UI.setAudioMuted(doMuteAudio);
  14364. XMPP.forceMuted = doMuteAudio;
  14365. }
  14366. return true;
  14367. },
  14368. eject: function (jid) {
  14369. // We're not the focus, so can't terminate
  14370. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14371. this.connection.emuc.kick(jid);
  14372. }
  14373. });
  14374. }
  14375. },{}],64:[function(require,module,exports){
  14376. /* jshint -W117 */
  14377. module.exports = function() {
  14378. Strophe.addConnectionPlugin('rayo',
  14379. {
  14380. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14381. connection: null,
  14382. init: function (conn) {
  14383. this.connection = conn;
  14384. if (this.connection.disco) {
  14385. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14386. }
  14387. this.connection.addHandler(
  14388. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14389. },
  14390. onRayo: function (iq) {
  14391. console.info("Rayo IQ", iq);
  14392. },
  14393. dial: function (to, from, roomName, roomPass) {
  14394. var self = this;
  14395. var req = $iq(
  14396. {
  14397. type: 'set',
  14398. to: this.connection.emuc.focusMucJid
  14399. }
  14400. );
  14401. req.c('dial',
  14402. {
  14403. xmlns: this.RAYO_XMLNS,
  14404. to: to,
  14405. from: from
  14406. });
  14407. req.c('header',
  14408. {
  14409. name: 'JvbRoomName',
  14410. value: roomName
  14411. }).up();
  14412. if (roomPass !== null && roomPass.length) {
  14413. req.c('header',
  14414. {
  14415. name: 'JvbRoomPassword',
  14416. value: roomPass
  14417. }).up();
  14418. }
  14419. this.connection.sendIQ(
  14420. req,
  14421. function (result) {
  14422. console.info('Dial result ', result);
  14423. var resource = $(result).find('ref').attr('uri');
  14424. this.call_resource = resource.substr('xmpp:'.length);
  14425. console.info(
  14426. "Received call resource: " + this.call_resource);
  14427. },
  14428. function (error) {
  14429. console.info('Dial error ', error);
  14430. }
  14431. );
  14432. },
  14433. hang_up: function () {
  14434. if (!this.call_resource) {
  14435. console.warn("No call in progress");
  14436. return;
  14437. }
  14438. var self = this;
  14439. var req = $iq(
  14440. {
  14441. type: 'set',
  14442. to: this.call_resource
  14443. }
  14444. );
  14445. req.c('hangup',
  14446. {
  14447. xmlns: this.RAYO_XMLNS
  14448. });
  14449. this.connection.sendIQ(
  14450. req,
  14451. function (result) {
  14452. console.info('Hangup result ', result);
  14453. self.call_resource = null;
  14454. },
  14455. function (error) {
  14456. console.info('Hangup error ', error);
  14457. self.call_resource = null;
  14458. }
  14459. );
  14460. }
  14461. }
  14462. );
  14463. };
  14464. },{}],65:[function(require,module,exports){
  14465. /**
  14466. * Strophe logger implementation. Logs from level WARN and above.
  14467. */
  14468. module.exports = function () {
  14469. Strophe.log = function (level, msg) {
  14470. switch (level) {
  14471. case Strophe.LogLevel.WARN:
  14472. console.warn("Strophe: " + msg);
  14473. break;
  14474. case Strophe.LogLevel.ERROR:
  14475. case Strophe.LogLevel.FATAL:
  14476. console.error("Strophe: " + msg);
  14477. break;
  14478. }
  14479. };
  14480. Strophe.getStatusString = function (status) {
  14481. switch (status) {
  14482. case Strophe.Status.ERROR:
  14483. return "ERROR";
  14484. case Strophe.Status.CONNECTING:
  14485. return "CONNECTING";
  14486. case Strophe.Status.CONNFAIL:
  14487. return "CONNFAIL";
  14488. case Strophe.Status.AUTHENTICATING:
  14489. return "AUTHENTICATING";
  14490. case Strophe.Status.AUTHFAIL:
  14491. return "AUTHFAIL";
  14492. case Strophe.Status.CONNECTED:
  14493. return "CONNECTED";
  14494. case Strophe.Status.DISCONNECTED:
  14495. return "DISCONNECTED";
  14496. case Strophe.Status.DISCONNECTING:
  14497. return "DISCONNECTING";
  14498. case Strophe.Status.ATTACHED:
  14499. return "ATTACHED";
  14500. default:
  14501. return "unknown";
  14502. }
  14503. };
  14504. };
  14505. },{}],66:[function(require,module,exports){
  14506. /* global $, APP, config, Strophe*/
  14507. var Moderator = require("./moderator");
  14508. var EventEmitter = require("events");
  14509. var Recording = require("./recording");
  14510. var SDP = require("./SDP");
  14511. var Settings = require("../settings/Settings");
  14512. var Pako = require("pako");
  14513. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14514. var RTCEvents = require("../../service/RTC/RTCEvents");
  14515. var UIEvents = require("../../service/UI/UIEvents");
  14516. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14517. var retry = require('retry');
  14518. var eventEmitter = new EventEmitter();
  14519. var connection = null;
  14520. var authenticatedUser = false;
  14521. function connect(jid, password) {
  14522. var faultTolerantConnect = retry.operation({
  14523. retries: 3
  14524. });
  14525. // fault tolerant connect
  14526. faultTolerantConnect.attempt(function () {
  14527. connection = XMPP.createConnection();
  14528. Moderator.setConnection(connection);
  14529. if (connection.disco) {
  14530. // for chrome, add multistream cap
  14531. }
  14532. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14533. if (config.useIPv6) {
  14534. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14535. if (!connection.jingle.pc_constraints.optional)
  14536. connection.jingle.pc_constraints.optional = [];
  14537. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14538. }
  14539. // Include user info in MUC presence
  14540. var settings = Settings.getSettings();
  14541. if (settings.email) {
  14542. connection.emuc.addEmailToPresence(settings.email);
  14543. }
  14544. if (settings.uid) {
  14545. connection.emuc.addUserIdToPresence(settings.uid);
  14546. }
  14547. if (settings.displayName) {
  14548. connection.emuc.addDisplayNameToPresence(settings.displayName);
  14549. }
  14550. // connection.connect() starts the connection process.
  14551. //
  14552. // As the connection process proceeds, the user supplied callback will
  14553. // be triggered multiple times with status updates. The callback should
  14554. // take two arguments - the status code and the error condition.
  14555. //
  14556. // The status code will be one of the values in the Strophe.Status
  14557. // constants. The error condition will be one of the conditions defined
  14558. // in RFC 3920 or the condition ‘strophe-parsererror’.
  14559. //
  14560. // The Parameters wait, hold and route are optional and only relevant
  14561. // for BOSH connections. Please see XEP 124 for a more detailed
  14562. // explanation of the optional parameters.
  14563. //
  14564. // Connection status constants for use by the connection handler
  14565. // callback.
  14566. //
  14567. // Status.ERROR - An error has occurred (websockets specific)
  14568. // Status.CONNECTING - The connection is currently being made
  14569. // Status.CONNFAIL - The connection attempt failed
  14570. // Status.AUTHENTICATING - The connection is authenticating
  14571. // Status.AUTHFAIL - The authentication attempt failed
  14572. // Status.CONNECTED - The connection has succeeded
  14573. // Status.DISCONNECTED - The connection has been terminated
  14574. // Status.DISCONNECTING - The connection is currently being terminated
  14575. // Status.ATTACHED - The connection has been attached
  14576. var anonymousConnectionFailed = false;
  14577. var connectionFailed = false;
  14578. var lastErrorMsg;
  14579. connection.connect(jid, password, function (status, msg) {
  14580. console.log('Strophe status changed to',
  14581. Strophe.getStatusString(status), msg);
  14582. if (status === Strophe.Status.CONNECTED) {
  14583. if (config.useStunTurn) {
  14584. connection.jingle.getStunAndTurnCredentials();
  14585. }
  14586. console.info("My Jabber ID: " + connection.jid);
  14587. if (password)
  14588. authenticatedUser = true;
  14589. maybeDoJoin();
  14590. } else if (status === Strophe.Status.CONNFAIL) {
  14591. if (msg === 'x-strophe-bad-non-anon-jid') {
  14592. anonymousConnectionFailed = true;
  14593. } else {
  14594. connectionFailed = true;
  14595. }
  14596. lastErrorMsg = msg;
  14597. } else if (status === Strophe.Status.DISCONNECTED) {
  14598. if (anonymousConnectionFailed) {
  14599. // prompt user for username and password
  14600. XMPP.promptLogin();
  14601. } else {
  14602. // Strophe already has built-in HTTP/BOSH error handling and
  14603. // request retry logic. Requests are resent automatically
  14604. // until their error count reaches 5. Strophe.js disconnects
  14605. // if the error count is > 5. We are not replicating this
  14606. // here.
  14607. //
  14608. // The "problem" is that failed HTTP/BOSH requests don't
  14609. // trigger a callback with a status update, so when a
  14610. // callback with status Strophe.Status.DISCONNECTED arrives,
  14611. // we can't be sure if it's a graceful disconnect or if it's
  14612. // triggered by some HTTP/BOSH error.
  14613. //
  14614. // But that's a minor issue in Jitsi Meet as we never
  14615. // disconnect anyway, not even when the user closes the
  14616. // browser window (which is kind of wrong, but the point is
  14617. // that we should never ever get disconnected).
  14618. //
  14619. // On the other hand, failed connections due to XMPP layer
  14620. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  14621. //
  14622. // Here we implement retry logic for failed connections due
  14623. // to XMPP layer errors and we display an error to the user
  14624. // if we get disconnected from the XMPP server permanently.
  14625. // If the connection failed, retry.
  14626. if (connectionFailed
  14627. && faultTolerantConnect.retry("connection-failed")) {
  14628. return;
  14629. }
  14630. // If we failed to connect to the XMPP server, fire an event
  14631. // to let all the interested module now about it.
  14632. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  14633. msg ? msg : lastErrorMsg);
  14634. }
  14635. } else if (status === Strophe.Status.AUTHFAIL) {
  14636. // wrong password or username, prompt user
  14637. XMPP.promptLogin();
  14638. }
  14639. });
  14640. });
  14641. }
  14642. function maybeDoJoin() {
  14643. if (connection && connection.connected &&
  14644. Strophe.getResourceFromJid(connection.jid)
  14645. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14646. // .connected is true while connecting?
  14647. doJoin();
  14648. }
  14649. }
  14650. function doJoin() {
  14651. var roomName = APP.UI.generateRoomName();
  14652. Moderator.allocateConferenceFocus(
  14653. roomName, APP.UI.checkForNicknameAndJoin);
  14654. }
  14655. function initStrophePlugins()
  14656. {
  14657. require("./strophe.emuc")(XMPP, eventEmitter);
  14658. require("./strophe.jingle")(XMPP, eventEmitter);
  14659. require("./strophe.moderate")(XMPP);
  14660. require("./strophe.util")();
  14661. require("./strophe.rayo")();
  14662. require("./strophe.logger")();
  14663. }
  14664. function registerListeners() {
  14665. APP.RTC.addStreamListener(maybeDoJoin,
  14666. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14667. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  14668. XMPP.addToPresence("devices", devices);
  14669. })
  14670. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14671. XMPP.addToPresence("displayName", nickname);
  14672. });
  14673. }
  14674. var unload = (function () {
  14675. var unloaded = false;
  14676. return function () {
  14677. if (unloaded) { return; }
  14678. unloaded = true;
  14679. if (connection && connection.connected) {
  14680. // ensure signout
  14681. $.ajax({
  14682. type: 'POST',
  14683. url: config.bosh,
  14684. async: false,
  14685. cache: false,
  14686. contentType: 'application/xml',
  14687. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  14688. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  14689. (connection.sid || connection._proto.sid) +
  14690. "' type='terminate'>" +
  14691. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14692. "</body>",
  14693. success: function (data) {
  14694. console.log('signed out');
  14695. console.log(data);
  14696. },
  14697. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14698. console.log('signout error',
  14699. textStatus + ' (' + errorThrown + ')');
  14700. }
  14701. });
  14702. }
  14703. XMPP.disposeConference(true);
  14704. };
  14705. })();
  14706. function setupEvents() {
  14707. // In recent versions of FF the 'beforeunload' event is not fired when the
  14708. // window or the tab is closed. It is only fired when we leave the page
  14709. // (change URL). If this participant doesn't unload properly, then it
  14710. // becomes a ghost for the rest of the participants that stay in the
  14711. // conference. Thankfully handling the 'unload' event in addition to the
  14712. // 'beforeunload' event seems to garante the execution of the 'unload'
  14713. // method at least once.
  14714. //
  14715. // The 'unload' method can safely be run multiple times, it will actually do
  14716. // something only the first time that it's run, so we're don't have to worry
  14717. // about browsers that fire both events.
  14718. $(window).bind('beforeunload', unload);
  14719. $(window).bind('unload', unload);
  14720. }
  14721. var XMPP = {
  14722. getConnection: function(){ return connection; },
  14723. sessionTerminated: false,
  14724. /**
  14725. * XMPP connection status
  14726. */
  14727. Status: Strophe.Status,
  14728. /**
  14729. * Remembers if we were muted by the focus.
  14730. * @type {boolean}
  14731. */
  14732. forceMuted: false,
  14733. start: function () {
  14734. setupEvents();
  14735. initStrophePlugins();
  14736. registerListeners();
  14737. Moderator.init(this, eventEmitter);
  14738. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14739. // Force authenticated domain if room is appended with '?login=true'
  14740. if (config.hosts.anonymousdomain &&
  14741. window.location.search.indexOf("login=true") !== -1) {
  14742. configDomain = config.hosts.domain;
  14743. }
  14744. var jid = configDomain || window.location.hostname;
  14745. connect(jid, null);
  14746. },
  14747. createConnection: function () {
  14748. var bosh = config.bosh || '/http-bind';
  14749. return new Strophe.Connection(bosh);
  14750. },
  14751. getStatusString: function (status) {
  14752. return Strophe.getStatusString(status);
  14753. },
  14754. promptLogin: function () {
  14755. // FIXME: re-use LoginDialog which supports retries
  14756. APP.UI.showLoginPopup(connect);
  14757. },
  14758. joinRoom: function(roomName, useNicks, nick)
  14759. {
  14760. var roomjid;
  14761. roomjid = roomName;
  14762. if (useNicks) {
  14763. if (nick) {
  14764. roomjid += '/' + nick;
  14765. } else {
  14766. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14767. }
  14768. } else {
  14769. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14770. if(!authenticatedUser)
  14771. tmpJid = tmpJid.substr(0, 8);
  14772. roomjid += '/' + tmpJid;
  14773. }
  14774. connection.emuc.doJoin(roomjid);
  14775. },
  14776. myJid: function () {
  14777. if(!connection)
  14778. return null;
  14779. return connection.emuc.myroomjid;
  14780. },
  14781. myResource: function () {
  14782. if(!connection || ! connection.emuc.myroomjid)
  14783. return null;
  14784. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14785. },
  14786. disposeConference: function (onUnload) {
  14787. var handler = connection.jingle.activecall;
  14788. if (handler && handler.peerconnection) {
  14789. // FIXME: probably removing streams is not required and close() should
  14790. // be enough
  14791. if (APP.RTC.localAudio) {
  14792. handler.peerconnection.removeStream(
  14793. APP.RTC.localAudio.getOriginalStream(), onUnload);
  14794. }
  14795. if (APP.RTC.localVideo) {
  14796. handler.peerconnection.removeStream(
  14797. APP.RTC.localVideo.getOriginalStream(), onUnload);
  14798. }
  14799. handler.peerconnection.close();
  14800. }
  14801. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14802. connection.jingle.activecall = null;
  14803. if(!onUnload)
  14804. {
  14805. this.sessionTerminated = true;
  14806. connection.emuc.doLeave();
  14807. }
  14808. },
  14809. addListener: function(type, listener)
  14810. {
  14811. eventEmitter.on(type, listener);
  14812. },
  14813. removeListener: function (type, listener) {
  14814. eventEmitter.removeListener(type, listener);
  14815. },
  14816. allocateConferenceFocus: function(roomName, callback) {
  14817. Moderator.allocateConferenceFocus(roomName, callback);
  14818. },
  14819. getLoginUrl: function (roomName, callback) {
  14820. Moderator.getLoginUrl(roomName, callback);
  14821. },
  14822. getPopupLoginUrl: function (roomName, callback) {
  14823. Moderator.getPopupLoginUrl(roomName, callback);
  14824. },
  14825. isModerator: function () {
  14826. return Moderator.isModerator();
  14827. },
  14828. isSipGatewayEnabled: function () {
  14829. return Moderator.isSipGatewayEnabled();
  14830. },
  14831. isExternalAuthEnabled: function () {
  14832. return Moderator.isExternalAuthEnabled();
  14833. },
  14834. isConferenceInProgress: function () {
  14835. return connection && connection.jingle.activecall &&
  14836. connection.jingle.activecall.peerconnection;
  14837. },
  14838. switchStreams: function (stream, oldStream, callback, isAudio) {
  14839. if (this.isConferenceInProgress()) {
  14840. // FIXME: will block switchInProgress on true value in case of exception
  14841. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  14842. } else {
  14843. // We are done immediately
  14844. console.warn("No conference handler or conference not started yet");
  14845. callback();
  14846. }
  14847. },
  14848. sendVideoInfoPresence: function (mute) {
  14849. if(!connection)
  14850. return;
  14851. connection.emuc.addVideoInfoToPresence(mute);
  14852. connection.emuc.sendPresence();
  14853. },
  14854. setVideoMute: function (mute, callback, options) {
  14855. if(!connection)
  14856. return;
  14857. var self = this;
  14858. var localCallback = function (mute) {
  14859. self.sendVideoInfoPresence(mute);
  14860. return callback(mute);
  14861. };
  14862. if(connection.jingle.activecall)
  14863. {
  14864. connection.jingle.activecall.setVideoMute(
  14865. mute, localCallback, options);
  14866. }
  14867. else {
  14868. localCallback(mute);
  14869. }
  14870. },
  14871. setAudioMute: function (mute, callback) {
  14872. if (!(connection && APP.RTC.localAudio)) {
  14873. return false;
  14874. }
  14875. if (this.forceMuted && !mute) {
  14876. console.info("Asking focus for unmute");
  14877. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14878. // FIXME: wait for result before resetting muted status
  14879. this.forceMuted = false;
  14880. }
  14881. if (mute == APP.RTC.localAudio.isMuted()) {
  14882. // Nothing to do
  14883. return true;
  14884. }
  14885. // It is not clear what is the right way to handle multiple tracks.
  14886. // So at least make sure that they are all muted or all unmuted and
  14887. // that we send presence just once.
  14888. APP.RTC.localAudio.setMute(!mute);
  14889. // isMuted is the opposite of audioEnabled
  14890. this.sendAudioInfoPresence(mute, callback);
  14891. return true;
  14892. },
  14893. sendAudioInfoPresence: function(mute, callback)
  14894. {
  14895. if(connection) {
  14896. connection.emuc.addAudioInfoToPresence(mute);
  14897. connection.emuc.sendPresence();
  14898. }
  14899. callback();
  14900. return true;
  14901. },
  14902. // Really mute video, i.e. dont even send black frames
  14903. muteVideo: function (pc, unmute) {
  14904. // FIXME: this probably needs another of those lovely state safeguards...
  14905. // which checks for iceconn == connected and sigstate == stable
  14906. pc.setRemoteDescription(pc.remoteDescription,
  14907. function () {
  14908. pc.createAnswer(
  14909. function (answer) {
  14910. var sdp = new SDP(answer.sdp);
  14911. if (sdp.media.length > 1) {
  14912. if (unmute)
  14913. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14914. else
  14915. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14916. sdp.raw = sdp.session + sdp.media.join('');
  14917. answer.sdp = sdp.raw;
  14918. }
  14919. pc.setLocalDescription(answer,
  14920. function () {
  14921. console.log('mute SLD ok');
  14922. },
  14923. function (error) {
  14924. console.log('mute SLD error');
  14925. APP.UI.messageHandler.showError("dialog.error",
  14926. "dialog.SLDFailure");
  14927. }
  14928. );
  14929. },
  14930. function (error) {
  14931. console.log(error);
  14932. APP.UI.messageHandler.showError();
  14933. }
  14934. );
  14935. },
  14936. function (error) {
  14937. console.log('muteVideo SRD error');
  14938. APP.UI.messageHandler.showError("dialog.error",
  14939. "dialog.SRDFailure");
  14940. }
  14941. );
  14942. },
  14943. toggleRecording: function (tokenEmptyCallback,
  14944. startingCallback, startedCallback) {
  14945. Recording.toggleRecording(tokenEmptyCallback,
  14946. startingCallback, startedCallback, connection);
  14947. },
  14948. addToPresence: function (name, value, dontSend) {
  14949. switch (name)
  14950. {
  14951. case "displayName":
  14952. connection.emuc.addDisplayNameToPresence(value);
  14953. break;
  14954. case "prezi":
  14955. connection.emuc.addPreziToPresence(value, 0);
  14956. break;
  14957. case "preziSlide":
  14958. connection.emuc.addCurrentSlideToPresence(value);
  14959. break;
  14960. case "connectionQuality":
  14961. connection.emuc.addConnectionInfoToPresence(value);
  14962. break;
  14963. case "email":
  14964. connection.emuc.addEmailToPresence(value);
  14965. break;
  14966. case "devices":
  14967. connection.emuc.addDevicesToPresence(value);
  14968. break;
  14969. case "startMuted":
  14970. if(!Moderator.isModerator())
  14971. return;
  14972. connection.emuc.addStartMutedToPresence(value[0],
  14973. value[1]);
  14974. break;
  14975. default :
  14976. console.log("Unknown tag for presence: " + name);
  14977. return;
  14978. }
  14979. if (!dontSend)
  14980. connection.emuc.sendPresence();
  14981. },
  14982. /**
  14983. * Sends 'data' as a log message to the focus. Returns true iff a message
  14984. * was sent.
  14985. * @param data
  14986. * @returns {boolean} true iff a message was sent.
  14987. */
  14988. sendLogs: function (data) {
  14989. if(!connection.emuc.focusMucJid)
  14990. return false;
  14991. var deflate = true;
  14992. var content = JSON.stringify(data);
  14993. if (deflate) {
  14994. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14995. }
  14996. content = Base64.encode(content);
  14997. // XEP-0337-ish
  14998. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14999. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15000. id: 'PeerConnectionStats'});
  15001. message.c('message').t(content).up();
  15002. if (deflate) {
  15003. message.c('tag', {name: "deflated", value: "true"}).up();
  15004. }
  15005. message.up();
  15006. connection.send(message);
  15007. return true;
  15008. },
  15009. populateData: function () {
  15010. var data = {};
  15011. if (connection.jingle) {
  15012. data = connection.jingle.populateData();
  15013. }
  15014. return data;
  15015. },
  15016. getLogger: function () {
  15017. if(connection.logger)
  15018. return connection.logger.log;
  15019. return null;
  15020. },
  15021. getPrezi: function () {
  15022. return connection.emuc.getPrezi(this.myJid());
  15023. },
  15024. removePreziFromPresence: function () {
  15025. connection.emuc.removePreziFromPresence();
  15026. connection.emuc.sendPresence();
  15027. },
  15028. sendChatMessage: function (message, nickname) {
  15029. connection.emuc.sendMessage(message, nickname);
  15030. },
  15031. setSubject: function (topic) {
  15032. connection.emuc.setSubject(topic);
  15033. },
  15034. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15035. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15036. },
  15037. dial: function (to, from, roomName,roomPass) {
  15038. connection.rayo.dial(to, from, roomName,roomPass);
  15039. },
  15040. setMute: function (jid, mute) {
  15041. connection.moderate.setMute(jid, mute);
  15042. },
  15043. eject: function (jid) {
  15044. connection.moderate.eject(jid);
  15045. },
  15046. logout: function (callback) {
  15047. Moderator.logout(callback);
  15048. },
  15049. findJidFromResource: function (resource) {
  15050. return connection.emuc.findJidFromResource(resource);
  15051. },
  15052. getMembers: function () {
  15053. return connection.emuc.members;
  15054. },
  15055. getJidFromSSRC: function (ssrc) {
  15056. if(!connection)
  15057. return null;
  15058. return connection.emuc.ssrc2jid[ssrc];
  15059. },
  15060. getMUCJoined: function () {
  15061. return connection.emuc.joined;
  15062. },
  15063. getSessions: function () {
  15064. return connection.jingle.sessions;
  15065. },
  15066. removeStream: function (stream) {
  15067. if (!this.isConferenceInProgress())
  15068. return;
  15069. connection.jingle.activecall.peerconnection.removeStream(stream);
  15070. }
  15071. };
  15072. module.exports = XMPP;
  15073. },{"../../service/RTC/RTCEvents":100,"../../service/RTC/StreamEventTypes":102,"../../service/UI/UIEvents":103,"../../service/xmpp/XMPPEvents":109,"../settings/Settings":47,"./SDP":54,"./moderator":58,"./recording":59,"./strophe.emuc":60,"./strophe.jingle":61,"./strophe.logger":62,"./strophe.moderate":63,"./strophe.rayo":64,"./strophe.util":65,"events":1,"pako":69,"retry":85}],67:[function(require,module,exports){
  15074. (function (process){
  15075. /*!
  15076. * async
  15077. * https://github.com/caolan/async
  15078. *
  15079. * Copyright 2010-2014 Caolan McMahon
  15080. * Released under the MIT license
  15081. */
  15082. /*jshint onevar: false, indent:4 */
  15083. /*global setImmediate: false, setTimeout: false, console: false */
  15084. (function () {
  15085. var async = {};
  15086. // global on the server, window in the browser
  15087. var root, previous_async;
  15088. root = this;
  15089. if (root != null) {
  15090. previous_async = root.async;
  15091. }
  15092. async.noConflict = function () {
  15093. root.async = previous_async;
  15094. return async;
  15095. };
  15096. function only_once(fn) {
  15097. var called = false;
  15098. return function() {
  15099. if (called) throw new Error("Callback was already called.");
  15100. called = true;
  15101. fn.apply(root, arguments);
  15102. }
  15103. }
  15104. //// cross-browser compatiblity functions ////
  15105. var _toString = Object.prototype.toString;
  15106. var _isArray = Array.isArray || function (obj) {
  15107. return _toString.call(obj) === '[object Array]';
  15108. };
  15109. var _each = function (arr, iterator) {
  15110. if (arr.forEach) {
  15111. return arr.forEach(iterator);
  15112. }
  15113. for (var i = 0; i < arr.length; i += 1) {
  15114. iterator(arr[i], i, arr);
  15115. }
  15116. };
  15117. var _map = function (arr, iterator) {
  15118. if (arr.map) {
  15119. return arr.map(iterator);
  15120. }
  15121. var results = [];
  15122. _each(arr, function (x, i, a) {
  15123. results.push(iterator(x, i, a));
  15124. });
  15125. return results;
  15126. };
  15127. var _reduce = function (arr, iterator, memo) {
  15128. if (arr.reduce) {
  15129. return arr.reduce(iterator, memo);
  15130. }
  15131. _each(arr, function (x, i, a) {
  15132. memo = iterator(memo, x, i, a);
  15133. });
  15134. return memo;
  15135. };
  15136. var _keys = function (obj) {
  15137. if (Object.keys) {
  15138. return Object.keys(obj);
  15139. }
  15140. var keys = [];
  15141. for (var k in obj) {
  15142. if (obj.hasOwnProperty(k)) {
  15143. keys.push(k);
  15144. }
  15145. }
  15146. return keys;
  15147. };
  15148. //// exported async module functions ////
  15149. //// nextTick implementation with browser-compatible fallback ////
  15150. if (typeof process === 'undefined' || !(process.nextTick)) {
  15151. if (typeof setImmediate === 'function') {
  15152. async.nextTick = function (fn) {
  15153. // not a direct alias for IE10 compatibility
  15154. setImmediate(fn);
  15155. };
  15156. async.setImmediate = async.nextTick;
  15157. }
  15158. else {
  15159. async.nextTick = function (fn) {
  15160. setTimeout(fn, 0);
  15161. };
  15162. async.setImmediate = async.nextTick;
  15163. }
  15164. }
  15165. else {
  15166. async.nextTick = process.nextTick;
  15167. if (typeof setImmediate !== 'undefined') {
  15168. async.setImmediate = function (fn) {
  15169. // not a direct alias for IE10 compatibility
  15170. setImmediate(fn);
  15171. };
  15172. }
  15173. else {
  15174. async.setImmediate = async.nextTick;
  15175. }
  15176. }
  15177. async.each = function (arr, iterator, callback) {
  15178. callback = callback || function () {};
  15179. if (!arr.length) {
  15180. return callback();
  15181. }
  15182. var completed = 0;
  15183. _each(arr, function (x) {
  15184. iterator(x, only_once(done) );
  15185. });
  15186. function done(err) {
  15187. if (err) {
  15188. callback(err);
  15189. callback = function () {};
  15190. }
  15191. else {
  15192. completed += 1;
  15193. if (completed >= arr.length) {
  15194. callback();
  15195. }
  15196. }
  15197. }
  15198. };
  15199. async.forEach = async.each;
  15200. async.eachSeries = function (arr, iterator, callback) {
  15201. callback = callback || function () {};
  15202. if (!arr.length) {
  15203. return callback();
  15204. }
  15205. var completed = 0;
  15206. var iterate = function () {
  15207. iterator(arr[completed], function (err) {
  15208. if (err) {
  15209. callback(err);
  15210. callback = function () {};
  15211. }
  15212. else {
  15213. completed += 1;
  15214. if (completed >= arr.length) {
  15215. callback();
  15216. }
  15217. else {
  15218. iterate();
  15219. }
  15220. }
  15221. });
  15222. };
  15223. iterate();
  15224. };
  15225. async.forEachSeries = async.eachSeries;
  15226. async.eachLimit = function (arr, limit, iterator, callback) {
  15227. var fn = _eachLimit(limit);
  15228. fn.apply(null, [arr, iterator, callback]);
  15229. };
  15230. async.forEachLimit = async.eachLimit;
  15231. var _eachLimit = function (limit) {
  15232. return function (arr, iterator, callback) {
  15233. callback = callback || function () {};
  15234. if (!arr.length || limit <= 0) {
  15235. return callback();
  15236. }
  15237. var completed = 0;
  15238. var started = 0;
  15239. var running = 0;
  15240. (function replenish () {
  15241. if (completed >= arr.length) {
  15242. return callback();
  15243. }
  15244. while (running < limit && started < arr.length) {
  15245. started += 1;
  15246. running += 1;
  15247. iterator(arr[started - 1], function (err) {
  15248. if (err) {
  15249. callback(err);
  15250. callback = function () {};
  15251. }
  15252. else {
  15253. completed += 1;
  15254. running -= 1;
  15255. if (completed >= arr.length) {
  15256. callback();
  15257. }
  15258. else {
  15259. replenish();
  15260. }
  15261. }
  15262. });
  15263. }
  15264. })();
  15265. };
  15266. };
  15267. var doParallel = function (fn) {
  15268. return function () {
  15269. var args = Array.prototype.slice.call(arguments);
  15270. return fn.apply(null, [async.each].concat(args));
  15271. };
  15272. };
  15273. var doParallelLimit = function(limit, fn) {
  15274. return function () {
  15275. var args = Array.prototype.slice.call(arguments);
  15276. return fn.apply(null, [_eachLimit(limit)].concat(args));
  15277. };
  15278. };
  15279. var doSeries = function (fn) {
  15280. return function () {
  15281. var args = Array.prototype.slice.call(arguments);
  15282. return fn.apply(null, [async.eachSeries].concat(args));
  15283. };
  15284. };
  15285. var _asyncMap = function (eachfn, arr, iterator, callback) {
  15286. arr = _map(arr, function (x, i) {
  15287. return {index: i, value: x};
  15288. });
  15289. if (!callback) {
  15290. eachfn(arr, function (x, callback) {
  15291. iterator(x.value, function (err) {
  15292. callback(err);
  15293. });
  15294. });
  15295. } else {
  15296. var results = [];
  15297. eachfn(arr, function (x, callback) {
  15298. iterator(x.value, function (err, v) {
  15299. results[x.index] = v;
  15300. callback(err);
  15301. });
  15302. }, function (err) {
  15303. callback(err, results);
  15304. });
  15305. }
  15306. };
  15307. async.map = doParallel(_asyncMap);
  15308. async.mapSeries = doSeries(_asyncMap);
  15309. async.mapLimit = function (arr, limit, iterator, callback) {
  15310. return _mapLimit(limit)(arr, iterator, callback);
  15311. };
  15312. var _mapLimit = function(limit) {
  15313. return doParallelLimit(limit, _asyncMap);
  15314. };
  15315. // reduce only has a series version, as doing reduce in parallel won't
  15316. // work in many situations.
  15317. async.reduce = function (arr, memo, iterator, callback) {
  15318. async.eachSeries(arr, function (x, callback) {
  15319. iterator(memo, x, function (err, v) {
  15320. memo = v;
  15321. callback(err);
  15322. });
  15323. }, function (err) {
  15324. callback(err, memo);
  15325. });
  15326. };
  15327. // inject alias
  15328. async.inject = async.reduce;
  15329. // foldl alias
  15330. async.foldl = async.reduce;
  15331. async.reduceRight = function (arr, memo, iterator, callback) {
  15332. var reversed = _map(arr, function (x) {
  15333. return x;
  15334. }).reverse();
  15335. async.reduce(reversed, memo, iterator, callback);
  15336. };
  15337. // foldr alias
  15338. async.foldr = async.reduceRight;
  15339. var _filter = function (eachfn, arr, iterator, callback) {
  15340. var results = [];
  15341. arr = _map(arr, function (x, i) {
  15342. return {index: i, value: x};
  15343. });
  15344. eachfn(arr, function (x, callback) {
  15345. iterator(x.value, function (v) {
  15346. if (v) {
  15347. results.push(x);
  15348. }
  15349. callback();
  15350. });
  15351. }, function (err) {
  15352. callback(_map(results.sort(function (a, b) {
  15353. return a.index - b.index;
  15354. }), function (x) {
  15355. return x.value;
  15356. }));
  15357. });
  15358. };
  15359. async.filter = doParallel(_filter);
  15360. async.filterSeries = doSeries(_filter);
  15361. // select alias
  15362. async.select = async.filter;
  15363. async.selectSeries = async.filterSeries;
  15364. var _reject = function (eachfn, arr, iterator, callback) {
  15365. var results = [];
  15366. arr = _map(arr, function (x, i) {
  15367. return {index: i, value: x};
  15368. });
  15369. eachfn(arr, function (x, callback) {
  15370. iterator(x.value, function (v) {
  15371. if (!v) {
  15372. results.push(x);
  15373. }
  15374. callback();
  15375. });
  15376. }, function (err) {
  15377. callback(_map(results.sort(function (a, b) {
  15378. return a.index - b.index;
  15379. }), function (x) {
  15380. return x.value;
  15381. }));
  15382. });
  15383. };
  15384. async.reject = doParallel(_reject);
  15385. async.rejectSeries = doSeries(_reject);
  15386. var _detect = function (eachfn, arr, iterator, main_callback) {
  15387. eachfn(arr, function (x, callback) {
  15388. iterator(x, function (result) {
  15389. if (result) {
  15390. main_callback(x);
  15391. main_callback = function () {};
  15392. }
  15393. else {
  15394. callback();
  15395. }
  15396. });
  15397. }, function (err) {
  15398. main_callback();
  15399. });
  15400. };
  15401. async.detect = doParallel(_detect);
  15402. async.detectSeries = doSeries(_detect);
  15403. async.some = function (arr, iterator, main_callback) {
  15404. async.each(arr, function (x, callback) {
  15405. iterator(x, function (v) {
  15406. if (v) {
  15407. main_callback(true);
  15408. main_callback = function () {};
  15409. }
  15410. callback();
  15411. });
  15412. }, function (err) {
  15413. main_callback(false);
  15414. });
  15415. };
  15416. // any alias
  15417. async.any = async.some;
  15418. async.every = function (arr, iterator, main_callback) {
  15419. async.each(arr, function (x, callback) {
  15420. iterator(x, function (v) {
  15421. if (!v) {
  15422. main_callback(false);
  15423. main_callback = function () {};
  15424. }
  15425. callback();
  15426. });
  15427. }, function (err) {
  15428. main_callback(true);
  15429. });
  15430. };
  15431. // all alias
  15432. async.all = async.every;
  15433. async.sortBy = function (arr, iterator, callback) {
  15434. async.map(arr, function (x, callback) {
  15435. iterator(x, function (err, criteria) {
  15436. if (err) {
  15437. callback(err);
  15438. }
  15439. else {
  15440. callback(null, {value: x, criteria: criteria});
  15441. }
  15442. });
  15443. }, function (err, results) {
  15444. if (err) {
  15445. return callback(err);
  15446. }
  15447. else {
  15448. var fn = function (left, right) {
  15449. var a = left.criteria, b = right.criteria;
  15450. return a < b ? -1 : a > b ? 1 : 0;
  15451. };
  15452. callback(null, _map(results.sort(fn), function (x) {
  15453. return x.value;
  15454. }));
  15455. }
  15456. });
  15457. };
  15458. async.auto = function (tasks, callback) {
  15459. callback = callback || function () {};
  15460. var keys = _keys(tasks);
  15461. var remainingTasks = keys.length
  15462. if (!remainingTasks) {
  15463. return callback();
  15464. }
  15465. var results = {};
  15466. var listeners = [];
  15467. var addListener = function (fn) {
  15468. listeners.unshift(fn);
  15469. };
  15470. var removeListener = function (fn) {
  15471. for (var i = 0; i < listeners.length; i += 1) {
  15472. if (listeners[i] === fn) {
  15473. listeners.splice(i, 1);
  15474. return;
  15475. }
  15476. }
  15477. };
  15478. var taskComplete = function () {
  15479. remainingTasks--
  15480. _each(listeners.slice(0), function (fn) {
  15481. fn();
  15482. });
  15483. };
  15484. addListener(function () {
  15485. if (!remainingTasks) {
  15486. var theCallback = callback;
  15487. // prevent final callback from calling itself if it errors
  15488. callback = function () {};
  15489. theCallback(null, results);
  15490. }
  15491. });
  15492. _each(keys, function (k) {
  15493. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  15494. var taskCallback = function (err) {
  15495. var args = Array.prototype.slice.call(arguments, 1);
  15496. if (args.length <= 1) {
  15497. args = args[0];
  15498. }
  15499. if (err) {
  15500. var safeResults = {};
  15501. _each(_keys(results), function(rkey) {
  15502. safeResults[rkey] = results[rkey];
  15503. });
  15504. safeResults[k] = args;
  15505. callback(err, safeResults);
  15506. // stop subsequent errors hitting callback multiple times
  15507. callback = function () {};
  15508. }
  15509. else {
  15510. results[k] = args;
  15511. async.setImmediate(taskComplete);
  15512. }
  15513. };
  15514. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  15515. var ready = function () {
  15516. return _reduce(requires, function (a, x) {
  15517. return (a && results.hasOwnProperty(x));
  15518. }, true) && !results.hasOwnProperty(k);
  15519. };
  15520. if (ready()) {
  15521. task[task.length - 1](taskCallback, results);
  15522. }
  15523. else {
  15524. var listener = function () {
  15525. if (ready()) {
  15526. removeListener(listener);
  15527. task[task.length - 1](taskCallback, results);
  15528. }
  15529. };
  15530. addListener(listener);
  15531. }
  15532. });
  15533. };
  15534. async.retry = function(times, task, callback) {
  15535. var DEFAULT_TIMES = 5;
  15536. var attempts = [];
  15537. // Use defaults if times not passed
  15538. if (typeof times === 'function') {
  15539. callback = task;
  15540. task = times;
  15541. times = DEFAULT_TIMES;
  15542. }
  15543. // Make sure times is a number
  15544. times = parseInt(times, 10) || DEFAULT_TIMES;
  15545. var wrappedTask = function(wrappedCallback, wrappedResults) {
  15546. var retryAttempt = function(task, finalAttempt) {
  15547. return function(seriesCallback) {
  15548. task(function(err, result){
  15549. seriesCallback(!err || finalAttempt, {err: err, result: result});
  15550. }, wrappedResults);
  15551. };
  15552. };
  15553. while (times) {
  15554. attempts.push(retryAttempt(task, !(times-=1)));
  15555. }
  15556. async.series(attempts, function(done, data){
  15557. data = data[data.length - 1];
  15558. (wrappedCallback || callback)(data.err, data.result);
  15559. });
  15560. }
  15561. // If a callback is passed, run this as a controll flow
  15562. return callback ? wrappedTask() : wrappedTask
  15563. };
  15564. async.waterfall = function (tasks, callback) {
  15565. callback = callback || function () {};
  15566. if (!_isArray(tasks)) {
  15567. var err = new Error('First argument to waterfall must be an array of functions');
  15568. return callback(err);
  15569. }
  15570. if (!tasks.length) {
  15571. return callback();
  15572. }
  15573. var wrapIterator = function (iterator) {
  15574. return function (err) {
  15575. if (err) {
  15576. callback.apply(null, arguments);
  15577. callback = function () {};
  15578. }
  15579. else {
  15580. var args = Array.prototype.slice.call(arguments, 1);
  15581. var next = iterator.next();
  15582. if (next) {
  15583. args.push(wrapIterator(next));
  15584. }
  15585. else {
  15586. args.push(callback);
  15587. }
  15588. async.setImmediate(function () {
  15589. iterator.apply(null, args);
  15590. });
  15591. }
  15592. };
  15593. };
  15594. wrapIterator(async.iterator(tasks))();
  15595. };
  15596. var _parallel = function(eachfn, tasks, callback) {
  15597. callback = callback || function () {};
  15598. if (_isArray(tasks)) {
  15599. eachfn.map(tasks, function (fn, callback) {
  15600. if (fn) {
  15601. fn(function (err) {
  15602. var args = Array.prototype.slice.call(arguments, 1);
  15603. if (args.length <= 1) {
  15604. args = args[0];
  15605. }
  15606. callback.call(null, err, args);
  15607. });
  15608. }
  15609. }, callback);
  15610. }
  15611. else {
  15612. var results = {};
  15613. eachfn.each(_keys(tasks), function (k, callback) {
  15614. tasks[k](function (err) {
  15615. var args = Array.prototype.slice.call(arguments, 1);
  15616. if (args.length <= 1) {
  15617. args = args[0];
  15618. }
  15619. results[k] = args;
  15620. callback(err);
  15621. });
  15622. }, function (err) {
  15623. callback(err, results);
  15624. });
  15625. }
  15626. };
  15627. async.parallel = function (tasks, callback) {
  15628. _parallel({ map: async.map, each: async.each }, tasks, callback);
  15629. };
  15630. async.parallelLimit = function(tasks, limit, callback) {
  15631. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  15632. };
  15633. async.series = function (tasks, callback) {
  15634. callback = callback || function () {};
  15635. if (_isArray(tasks)) {
  15636. async.mapSeries(tasks, function (fn, callback) {
  15637. if (fn) {
  15638. fn(function (err) {
  15639. var args = Array.prototype.slice.call(arguments, 1);
  15640. if (args.length <= 1) {
  15641. args = args[0];
  15642. }
  15643. callback.call(null, err, args);
  15644. });
  15645. }
  15646. }, callback);
  15647. }
  15648. else {
  15649. var results = {};
  15650. async.eachSeries(_keys(tasks), function (k, callback) {
  15651. tasks[k](function (err) {
  15652. var args = Array.prototype.slice.call(arguments, 1);
  15653. if (args.length <= 1) {
  15654. args = args[0];
  15655. }
  15656. results[k] = args;
  15657. callback(err);
  15658. });
  15659. }, function (err) {
  15660. callback(err, results);
  15661. });
  15662. }
  15663. };
  15664. async.iterator = function (tasks) {
  15665. var makeCallback = function (index) {
  15666. var fn = function () {
  15667. if (tasks.length) {
  15668. tasks[index].apply(null, arguments);
  15669. }
  15670. return fn.next();
  15671. };
  15672. fn.next = function () {
  15673. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  15674. };
  15675. return fn;
  15676. };
  15677. return makeCallback(0);
  15678. };
  15679. async.apply = function (fn) {
  15680. var args = Array.prototype.slice.call(arguments, 1);
  15681. return function () {
  15682. return fn.apply(
  15683. null, args.concat(Array.prototype.slice.call(arguments))
  15684. );
  15685. };
  15686. };
  15687. var _concat = function (eachfn, arr, fn, callback) {
  15688. var r = [];
  15689. eachfn(arr, function (x, cb) {
  15690. fn(x, function (err, y) {
  15691. r = r.concat(y || []);
  15692. cb(err);
  15693. });
  15694. }, function (err) {
  15695. callback(err, r);
  15696. });
  15697. };
  15698. async.concat = doParallel(_concat);
  15699. async.concatSeries = doSeries(_concat);
  15700. async.whilst = function (test, iterator, callback) {
  15701. if (test()) {
  15702. iterator(function (err) {
  15703. if (err) {
  15704. return callback(err);
  15705. }
  15706. async.whilst(test, iterator, callback);
  15707. });
  15708. }
  15709. else {
  15710. callback();
  15711. }
  15712. };
  15713. async.doWhilst = function (iterator, test, callback) {
  15714. iterator(function (err) {
  15715. if (err) {
  15716. return callback(err);
  15717. }
  15718. var args = Array.prototype.slice.call(arguments, 1);
  15719. if (test.apply(null, args)) {
  15720. async.doWhilst(iterator, test, callback);
  15721. }
  15722. else {
  15723. callback();
  15724. }
  15725. });
  15726. };
  15727. async.until = function (test, iterator, callback) {
  15728. if (!test()) {
  15729. iterator(function (err) {
  15730. if (err) {
  15731. return callback(err);
  15732. }
  15733. async.until(test, iterator, callback);
  15734. });
  15735. }
  15736. else {
  15737. callback();
  15738. }
  15739. };
  15740. async.doUntil = function (iterator, test, callback) {
  15741. iterator(function (err) {
  15742. if (err) {
  15743. return callback(err);
  15744. }
  15745. var args = Array.prototype.slice.call(arguments, 1);
  15746. if (!test.apply(null, args)) {
  15747. async.doUntil(iterator, test, callback);
  15748. }
  15749. else {
  15750. callback();
  15751. }
  15752. });
  15753. };
  15754. async.queue = function (worker, concurrency) {
  15755. if (concurrency === undefined) {
  15756. concurrency = 1;
  15757. }
  15758. function _insert(q, data, pos, callback) {
  15759. if (!q.started){
  15760. q.started = true;
  15761. }
  15762. if (!_isArray(data)) {
  15763. data = [data];
  15764. }
  15765. if(data.length == 0) {
  15766. // call drain immediately if there are no tasks
  15767. return async.setImmediate(function() {
  15768. if (q.drain) {
  15769. q.drain();
  15770. }
  15771. });
  15772. }
  15773. _each(data, function(task) {
  15774. var item = {
  15775. data: task,
  15776. callback: typeof callback === 'function' ? callback : null
  15777. };
  15778. if (pos) {
  15779. q.tasks.unshift(item);
  15780. } else {
  15781. q.tasks.push(item);
  15782. }
  15783. if (q.saturated && q.tasks.length === q.concurrency) {
  15784. q.saturated();
  15785. }
  15786. async.setImmediate(q.process);
  15787. });
  15788. }
  15789. var workers = 0;
  15790. var q = {
  15791. tasks: [],
  15792. concurrency: concurrency,
  15793. saturated: null,
  15794. empty: null,
  15795. drain: null,
  15796. started: false,
  15797. paused: false,
  15798. push: function (data, callback) {
  15799. _insert(q, data, false, callback);
  15800. },
  15801. kill: function () {
  15802. q.drain = null;
  15803. q.tasks = [];
  15804. },
  15805. unshift: function (data, callback) {
  15806. _insert(q, data, true, callback);
  15807. },
  15808. process: function () {
  15809. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  15810. var task = q.tasks.shift();
  15811. if (q.empty && q.tasks.length === 0) {
  15812. q.empty();
  15813. }
  15814. workers += 1;
  15815. var next = function () {
  15816. workers -= 1;
  15817. if (task.callback) {
  15818. task.callback.apply(task, arguments);
  15819. }
  15820. if (q.drain && q.tasks.length + workers === 0) {
  15821. q.drain();
  15822. }
  15823. q.process();
  15824. };
  15825. var cb = only_once(next);
  15826. worker(task.data, cb);
  15827. }
  15828. },
  15829. length: function () {
  15830. return q.tasks.length;
  15831. },
  15832. running: function () {
  15833. return workers;
  15834. },
  15835. idle: function() {
  15836. return q.tasks.length + workers === 0;
  15837. },
  15838. pause: function () {
  15839. if (q.paused === true) { return; }
  15840. q.paused = true;
  15841. q.process();
  15842. },
  15843. resume: function () {
  15844. if (q.paused === false) { return; }
  15845. q.paused = false;
  15846. q.process();
  15847. }
  15848. };
  15849. return q;
  15850. };
  15851. async.priorityQueue = function (worker, concurrency) {
  15852. function _compareTasks(a, b){
  15853. return a.priority - b.priority;
  15854. };
  15855. function _binarySearch(sequence, item, compare) {
  15856. var beg = -1,
  15857. end = sequence.length - 1;
  15858. while (beg < end) {
  15859. var mid = beg + ((end - beg + 1) >>> 1);
  15860. if (compare(item, sequence[mid]) >= 0) {
  15861. beg = mid;
  15862. } else {
  15863. end = mid - 1;
  15864. }
  15865. }
  15866. return beg;
  15867. }
  15868. function _insert(q, data, priority, callback) {
  15869. if (!q.started){
  15870. q.started = true;
  15871. }
  15872. if (!_isArray(data)) {
  15873. data = [data];
  15874. }
  15875. if(data.length == 0) {
  15876. // call drain immediately if there are no tasks
  15877. return async.setImmediate(function() {
  15878. if (q.drain) {
  15879. q.drain();
  15880. }
  15881. });
  15882. }
  15883. _each(data, function(task) {
  15884. var item = {
  15885. data: task,
  15886. priority: priority,
  15887. callback: typeof callback === 'function' ? callback : null
  15888. };
  15889. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  15890. if (q.saturated && q.tasks.length === q.concurrency) {
  15891. q.saturated();
  15892. }
  15893. async.setImmediate(q.process);
  15894. });
  15895. }
  15896. // Start with a normal queue
  15897. var q = async.queue(worker, concurrency);
  15898. // Override push to accept second parameter representing priority
  15899. q.push = function (data, priority, callback) {
  15900. _insert(q, data, priority, callback);
  15901. };
  15902. // Remove unshift function
  15903. delete q.unshift;
  15904. return q;
  15905. };
  15906. async.cargo = function (worker, payload) {
  15907. var working = false,
  15908. tasks = [];
  15909. var cargo = {
  15910. tasks: tasks,
  15911. payload: payload,
  15912. saturated: null,
  15913. empty: null,
  15914. drain: null,
  15915. drained: true,
  15916. push: function (data, callback) {
  15917. if (!_isArray(data)) {
  15918. data = [data];
  15919. }
  15920. _each(data, function(task) {
  15921. tasks.push({
  15922. data: task,
  15923. callback: typeof callback === 'function' ? callback : null
  15924. });
  15925. cargo.drained = false;
  15926. if (cargo.saturated && tasks.length === payload) {
  15927. cargo.saturated();
  15928. }
  15929. });
  15930. async.setImmediate(cargo.process);
  15931. },
  15932. process: function process() {
  15933. if (working) return;
  15934. if (tasks.length === 0) {
  15935. if(cargo.drain && !cargo.drained) cargo.drain();
  15936. cargo.drained = true;
  15937. return;
  15938. }
  15939. var ts = typeof payload === 'number'
  15940. ? tasks.splice(0, payload)
  15941. : tasks.splice(0, tasks.length);
  15942. var ds = _map(ts, function (task) {
  15943. return task.data;
  15944. });
  15945. if(cargo.empty) cargo.empty();
  15946. working = true;
  15947. worker(ds, function () {
  15948. working = false;
  15949. var args = arguments;
  15950. _each(ts, function (data) {
  15951. if (data.callback) {
  15952. data.callback.apply(null, args);
  15953. }
  15954. });
  15955. process();
  15956. });
  15957. },
  15958. length: function () {
  15959. return tasks.length;
  15960. },
  15961. running: function () {
  15962. return working;
  15963. }
  15964. };
  15965. return cargo;
  15966. };
  15967. var _console_fn = function (name) {
  15968. return function (fn) {
  15969. var args = Array.prototype.slice.call(arguments, 1);
  15970. fn.apply(null, args.concat([function (err) {
  15971. var args = Array.prototype.slice.call(arguments, 1);
  15972. if (typeof console !== 'undefined') {
  15973. if (err) {
  15974. if (console.error) {
  15975. console.error(err);
  15976. }
  15977. }
  15978. else if (console[name]) {
  15979. _each(args, function (x) {
  15980. console[name](x);
  15981. });
  15982. }
  15983. }
  15984. }]));
  15985. };
  15986. };
  15987. async.log = _console_fn('log');
  15988. async.dir = _console_fn('dir');
  15989. /*async.info = _console_fn('info');
  15990. async.warn = _console_fn('warn');
  15991. async.error = _console_fn('error');*/
  15992. async.memoize = function (fn, hasher) {
  15993. var memo = {};
  15994. var queues = {};
  15995. hasher = hasher || function (x) {
  15996. return x;
  15997. };
  15998. var memoized = function () {
  15999. var args = Array.prototype.slice.call(arguments);
  16000. var callback = args.pop();
  16001. var key = hasher.apply(null, args);
  16002. if (key in memo) {
  16003. async.nextTick(function () {
  16004. callback.apply(null, memo[key]);
  16005. });
  16006. }
  16007. else if (key in queues) {
  16008. queues[key].push(callback);
  16009. }
  16010. else {
  16011. queues[key] = [callback];
  16012. fn.apply(null, args.concat([function () {
  16013. memo[key] = arguments;
  16014. var q = queues[key];
  16015. delete queues[key];
  16016. for (var i = 0, l = q.length; i < l; i++) {
  16017. q[i].apply(null, arguments);
  16018. }
  16019. }]));
  16020. }
  16021. };
  16022. memoized.memo = memo;
  16023. memoized.unmemoized = fn;
  16024. return memoized;
  16025. };
  16026. async.unmemoize = function (fn) {
  16027. return function () {
  16028. return (fn.unmemoized || fn).apply(null, arguments);
  16029. };
  16030. };
  16031. async.times = function (count, iterator, callback) {
  16032. var counter = [];
  16033. for (var i = 0; i < count; i++) {
  16034. counter.push(i);
  16035. }
  16036. return async.map(counter, iterator, callback);
  16037. };
  16038. async.timesSeries = function (count, iterator, callback) {
  16039. var counter = [];
  16040. for (var i = 0; i < count; i++) {
  16041. counter.push(i);
  16042. }
  16043. return async.mapSeries(counter, iterator, callback);
  16044. };
  16045. async.seq = function (/* functions... */) {
  16046. var fns = arguments;
  16047. return function () {
  16048. var that = this;
  16049. var args = Array.prototype.slice.call(arguments);
  16050. var callback = args.pop();
  16051. async.reduce(fns, args, function (newargs, fn, cb) {
  16052. fn.apply(that, newargs.concat([function () {
  16053. var err = arguments[0];
  16054. var nextargs = Array.prototype.slice.call(arguments, 1);
  16055. cb(err, nextargs);
  16056. }]))
  16057. },
  16058. function (err, results) {
  16059. callback.apply(that, [err].concat(results));
  16060. });
  16061. };
  16062. };
  16063. async.compose = function (/* functions... */) {
  16064. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  16065. };
  16066. var _applyEach = function (eachfn, fns /*args...*/) {
  16067. var go = function () {
  16068. var that = this;
  16069. var args = Array.prototype.slice.call(arguments);
  16070. var callback = args.pop();
  16071. return eachfn(fns, function (fn, cb) {
  16072. fn.apply(that, args.concat([cb]));
  16073. },
  16074. callback);
  16075. };
  16076. if (arguments.length > 2) {
  16077. var args = Array.prototype.slice.call(arguments, 2);
  16078. return go.apply(this, args);
  16079. }
  16080. else {
  16081. return go;
  16082. }
  16083. };
  16084. async.applyEach = doParallel(_applyEach);
  16085. async.applyEachSeries = doSeries(_applyEach);
  16086. async.forever = function (fn, callback) {
  16087. function next(err) {
  16088. if (err) {
  16089. if (callback) {
  16090. return callback(err);
  16091. }
  16092. throw err;
  16093. }
  16094. fn(next);
  16095. }
  16096. next();
  16097. };
  16098. // Node.js
  16099. if (typeof module !== 'undefined' && module.exports) {
  16100. module.exports = async;
  16101. }
  16102. // AMD / RequireJS
  16103. else if (typeof define !== 'undefined' && define.amd) {
  16104. define([], function () {
  16105. return async;
  16106. });
  16107. }
  16108. // included directly via <script> tag
  16109. else {
  16110. root.async = async;
  16111. }
  16112. }());
  16113. }).call(this,require('_process'))
  16114. },{"_process":2}],68:[function(require,module,exports){
  16115. // i18next, v1.7.7
  16116. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  16117. // Distributed under MIT license
  16118. // http://i18next.com
  16119. (function() {
  16120. // add indexOf to non ECMA-262 standard compliant browsers
  16121. if (!Array.prototype.indexOf) {
  16122. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  16123. "use strict";
  16124. if (this == null) {
  16125. throw new TypeError();
  16126. }
  16127. var t = Object(this);
  16128. var len = t.length >>> 0;
  16129. if (len === 0) {
  16130. return -1;
  16131. }
  16132. var n = 0;
  16133. if (arguments.length > 0) {
  16134. n = Number(arguments[1]);
  16135. if (n != n) { // shortcut for verifying if it's NaN
  16136. n = 0;
  16137. } else if (n != 0 && n != Infinity && n != -Infinity) {
  16138. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16139. }
  16140. }
  16141. if (n >= len) {
  16142. return -1;
  16143. }
  16144. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  16145. for (; k < len; k++) {
  16146. if (k in t && t[k] === searchElement) {
  16147. return k;
  16148. }
  16149. }
  16150. return -1;
  16151. }
  16152. }
  16153. // add lastIndexOf to non ECMA-262 standard compliant browsers
  16154. if (!Array.prototype.lastIndexOf) {
  16155. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  16156. "use strict";
  16157. if (this == null) {
  16158. throw new TypeError();
  16159. }
  16160. var t = Object(this);
  16161. var len = t.length >>> 0;
  16162. if (len === 0) {
  16163. return -1;
  16164. }
  16165. var n = len;
  16166. if (arguments.length > 1) {
  16167. n = Number(arguments[1]);
  16168. if (n != n) {
  16169. n = 0;
  16170. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  16171. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16172. }
  16173. }
  16174. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  16175. for (; k >= 0; k--) {
  16176. if (k in t && t[k] === searchElement) {
  16177. return k;
  16178. }
  16179. }
  16180. return -1;
  16181. };
  16182. }
  16183. // Add string trim for IE8.
  16184. if (typeof String.prototype.trim !== 'function') {
  16185. String.prototype.trim = function() {
  16186. return this.replace(/^\s+|\s+$/g, '');
  16187. }
  16188. }
  16189. var root = this
  16190. , $ = root.jQuery || root.Zepto
  16191. , i18n = {}
  16192. , resStore = {}
  16193. , currentLng
  16194. , replacementCounter = 0
  16195. , languages = []
  16196. , initialized = false
  16197. , sync = {};
  16198. // Export the i18next object for **CommonJS**.
  16199. // If we're not in CommonJS, add `i18n` to the
  16200. // global object or to jquery.
  16201. if (typeof module !== 'undefined' && module.exports) {
  16202. if (!$) {
  16203. try {
  16204. $ = require('jquery');
  16205. } catch(e) {
  16206. // just ignore
  16207. }
  16208. }
  16209. if ($) {
  16210. $.i18n = $.i18n || i18n;
  16211. }
  16212. module.exports = i18n;
  16213. } else {
  16214. if ($) {
  16215. $.i18n = $.i18n || i18n;
  16216. }
  16217. root.i18n = root.i18n || i18n;
  16218. }
  16219. sync = {
  16220. load: function(lngs, options, cb) {
  16221. if (options.useLocalStorage) {
  16222. sync._loadLocal(lngs, options, function(err, store) {
  16223. var missingLngs = [];
  16224. for (var i = 0, len = lngs.length; i < len; i++) {
  16225. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  16226. }
  16227. if (missingLngs.length > 0) {
  16228. sync._fetch(missingLngs, options, function(err, fetched) {
  16229. f.extend(store, fetched);
  16230. sync._storeLocal(fetched);
  16231. cb(null, store);
  16232. });
  16233. } else {
  16234. cb(null, store);
  16235. }
  16236. });
  16237. } else {
  16238. sync._fetch(lngs, options, function(err, store){
  16239. cb(null, store);
  16240. });
  16241. }
  16242. },
  16243. _loadLocal: function(lngs, options, cb) {
  16244. var store = {}
  16245. , nowMS = new Date().getTime();
  16246. if(window.localStorage) {
  16247. var todo = lngs.length;
  16248. f.each(lngs, function(key, lng) {
  16249. var local = window.localStorage.getItem('res_' + lng);
  16250. if (local) {
  16251. local = JSON.parse(local);
  16252. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  16253. store[lng] = local;
  16254. }
  16255. }
  16256. todo--; // wait for all done befor callback
  16257. if (todo === 0) cb(null, store);
  16258. });
  16259. }
  16260. },
  16261. _storeLocal: function(store) {
  16262. if(window.localStorage) {
  16263. for (var m in store) {
  16264. store[m].i18nStamp = new Date().getTime();
  16265. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  16266. }
  16267. }
  16268. return;
  16269. },
  16270. _fetch: function(lngs, options, cb) {
  16271. var ns = options.ns
  16272. , store = {};
  16273. if (!options.dynamicLoad) {
  16274. var todo = ns.namespaces.length * lngs.length
  16275. , errors;
  16276. // load each file individual
  16277. f.each(ns.namespaces, function(nsIndex, nsValue) {
  16278. f.each(lngs, function(lngIndex, lngValue) {
  16279. // Call this once our translation has returned.
  16280. var loadComplete = function(err, data) {
  16281. if (err) {
  16282. errors = errors || [];
  16283. errors.push(err);
  16284. }
  16285. store[lngValue] = store[lngValue] || {};
  16286. store[lngValue][nsValue] = data;
  16287. todo--; // wait for all done befor callback
  16288. if (todo === 0) cb(errors, store);
  16289. };
  16290. if(typeof options.customLoad == 'function'){
  16291. // Use the specified custom callback.
  16292. options.customLoad(lngValue, nsValue, options, loadComplete);
  16293. } else {
  16294. //~ // Use our inbuilt sync.
  16295. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  16296. }
  16297. });
  16298. });
  16299. } else {
  16300. // Call this once our translation has returned.
  16301. var loadComplete = function(err, data) {
  16302. cb(null, data);
  16303. };
  16304. if(typeof options.customLoad == 'function'){
  16305. // Use the specified custom callback.
  16306. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  16307. } else {
  16308. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  16309. // load all needed stuff once
  16310. f.ajax({
  16311. url: url,
  16312. success: function(data, status, xhr) {
  16313. f.log('loaded: ' + url);
  16314. loadComplete(null, data);
  16315. },
  16316. error : function(xhr, status, error) {
  16317. f.log('failed loading: ' + url);
  16318. loadComplete('failed loading resource.json error: ' + error);
  16319. },
  16320. dataType: "json",
  16321. async : options.getAsync
  16322. });
  16323. }
  16324. }
  16325. },
  16326. _fetchOne: function(lng, ns, options, done) {
  16327. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  16328. f.ajax({
  16329. url: url,
  16330. success: function(data, status, xhr) {
  16331. f.log('loaded: ' + url);
  16332. done(null, data);
  16333. },
  16334. error : function(xhr, status, error) {
  16335. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  16336. // file loaded but invalid json, stop waste time !
  16337. f.error('There is a typo in: ' + url);
  16338. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  16339. f.log('Does not exist: ' + url);
  16340. } else {
  16341. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  16342. f.log(theStatus + ' when loading ' + url);
  16343. }
  16344. done(error, {});
  16345. },
  16346. dataType: "json",
  16347. async : options.getAsync
  16348. });
  16349. },
  16350. postMissing: function(lng, ns, key, defaultValue, lngs) {
  16351. var payload = {};
  16352. payload[key] = defaultValue;
  16353. var urls = [];
  16354. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  16355. for (var i = 0; i < o.fallbackLng.length; i++) {
  16356. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  16357. }
  16358. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  16359. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  16360. } else if (o.sendMissingTo === 'all') {
  16361. for (var i = 0, l = lngs.length; i < l; i++) {
  16362. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  16363. }
  16364. }
  16365. for (var y = 0, len = urls.length; y < len; y++) {
  16366. var item = urls[y];
  16367. f.ajax({
  16368. url: item.url,
  16369. type: o.sendType,
  16370. data: payload,
  16371. success: function(data, status, xhr) {
  16372. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  16373. // add key to resStore
  16374. var keys = key.split('.');
  16375. var x = 0;
  16376. var value = resStore[item.lng][ns];
  16377. while (keys[x]) {
  16378. if (x === keys.length - 1) {
  16379. value = value[keys[x]] = defaultValue;
  16380. } else {
  16381. value = value[keys[x]] = value[keys[x]] || {};
  16382. }
  16383. x++;
  16384. }
  16385. },
  16386. error : function(xhr, status, error) {
  16387. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  16388. },
  16389. dataType: "json",
  16390. async : o.postAsync
  16391. });
  16392. }
  16393. },
  16394. reload: reload
  16395. };
  16396. // defaults
  16397. var o = {
  16398. lng: undefined,
  16399. load: 'all',
  16400. preload: [],
  16401. lowerCaseLng: false,
  16402. returnObjectTrees: false,
  16403. fallbackLng: ['dev'],
  16404. fallbackNS: [],
  16405. detectLngQS: 'setLng',
  16406. detectLngFromLocalStorage: false,
  16407. ns: 'translation',
  16408. fallbackOnNull: true,
  16409. fallbackOnEmpty: false,
  16410. fallbackToDefaultNS: false,
  16411. nsseparator: ':',
  16412. keyseparator: '.',
  16413. selectorAttr: 'data-i18n',
  16414. debug: false,
  16415. resGetPath: 'locales/__lng__/__ns__.json',
  16416. resPostPath: 'locales/add/__lng__/__ns__',
  16417. getAsync: true,
  16418. postAsync: true,
  16419. resStore: undefined,
  16420. useLocalStorage: false,
  16421. localStorageExpirationTime: 7*24*60*60*1000,
  16422. dynamicLoad: false,
  16423. sendMissing: false,
  16424. sendMissingTo: 'fallback', // current | all
  16425. sendType: 'POST',
  16426. interpolationPrefix: '__',
  16427. interpolationSuffix: '__',
  16428. defaultVariables: false,
  16429. reusePrefix: '$t(',
  16430. reuseSuffix: ')',
  16431. pluralSuffix: '_plural',
  16432. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  16433. contextNotFound: ['context_not_found', Math.random()].join(''),
  16434. escapeInterpolation: false,
  16435. indefiniteSuffix: '_indefinite',
  16436. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  16437. setJqueryExt: true,
  16438. defaultValueFromContent: true,
  16439. useDataAttrOptions: false,
  16440. cookieExpirationTime: undefined,
  16441. useCookie: true,
  16442. cookieName: 'i18next',
  16443. cookieDomain: undefined,
  16444. objectTreeKeyHandler: undefined,
  16445. postProcess: undefined,
  16446. parseMissingKey: undefined,
  16447. missingKeyHandler: sync.postMissing,
  16448. shortcutFunction: 'sprintf' // or: defaultValue
  16449. };
  16450. function _extend(target, source) {
  16451. if (!source || typeof source === 'function') {
  16452. return target;
  16453. }
  16454. for (var attr in source) { target[attr] = source[attr]; }
  16455. return target;
  16456. }
  16457. function _deepExtend(target, source) {
  16458. for (var prop in source)
  16459. if (prop in target)
  16460. _deepExtend(target[prop], source[prop]);
  16461. else
  16462. target[prop] = source[prop];
  16463. return target;
  16464. }
  16465. function _each(object, callback, args) {
  16466. var name, i = 0,
  16467. length = object.length,
  16468. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  16469. if (args) {
  16470. if (isObj) {
  16471. for (name in object) {
  16472. if (callback.apply(object[name], args) === false) {
  16473. break;
  16474. }
  16475. }
  16476. } else {
  16477. for ( ; i < length; ) {
  16478. if (callback.apply(object[i++], args) === false) {
  16479. break;
  16480. }
  16481. }
  16482. }
  16483. // A special, fast, case for the most common use of each
  16484. } else {
  16485. if (isObj) {
  16486. for (name in object) {
  16487. if (callback.call(object[name], name, object[name]) === false) {
  16488. break;
  16489. }
  16490. }
  16491. } else {
  16492. for ( ; i < length; ) {
  16493. if (callback.call(object[i], i, object[i++]) === false) {
  16494. break;
  16495. }
  16496. }
  16497. }
  16498. }
  16499. return object;
  16500. }
  16501. var _entityMap = {
  16502. "&": "&amp;",
  16503. "<": "&lt;",
  16504. ">": "&gt;",
  16505. '"': '&quot;',
  16506. "'": '&#39;',
  16507. "/": '&#x2F;'
  16508. };
  16509. function _escape(data) {
  16510. if (typeof data === 'string') {
  16511. return data.replace(/[&<>"'\/]/g, function (s) {
  16512. return _entityMap[s];
  16513. });
  16514. }else{
  16515. return data;
  16516. }
  16517. }
  16518. function _ajax(options) {
  16519. // v0.5.0 of https://github.com/goloroden/http.js
  16520. var getXhr = function (callback) {
  16521. // Use the native XHR object if the browser supports it.
  16522. if (window.XMLHttpRequest) {
  16523. return callback(null, new XMLHttpRequest());
  16524. } else if (window.ActiveXObject) {
  16525. // In Internet Explorer check for ActiveX versions of the XHR object.
  16526. try {
  16527. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  16528. } catch (e) {
  16529. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  16530. }
  16531. }
  16532. // If no XHR support was found, throw an error.
  16533. return callback(new Error());
  16534. };
  16535. var encodeUsingUrlEncoding = function (data) {
  16536. if(typeof data === 'string') {
  16537. return data;
  16538. }
  16539. var result = [];
  16540. for(var dataItem in data) {
  16541. if(data.hasOwnProperty(dataItem)) {
  16542. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  16543. }
  16544. }
  16545. return result.join('&');
  16546. };
  16547. var utf8 = function (text) {
  16548. text = text.replace(/\r\n/g, '\n');
  16549. var result = '';
  16550. for(var i = 0; i < text.length; i++) {
  16551. var c = text.charCodeAt(i);
  16552. if(c < 128) {
  16553. result += String.fromCharCode(c);
  16554. } else if((c > 127) && (c < 2048)) {
  16555. result += String.fromCharCode((c >> 6) | 192);
  16556. result += String.fromCharCode((c & 63) | 128);
  16557. } else {
  16558. result += String.fromCharCode((c >> 12) | 224);
  16559. result += String.fromCharCode(((c >> 6) & 63) | 128);
  16560. result += String.fromCharCode((c & 63) | 128);
  16561. }
  16562. }
  16563. return result;
  16564. };
  16565. var base64 = function (text) {
  16566. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  16567. text = utf8(text);
  16568. var result = '',
  16569. chr1, chr2, chr3,
  16570. enc1, enc2, enc3, enc4,
  16571. i = 0;
  16572. do {
  16573. chr1 = text.charCodeAt(i++);
  16574. chr2 = text.charCodeAt(i++);
  16575. chr3 = text.charCodeAt(i++);
  16576. enc1 = chr1 >> 2;
  16577. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  16578. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  16579. enc4 = chr3 & 63;
  16580. if(isNaN(chr2)) {
  16581. enc3 = enc4 = 64;
  16582. } else if(isNaN(chr3)) {
  16583. enc4 = 64;
  16584. }
  16585. result +=
  16586. keyStr.charAt(enc1) +
  16587. keyStr.charAt(enc2) +
  16588. keyStr.charAt(enc3) +
  16589. keyStr.charAt(enc4);
  16590. chr1 = chr2 = chr3 = '';
  16591. enc1 = enc2 = enc3 = enc4 = '';
  16592. } while(i < text.length);
  16593. return result;
  16594. };
  16595. var mergeHeaders = function () {
  16596. // Use the first header object as base.
  16597. var result = arguments[0];
  16598. // Iterate through the remaining header objects and add them.
  16599. for(var i = 1; i < arguments.length; i++) {
  16600. var currentHeaders = arguments[i];
  16601. for(var header in currentHeaders) {
  16602. if(currentHeaders.hasOwnProperty(header)) {
  16603. result[header] = currentHeaders[header];
  16604. }
  16605. }
  16606. }
  16607. // Return the merged headers.
  16608. return result;
  16609. };
  16610. var ajax = function (method, url, options, callback) {
  16611. // Adjust parameters.
  16612. if(typeof options === 'function') {
  16613. callback = options;
  16614. options = {};
  16615. }
  16616. // Set default parameter values.
  16617. options.cache = options.cache || false;
  16618. options.data = options.data || {};
  16619. options.headers = options.headers || {};
  16620. options.jsonp = options.jsonp || false;
  16621. options.async = options.async === undefined ? true : options.async;
  16622. // Merge the various header objects.
  16623. var headers = mergeHeaders({
  16624. 'accept': '*/*',
  16625. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  16626. }, ajax.headers, options.headers);
  16627. // Encode the data according to the content-type.
  16628. var payload;
  16629. if (headers['content-type'] === 'application/json') {
  16630. payload = JSON.stringify(options.data);
  16631. } else {
  16632. payload = encodeUsingUrlEncoding(options.data);
  16633. }
  16634. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  16635. // if neccessary.
  16636. if(method === 'GET') {
  16637. // Setup the query string.
  16638. var queryString = [];
  16639. if(payload) {
  16640. queryString.push(payload);
  16641. payload = null;
  16642. }
  16643. // Handle caching.
  16644. if(!options.cache) {
  16645. queryString.push('_=' + (new Date()).getTime());
  16646. }
  16647. // If neccessary prepare the query string for a JSONP call.
  16648. if(options.jsonp) {
  16649. queryString.push('callback=' + options.jsonp);
  16650. queryString.push('jsonp=' + options.jsonp);
  16651. }
  16652. // Merge the query string and attach it to the url.
  16653. queryString = queryString.join('&');
  16654. if (queryString.length > 1) {
  16655. if (url.indexOf('?') > -1) {
  16656. url += '&' + queryString;
  16657. } else {
  16658. url += '?' + queryString;
  16659. }
  16660. }
  16661. // Make a JSONP call if neccessary.
  16662. if(options.jsonp) {
  16663. var head = document.getElementsByTagName('head')[0];
  16664. var script = document.createElement('script');
  16665. script.type = 'text/javascript';
  16666. script.src = url;
  16667. head.appendChild(script);
  16668. return;
  16669. }
  16670. }
  16671. // Since we got here, it is no JSONP request, so make a normal XHR request.
  16672. getXhr(function (err, xhr) {
  16673. if(err) return callback(err);
  16674. // Open the request.
  16675. xhr.open(method, url, options.async);
  16676. // Set the request headers.
  16677. for(var header in headers) {
  16678. if(headers.hasOwnProperty(header)) {
  16679. xhr.setRequestHeader(header, headers[header]);
  16680. }
  16681. }
  16682. // Handle the request events.
  16683. xhr.onreadystatechange = function () {
  16684. if(xhr.readyState === 4) {
  16685. var data = xhr.responseText || '';
  16686. // If no callback is given, return.
  16687. if(!callback) {
  16688. return;
  16689. }
  16690. // Return an object that provides access to the data as text and JSON.
  16691. callback(xhr.status, {
  16692. text: function () {
  16693. return data;
  16694. },
  16695. json: function () {
  16696. try {
  16697. return JSON.parse(data)
  16698. } catch (e) {
  16699. f.error('Can not parse JSON. URL: ' + url);
  16700. return {};
  16701. }
  16702. }
  16703. });
  16704. }
  16705. };
  16706. // Actually send the XHR request.
  16707. xhr.send(payload);
  16708. });
  16709. };
  16710. // Define the external interface.
  16711. var http = {
  16712. authBasic: function (username, password) {
  16713. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  16714. },
  16715. connect: function (url, options, callback) {
  16716. return ajax('CONNECT', url, options, callback);
  16717. },
  16718. del: function (url, options, callback) {
  16719. return ajax('DELETE', url, options, callback);
  16720. },
  16721. get: function (url, options, callback) {
  16722. return ajax('GET', url, options, callback);
  16723. },
  16724. head: function (url, options, callback) {
  16725. return ajax('HEAD', url, options, callback);
  16726. },
  16727. headers: function (headers) {
  16728. ajax.headers = headers || {};
  16729. },
  16730. isAllowed: function (url, verb, callback) {
  16731. this.options(url, function (status, data) {
  16732. callback(data.text().indexOf(verb) !== -1);
  16733. });
  16734. },
  16735. options: function (url, options, callback) {
  16736. return ajax('OPTIONS', url, options, callback);
  16737. },
  16738. patch: function (url, options, callback) {
  16739. return ajax('PATCH', url, options, callback);
  16740. },
  16741. post: function (url, options, callback) {
  16742. return ajax('POST', url, options, callback);
  16743. },
  16744. put: function (url, options, callback) {
  16745. return ajax('PUT', url, options, callback);
  16746. },
  16747. trace: function (url, options, callback) {
  16748. return ajax('TRACE', url, options, callback);
  16749. }
  16750. };
  16751. var methode = options.type ? options.type.toLowerCase() : 'get';
  16752. http[methode](options.url, options, function (status, data) {
  16753. // file: protocol always gives status code 0, so check for data
  16754. if (status === 200 || (status === 0 && data.text())) {
  16755. options.success(data.json(), status, null);
  16756. } else {
  16757. options.error(data.text(), status, null);
  16758. }
  16759. });
  16760. }
  16761. var _cookie = {
  16762. create: function(name,value,minutes,domain) {
  16763. var expires;
  16764. if (minutes) {
  16765. var date = new Date();
  16766. date.setTime(date.getTime()+(minutes*60*1000));
  16767. expires = "; expires="+date.toGMTString();
  16768. }
  16769. else expires = "";
  16770. domain = (domain)? "domain="+domain+";" : "";
  16771. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  16772. },
  16773. read: function(name) {
  16774. var nameEQ = name + "=";
  16775. var ca = document.cookie.split(';');
  16776. for(var i=0;i < ca.length;i++) {
  16777. var c = ca[i];
  16778. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  16779. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  16780. }
  16781. return null;
  16782. },
  16783. remove: function(name) {
  16784. this.create(name,"",-1);
  16785. }
  16786. };
  16787. var cookie_noop = {
  16788. create: function(name,value,minutes,domain) {},
  16789. read: function(name) { return null; },
  16790. remove: function(name) {}
  16791. };
  16792. // move dependent functions to a container so that
  16793. // they can be overriden easier in no jquery environment (node.js)
  16794. var f = {
  16795. extend: $ ? $.extend : _extend,
  16796. deepExtend: _deepExtend,
  16797. each: $ ? $.each : _each,
  16798. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  16799. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  16800. detectLanguage: detectLanguage,
  16801. escape: _escape,
  16802. log: function(str) {
  16803. if (o.debug && typeof console !== "undefined") console.log(str);
  16804. },
  16805. error: function(str) {
  16806. if (typeof console !== "undefined") console.error(str);
  16807. },
  16808. getCountyIndexOfLng: function(lng) {
  16809. var lng_index = 0;
  16810. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  16811. return lng_index;
  16812. },
  16813. toLanguages: function(lng) {
  16814. var log = this.log;
  16815. function applyCase(l) {
  16816. var ret = l;
  16817. if (typeof l === 'string' && l.indexOf('-') > -1) {
  16818. var parts = l.split('-');
  16819. ret = o.lowerCaseLng ?
  16820. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16821. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16822. } else {
  16823. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  16824. }
  16825. return ret;
  16826. }
  16827. var languages = [];
  16828. var whitelist = o.lngWhitelist || false;
  16829. var addLanguage = function(language){
  16830. //reject langs not whitelisted
  16831. if(!whitelist || whitelist.indexOf(language) > -1){
  16832. languages.push(language);
  16833. }else{
  16834. log('rejecting non-whitelisted language: ' + language);
  16835. }
  16836. };
  16837. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  16838. var parts = lng.split('-');
  16839. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  16840. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  16841. } else {
  16842. addLanguage(applyCase(lng));
  16843. }
  16844. for (var i = 0; i < o.fallbackLng.length; i++) {
  16845. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  16846. }
  16847. return languages;
  16848. },
  16849. regexEscape: function(str) {
  16850. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  16851. },
  16852. regexReplacementEscape: function(strOrFn) {
  16853. if (typeof strOrFn === 'string') {
  16854. return strOrFn.replace(/\$/g, "$$$$");
  16855. } else {
  16856. return strOrFn;
  16857. }
  16858. },
  16859. localStorage: {
  16860. setItem: function(key, value) {
  16861. if (window.localStorage) {
  16862. try {
  16863. window.localStorage.setItem(key, value);
  16864. } catch (e) {
  16865. f.log('failed to set value for key "' + key + '" to localStorage.');
  16866. }
  16867. }
  16868. }
  16869. }
  16870. };
  16871. function init(options, cb) {
  16872. if (typeof options === 'function') {
  16873. cb = options;
  16874. options = {};
  16875. }
  16876. options = options || {};
  16877. // override defaults with passed in options
  16878. f.extend(o, options);
  16879. delete o.fixLng; /* passed in each time */
  16880. // override functions: .log(), .detectLanguage(), etc
  16881. if (o.functions) {
  16882. delete o.functions;
  16883. f.extend(f, options.functions);
  16884. }
  16885. // create namespace object if namespace is passed in as string
  16886. if (typeof o.ns == 'string') {
  16887. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  16888. }
  16889. // fallback namespaces
  16890. if (typeof o.fallbackNS == 'string') {
  16891. o.fallbackNS = [o.fallbackNS];
  16892. }
  16893. // fallback languages
  16894. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  16895. o.fallbackLng = [o.fallbackLng];
  16896. }
  16897. // escape prefix/suffix
  16898. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  16899. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  16900. if (!o.lng) o.lng = f.detectLanguage();
  16901. languages = f.toLanguages(o.lng);
  16902. currentLng = languages[0];
  16903. f.log('currentLng set to: ' + currentLng);
  16904. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  16905. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  16906. }
  16907. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  16908. f.localStorage.setItem('i18next_lng', currentLng);
  16909. }
  16910. var lngTranslate = translate;
  16911. if (options.fixLng) {
  16912. lngTranslate = function(key, options) {
  16913. options = options || {};
  16914. options.lng = options.lng || lngTranslate.lng;
  16915. return translate(key, options);
  16916. };
  16917. lngTranslate.lng = currentLng;
  16918. }
  16919. pluralExtensions.setCurrentLng(currentLng);
  16920. // add JQuery extensions
  16921. if ($ && o.setJqueryExt) addJqueryFunct();
  16922. // jQuery deferred
  16923. var deferred;
  16924. if ($ && $.Deferred) {
  16925. deferred = $.Deferred();
  16926. }
  16927. // return immidiatly if res are passed in
  16928. if (o.resStore) {
  16929. resStore = o.resStore;
  16930. initialized = true;
  16931. if (cb) cb(lngTranslate);
  16932. if (deferred) deferred.resolve(lngTranslate);
  16933. if (deferred) return deferred.promise();
  16934. return;
  16935. }
  16936. // languages to load
  16937. var lngsToLoad = f.toLanguages(o.lng);
  16938. if (typeof o.preload === 'string') o.preload = [o.preload];
  16939. for (var i = 0, l = o.preload.length; i < l; i++) {
  16940. var pres = f.toLanguages(o.preload[i]);
  16941. for (var y = 0, len = pres.length; y < len; y++) {
  16942. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16943. lngsToLoad.push(pres[y]);
  16944. }
  16945. }
  16946. }
  16947. // else load them
  16948. i18n.sync.load(lngsToLoad, o, function(err, store) {
  16949. resStore = store;
  16950. initialized = true;
  16951. if (cb) cb(lngTranslate);
  16952. if (deferred) deferred.resolve(lngTranslate);
  16953. });
  16954. if (deferred) return deferred.promise();
  16955. }
  16956. function preload(lngs, cb) {
  16957. if (typeof lngs === 'string') lngs = [lngs];
  16958. for (var i = 0, l = lngs.length; i < l; i++) {
  16959. if (o.preload.indexOf(lngs[i]) < 0) {
  16960. o.preload.push(lngs[i]);
  16961. }
  16962. }
  16963. return init(cb);
  16964. }
  16965. function addResourceBundle(lng, ns, resources, deep) {
  16966. if (typeof ns !== 'string') {
  16967. resources = ns;
  16968. ns = o.ns.defaultNs;
  16969. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16970. o.ns.namespaces.push(ns);
  16971. }
  16972. resStore[lng] = resStore[lng] || {};
  16973. resStore[lng][ns] = resStore[lng][ns] || {};
  16974. if (deep) {
  16975. f.deepExtend(resStore[lng][ns], resources);
  16976. } else {
  16977. f.extend(resStore[lng][ns], resources);
  16978. }
  16979. }
  16980. function hasResourceBundle(lng, ns) {
  16981. if (typeof ns !== 'string') {
  16982. ns = o.ns.defaultNs;
  16983. }
  16984. resStore[lng] = resStore[lng] || {};
  16985. var res = resStore[lng][ns] || {};
  16986. var hasValues = false;
  16987. for(var prop in res) {
  16988. if (res.hasOwnProperty(prop)) {
  16989. hasValues = true;
  16990. }
  16991. }
  16992. return hasValues;
  16993. }
  16994. function removeResourceBundle(lng, ns) {
  16995. if (typeof ns !== 'string') {
  16996. ns = o.ns.defaultNs;
  16997. }
  16998. resStore[lng] = resStore[lng] || {};
  16999. resStore[lng][ns] = {};
  17000. }
  17001. function addResource(lng, ns, key, value) {
  17002. if (typeof ns !== 'string') {
  17003. resource = ns;
  17004. ns = o.ns.defaultNs;
  17005. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17006. o.ns.namespaces.push(ns);
  17007. }
  17008. resStore[lng] = resStore[lng] || {};
  17009. resStore[lng][ns] = resStore[lng][ns] || {};
  17010. var keys = key.split(o.keyseparator);
  17011. var x = 0;
  17012. var node = resStore[lng][ns];
  17013. var origRef = node;
  17014. while (keys[x]) {
  17015. if (x == keys.length - 1)
  17016. node[keys[x]] = value;
  17017. else {
  17018. if (node[keys[x]] == null)
  17019. node[keys[x]] = {};
  17020. node = node[keys[x]];
  17021. }
  17022. x++;
  17023. }
  17024. }
  17025. function addResources(lng, ns, resources) {
  17026. if (typeof ns !== 'string') {
  17027. resource = ns;
  17028. ns = o.ns.defaultNs;
  17029. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17030. o.ns.namespaces.push(ns);
  17031. }
  17032. for (var m in resources) {
  17033. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  17034. }
  17035. }
  17036. function setDefaultNamespace(ns) {
  17037. o.ns.defaultNs = ns;
  17038. }
  17039. function loadNamespace(namespace, cb) {
  17040. loadNamespaces([namespace], cb);
  17041. }
  17042. function loadNamespaces(namespaces, cb) {
  17043. var opts = {
  17044. dynamicLoad: o.dynamicLoad,
  17045. resGetPath: o.resGetPath,
  17046. getAsync: o.getAsync,
  17047. customLoad: o.customLoad,
  17048. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  17049. };
  17050. // languages to load
  17051. var lngsToLoad = f.toLanguages(o.lng);
  17052. if (typeof o.preload === 'string') o.preload = [o.preload];
  17053. for (var i = 0, l = o.preload.length; i < l; i++) {
  17054. var pres = f.toLanguages(o.preload[i]);
  17055. for (var y = 0, len = pres.length; y < len; y++) {
  17056. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17057. lngsToLoad.push(pres[y]);
  17058. }
  17059. }
  17060. }
  17061. // check if we have to load
  17062. var lngNeedLoad = [];
  17063. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  17064. var needLoad = false;
  17065. var resSet = resStore[lngsToLoad[a]];
  17066. if (resSet) {
  17067. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  17068. if (!resSet[namespaces[b]]) needLoad = true;
  17069. }
  17070. } else {
  17071. needLoad = true;
  17072. }
  17073. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  17074. }
  17075. if (lngNeedLoad.length) {
  17076. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  17077. var todo = namespaces.length * lngNeedLoad.length;
  17078. // load each file individual
  17079. f.each(namespaces, function(nsIndex, nsValue) {
  17080. // append namespace to namespace array
  17081. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  17082. o.ns.namespaces.push(nsValue);
  17083. }
  17084. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  17085. resStore[lngValue] = resStore[lngValue] || {};
  17086. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  17087. todo--; // wait for all done befor callback
  17088. if (todo === 0 && cb) {
  17089. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  17090. cb();
  17091. }
  17092. });
  17093. });
  17094. });
  17095. } else {
  17096. if (cb) cb();
  17097. }
  17098. }
  17099. function setLng(lng, options, cb) {
  17100. if (typeof options === 'function') {
  17101. cb = options;
  17102. options = {};
  17103. } else if (!options) {
  17104. options = {};
  17105. }
  17106. options.lng = lng;
  17107. return init(options, cb);
  17108. }
  17109. function lng() {
  17110. return currentLng;
  17111. }
  17112. function reload(cb) {
  17113. resStore = {};
  17114. setLng(currentLng, cb);
  17115. }
  17116. function addJqueryFunct() {
  17117. // $.t shortcut
  17118. $.t = $.t || translate;
  17119. function parse(ele, key, options) {
  17120. if (key.length === 0) return;
  17121. var attr = 'text';
  17122. if (key.indexOf('[') === 0) {
  17123. var parts = key.split(']');
  17124. key = parts[1];
  17125. attr = parts[0].substr(1, parts[0].length-1);
  17126. }
  17127. if (key.indexOf(';') === key.length-1) {
  17128. key = key.substr(0, key.length-2);
  17129. }
  17130. var optionsToUse;
  17131. if (attr === 'html') {
  17132. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17133. ele.html($.t(key, optionsToUse));
  17134. } else if (attr === 'text') {
  17135. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  17136. ele.text($.t(key, optionsToUse));
  17137. } else if (attr === 'prepend') {
  17138. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17139. ele.prepend($.t(key, optionsToUse));
  17140. } else if (attr === 'append') {
  17141. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17142. ele.append($.t(key, optionsToUse));
  17143. } else if (attr.indexOf("data-") === 0) {
  17144. var dataAttr = attr.substr(("data-").length);
  17145. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  17146. var translated = $.t(key, optionsToUse);
  17147. //we change into the data cache
  17148. ele.data(dataAttr, translated);
  17149. //we change into the dom
  17150. ele.attr(attr, translated);
  17151. } else {
  17152. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  17153. ele.attr(attr, $.t(key, optionsToUse));
  17154. }
  17155. }
  17156. function localize(ele, options) {
  17157. var key = ele.attr(o.selectorAttr);
  17158. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  17159. if (!key) return;
  17160. var target = ele
  17161. , targetSelector = ele.data("i18n-target");
  17162. if (targetSelector) {
  17163. target = ele.find(targetSelector) || ele;
  17164. }
  17165. if (!options && o.useDataAttrOptions === true) {
  17166. options = ele.data("i18n-options");
  17167. }
  17168. options = options || {};
  17169. if (key.indexOf(';') >= 0) {
  17170. var keys = key.split(';');
  17171. $.each(keys, function(m, k) {
  17172. if (k !== '') parse(target, k, options);
  17173. });
  17174. } else {
  17175. parse(target, key, options);
  17176. }
  17177. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  17178. }
  17179. // fn
  17180. $.fn.i18n = function (options) {
  17181. return this.each(function() {
  17182. // localize element itself
  17183. localize($(this), options);
  17184. // localize childs
  17185. var elements = $(this).find('[' + o.selectorAttr + ']');
  17186. elements.each(function() {
  17187. localize($(this), options);
  17188. });
  17189. });
  17190. };
  17191. }
  17192. function applyReplacement(str, replacementHash, nestedKey, options) {
  17193. if (!str) return str;
  17194. options = options || replacementHash; // first call uses replacement hash combined with options
  17195. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  17196. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  17197. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  17198. , unEscapingSuffix = 'HTML'+suffix;
  17199. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  17200. f.each(hash, function(key, value) {
  17201. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  17202. if (typeof value === 'object' && value !== null) {
  17203. str = applyReplacement(str, value, nextKey, options);
  17204. } else {
  17205. if (options.escapeInterpolation || o.escapeInterpolation) {
  17206. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  17207. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  17208. } else {
  17209. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  17210. }
  17211. // str = options.escapeInterpolation;
  17212. }
  17213. });
  17214. return str;
  17215. }
  17216. // append it to functions
  17217. f.applyReplacement = applyReplacement;
  17218. function applyReuse(translated, options) {
  17219. var comma = ',';
  17220. var options_open = '{';
  17221. var options_close = '}';
  17222. var opts = f.extend({}, options);
  17223. delete opts.postProcess;
  17224. while (translated.indexOf(o.reusePrefix) != -1) {
  17225. replacementCounter++;
  17226. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  17227. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  17228. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  17229. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  17230. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  17231. if (index_of_end_of_closing <= index_of_opening) {
  17232. f.error('there is an missing closing in following translation value', translated);
  17233. return '';
  17234. }
  17235. if (token_without_symbols.indexOf(comma) != -1) {
  17236. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  17237. 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) {
  17238. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  17239. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  17240. try {
  17241. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  17242. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  17243. } catch (e) {
  17244. }
  17245. }
  17246. }
  17247. var translated_token = _translate(token_without_symbols, opts);
  17248. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  17249. }
  17250. return translated;
  17251. }
  17252. function hasContext(options) {
  17253. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  17254. }
  17255. function needsPlural(options, lng) {
  17256. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  17257. }
  17258. function needsIndefiniteArticle(options) {
  17259. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  17260. }
  17261. function exists(key, options) {
  17262. options = options || {};
  17263. var notFound = _getDefaultValue(key, options)
  17264. , found = _find(key, options);
  17265. return found !== undefined || found === notFound;
  17266. }
  17267. function translate(key, options) {
  17268. options = options || {};
  17269. if (!initialized) {
  17270. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  17271. return options.defaultValue || '';
  17272. };
  17273. replacementCounter = 0;
  17274. return _translate.apply(null, arguments);
  17275. }
  17276. function _getDefaultValue(key, options) {
  17277. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  17278. }
  17279. function _injectSprintfProcessor() {
  17280. var values = [];
  17281. // mh: build array from second argument onwards
  17282. for (var i = 1; i < arguments.length; i++) {
  17283. values.push(arguments[i]);
  17284. }
  17285. return {
  17286. postProcess: 'sprintf',
  17287. sprintf: values
  17288. };
  17289. }
  17290. function _translate(potentialKeys, options) {
  17291. if (options && typeof options !== 'object') {
  17292. if (o.shortcutFunction === 'sprintf') {
  17293. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  17294. options = _injectSprintfProcessor.apply(null, arguments);
  17295. } else if (o.shortcutFunction === 'defaultValue') {
  17296. options = {
  17297. defaultValue: options
  17298. }
  17299. }
  17300. } else {
  17301. options = options || {};
  17302. }
  17303. if (typeof o.defaultVariables === 'object') {
  17304. options = f.extend({}, o.defaultVariables, options);
  17305. }
  17306. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  17307. if (typeof potentialKeys === 'string') {
  17308. potentialKeys = [potentialKeys];
  17309. }
  17310. var key = potentialKeys[0];
  17311. if (potentialKeys.length > 1) {
  17312. for (var i = 0; i < potentialKeys.length; i++) {
  17313. key = potentialKeys[i];
  17314. if (exists(key, options)) {
  17315. break;
  17316. }
  17317. }
  17318. }
  17319. var notFound = _getDefaultValue(key, options)
  17320. , found = _find(key, options)
  17321. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  17322. , ns = options.ns || o.ns.defaultNs
  17323. , parts;
  17324. // split ns and key
  17325. if (key.indexOf(o.nsseparator) > -1) {
  17326. parts = key.split(o.nsseparator);
  17327. ns = parts[0];
  17328. key = parts[1];
  17329. }
  17330. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  17331. if (options.lng) {
  17332. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  17333. } else {
  17334. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  17335. }
  17336. }
  17337. var postProcessor = options.postProcess || o.postProcess;
  17338. if (found !== undefined && postProcessor) {
  17339. if (postProcessors[postProcessor]) {
  17340. found = postProcessors[postProcessor](found, key, options);
  17341. }
  17342. }
  17343. // process notFound if function exists
  17344. var splitNotFound = notFound;
  17345. if (notFound.indexOf(o.nsseparator) > -1) {
  17346. parts = notFound.split(o.nsseparator);
  17347. splitNotFound = parts[1];
  17348. }
  17349. if (splitNotFound === key && o.parseMissingKey) {
  17350. notFound = o.parseMissingKey(notFound);
  17351. }
  17352. if (found === undefined) {
  17353. notFound = applyReplacement(notFound, options);
  17354. notFound = applyReuse(notFound, options);
  17355. if (postProcessor && postProcessors[postProcessor]) {
  17356. var val = _getDefaultValue(key, options);
  17357. found = postProcessors[postProcessor](val, key, options);
  17358. }
  17359. }
  17360. return (found !== undefined) ? found : notFound;
  17361. }
  17362. function _find(key, options) {
  17363. options = options || {};
  17364. var optionWithoutCount, translated
  17365. , notFound = _getDefaultValue(key, options)
  17366. , lngs = languages;
  17367. if (!resStore) { return notFound; } // no resStore to translate from
  17368. // CI mode
  17369. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  17370. // passed in lng
  17371. if (options.lngs) lngs = options.lngs;
  17372. if (options.lng) {
  17373. lngs = f.toLanguages(options.lng, options.fallbackLng);
  17374. if (!resStore[lngs[0]]) {
  17375. var oldAsync = o.getAsync;
  17376. o.getAsync = false;
  17377. i18n.sync.load(lngs, o, function(err, store) {
  17378. f.extend(resStore, store);
  17379. o.getAsync = oldAsync;
  17380. });
  17381. }
  17382. }
  17383. var ns = options.ns || o.ns.defaultNs;
  17384. if (key.indexOf(o.nsseparator) > -1) {
  17385. var parts = key.split(o.nsseparator);
  17386. ns = parts[0];
  17387. key = parts[1];
  17388. }
  17389. if (hasContext(options)) {
  17390. optionWithoutCount = f.extend({}, options);
  17391. delete optionWithoutCount.context;
  17392. optionWithoutCount.defaultValue = o.contextNotFound;
  17393. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  17394. translated = translate(contextKey, optionWithoutCount);
  17395. if (translated != o.contextNotFound) {
  17396. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  17397. } // else continue translation with original/nonContext key
  17398. }
  17399. if (needsPlural(options, lngs[0])) {
  17400. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  17401. delete optionWithoutCount.count;
  17402. delete optionWithoutCount.lng;
  17403. optionWithoutCount.defaultValue = o.pluralNotFound;
  17404. var pluralKey;
  17405. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  17406. pluralKey = ns + o.nsseparator + key;
  17407. } else {
  17408. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  17409. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  17410. if (pluralExtension >= 0) {
  17411. pluralKey = pluralKey + '_' + pluralExtension;
  17412. } else if (pluralExtension === 1) {
  17413. pluralKey = ns + o.nsseparator + key; // singular
  17414. }
  17415. }
  17416. translated = translate(pluralKey, optionWithoutCount);
  17417. if (translated != o.pluralNotFound) {
  17418. return applyReplacement(translated, {
  17419. count: options.count,
  17420. interpolationPrefix: options.interpolationPrefix,
  17421. interpolationSuffix: options.interpolationSuffix
  17422. }); // apply replacement for count only
  17423. } else if (lngs.length > 1) {
  17424. // remove failed lng
  17425. var clone = lngs.slice();
  17426. clone.shift();
  17427. options = f.extend(options, { lngs: clone });
  17428. delete options.lng;
  17429. // retry with fallbacks
  17430. translated = translate(ns + o.nsseparator + key, options);
  17431. if (translated != o.pluralNotFound) return translated;
  17432. } else {
  17433. return translated;
  17434. }
  17435. }
  17436. if (needsIndefiniteArticle(options)) {
  17437. var optionsWithoutIndef = f.extend({}, options);
  17438. delete optionsWithoutIndef.indefinite_article;
  17439. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  17440. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  17441. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  17442. translated = translate(indefiniteKey, optionsWithoutIndef);
  17443. if (translated != o.indefiniteNotFound) {
  17444. return translated;
  17445. }
  17446. }
  17447. var found;
  17448. var keys = key.split(o.keyseparator);
  17449. for (var i = 0, len = lngs.length; i < len; i++ ) {
  17450. if (found !== undefined) break;
  17451. var l = lngs[i];
  17452. var x = 0;
  17453. var value = resStore[l] && resStore[l][ns];
  17454. while (keys[x]) {
  17455. value = value && value[keys[x]];
  17456. x++;
  17457. }
  17458. if (value !== undefined) {
  17459. var valueType = Object.prototype.toString.apply(value);
  17460. if (typeof value === 'string') {
  17461. value = applyReplacement(value, options);
  17462. value = applyReuse(value, options);
  17463. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  17464. value = value.join('\n');
  17465. value = applyReplacement(value, options);
  17466. value = applyReuse(value, options);
  17467. } else if (value === null && o.fallbackOnNull === true) {
  17468. value = undefined;
  17469. } else if (value !== null) {
  17470. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  17471. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  17472. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  17473. } else {
  17474. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  17475. 'returned an object instead of string.';
  17476. f.log(value);
  17477. }
  17478. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  17479. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  17480. f.each(value, function(m) {
  17481. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  17482. });
  17483. value = copy;
  17484. }
  17485. }
  17486. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  17487. value = undefined;
  17488. found = value;
  17489. }
  17490. }
  17491. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  17492. // set flag for fallback lookup - avoid recursion
  17493. options.isFallbackLookup = true;
  17494. if (o.fallbackNS.length) {
  17495. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  17496. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  17497. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  17498. /* compare value without namespace */
  17499. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  17500. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  17501. if (foundValue !== notFoundValue) break;
  17502. }
  17503. }
  17504. } else {
  17505. found = _find(key, options); // fallback to default NS
  17506. }
  17507. options.isFallbackLookup = false;
  17508. }
  17509. return found;
  17510. }
  17511. function detectLanguage() {
  17512. var detectedLng;
  17513. var whitelist = o.lngWhitelist || [];
  17514. var userLngChoices = [];
  17515. // get from qs
  17516. var qsParm = [];
  17517. if (typeof window !== 'undefined') {
  17518. (function() {
  17519. var query = window.location.search.substring(1);
  17520. var params = query.split('&');
  17521. for (var i=0; i<params.length; i++) {
  17522. var pos = params[i].indexOf('=');
  17523. if (pos > 0) {
  17524. var key = params[i].substring(0,pos);
  17525. if (key == o.detectLngQS) {
  17526. userLngChoices.push(params[i].substring(pos+1));
  17527. }
  17528. }
  17529. }
  17530. })();
  17531. }
  17532. // get from cookie
  17533. if (o.useCookie && typeof document !== 'undefined') {
  17534. var c = f.cookie.read(o.cookieName);
  17535. if (c) userLngChoices.push(c);
  17536. }
  17537. // get from localStorage
  17538. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  17539. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  17540. }
  17541. // get from navigator
  17542. if (typeof navigator !== 'undefined') {
  17543. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  17544. for (var i=0;i<navigator.languages.length;i++) {
  17545. userLngChoices.push(navigator.languages[i]);
  17546. }
  17547. }
  17548. if (navigator.userLanguage) {
  17549. userLngChoices.push(navigator.userLanguage);
  17550. }
  17551. if (navigator.language) {
  17552. userLngChoices.push(navigator.language);
  17553. }
  17554. }
  17555. (function() {
  17556. for (var i=0;i<userLngChoices.length;i++) {
  17557. var lng = userLngChoices[i];
  17558. if (lng.indexOf('-') > -1) {
  17559. var parts = lng.split('-');
  17560. lng = o.lowerCaseLng ?
  17561. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17562. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17563. }
  17564. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  17565. detectedLng = lng;
  17566. break;
  17567. }
  17568. }
  17569. })();
  17570. //fallback
  17571. if (!detectedLng){
  17572. detectedLng = o.fallbackLng[0];
  17573. }
  17574. return detectedLng;
  17575. }
  17576. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  17577. /* [code, name, numbers, pluralsType] */
  17578. var _rules = [
  17579. ["ach", "Acholi", [1,2], 1],
  17580. ["af", "Afrikaans",[1,2], 2],
  17581. ["ak", "Akan", [1,2], 1],
  17582. ["am", "Amharic", [1,2], 1],
  17583. ["an", "Aragonese",[1,2], 2],
  17584. ["ar", "Arabic", [0,1,2,3,11,100],5],
  17585. ["arn", "Mapudungun",[1,2], 1],
  17586. ["ast", "Asturian", [1,2], 2],
  17587. ["ay", "Aymará", [1], 3],
  17588. ["az", "Azerbaijani",[1,2],2],
  17589. ["be", "Belarusian",[1,2,5],4],
  17590. ["bg", "Bulgarian",[1,2], 2],
  17591. ["bn", "Bengali", [1,2], 2],
  17592. ["bo", "Tibetan", [1], 3],
  17593. ["br", "Breton", [1,2], 1],
  17594. ["bs", "Bosnian", [1,2,5],4],
  17595. ["ca", "Catalan", [1,2], 2],
  17596. ["cgg", "Chiga", [1], 3],
  17597. ["cs", "Czech", [1,2,5],6],
  17598. ["csb", "Kashubian",[1,2,5],7],
  17599. ["cy", "Welsh", [1,2,3,8],8],
  17600. ["da", "Danish", [1,2], 2],
  17601. ["de", "German", [1,2], 2],
  17602. ["dev", "Development Fallback", [1,2], 2],
  17603. ["dz", "Dzongkha", [1], 3],
  17604. ["el", "Greek", [1,2], 2],
  17605. ["en", "English", [1,2], 2],
  17606. ["eo", "Esperanto",[1,2], 2],
  17607. ["es", "Spanish", [1,2], 2],
  17608. ["es_ar","Argentinean Spanish", [1,2], 2],
  17609. ["et", "Estonian", [1,2], 2],
  17610. ["eu", "Basque", [1,2], 2],
  17611. ["fa", "Persian", [1], 3],
  17612. ["fi", "Finnish", [1,2], 2],
  17613. ["fil", "Filipino", [1,2], 1],
  17614. ["fo", "Faroese", [1,2], 2],
  17615. ["fr", "French", [1,2], 9],
  17616. ["fur", "Friulian", [1,2], 2],
  17617. ["fy", "Frisian", [1,2], 2],
  17618. ["ga", "Irish", [1,2,3,7,11],10],
  17619. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  17620. ["gl", "Galician", [1,2], 2],
  17621. ["gu", "Gujarati", [1,2], 2],
  17622. ["gun", "Gun", [1,2], 1],
  17623. ["ha", "Hausa", [1,2], 2],
  17624. ["he", "Hebrew", [1,2], 2],
  17625. ["hi", "Hindi", [1,2], 2],
  17626. ["hr", "Croatian", [1,2,5],4],
  17627. ["hu", "Hungarian",[1,2], 2],
  17628. ["hy", "Armenian", [1,2], 2],
  17629. ["ia", "Interlingua",[1,2],2],
  17630. ["id", "Indonesian",[1], 3],
  17631. ["is", "Icelandic",[1,2], 12],
  17632. ["it", "Italian", [1,2], 2],
  17633. ["ja", "Japanese", [1], 3],
  17634. ["jbo", "Lojban", [1], 3],
  17635. ["jv", "Javanese", [0,1], 13],
  17636. ["ka", "Georgian", [1], 3],
  17637. ["kk", "Kazakh", [1], 3],
  17638. ["km", "Khmer", [1], 3],
  17639. ["kn", "Kannada", [1,2], 2],
  17640. ["ko", "Korean", [1], 3],
  17641. ["ku", "Kurdish", [1,2], 2],
  17642. ["kw", "Cornish", [1,2,3,4],14],
  17643. ["ky", "Kyrgyz", [1], 3],
  17644. ["lb", "Letzeburgesch",[1,2],2],
  17645. ["ln", "Lingala", [1,2], 1],
  17646. ["lo", "Lao", [1], 3],
  17647. ["lt", "Lithuanian",[1,2,10],15],
  17648. ["lv", "Latvian", [1,2,0],16],
  17649. ["mai", "Maithili", [1,2], 2],
  17650. ["mfe", "Mauritian Creole",[1,2],1],
  17651. ["mg", "Malagasy", [1,2], 1],
  17652. ["mi", "Maori", [1,2], 1],
  17653. ["mk", "Macedonian",[1,2],17],
  17654. ["ml", "Malayalam",[1,2], 2],
  17655. ["mn", "Mongolian",[1,2], 2],
  17656. ["mnk", "Mandinka", [0,1,2],18],
  17657. ["mr", "Marathi", [1,2], 2],
  17658. ["ms", "Malay", [1], 3],
  17659. ["mt", "Maltese", [1,2,11,20],19],
  17660. ["nah", "Nahuatl", [1,2], 2],
  17661. ["nap", "Neapolitan",[1,2], 2],
  17662. ["nb", "Norwegian Bokmal",[1,2],2],
  17663. ["ne", "Nepali", [1,2], 2],
  17664. ["nl", "Dutch", [1,2], 2],
  17665. ["nn", "Norwegian Nynorsk",[1,2],2],
  17666. ["no", "Norwegian",[1,2], 2],
  17667. ["nso", "Northern Sotho",[1,2],2],
  17668. ["oc", "Occitan", [1,2], 1],
  17669. ["or", "Oriya", [2,1], 2],
  17670. ["pa", "Punjabi", [1,2], 2],
  17671. ["pap", "Papiamento",[1,2], 2],
  17672. ["pl", "Polish", [1,2,5],7],
  17673. ["pms", "Piemontese",[1,2], 2],
  17674. ["ps", "Pashto", [1,2], 2],
  17675. ["pt", "Portuguese",[1,2], 2],
  17676. ["pt_br","Brazilian Portuguese",[1,2], 2],
  17677. ["rm", "Romansh", [1,2], 2],
  17678. ["ro", "Romanian", [1,2,20],20],
  17679. ["ru", "Russian", [1,2,5],4],
  17680. ["sah", "Yakut", [1], 3],
  17681. ["sco", "Scots", [1,2], 2],
  17682. ["se", "Northern Sami",[1,2], 2],
  17683. ["si", "Sinhala", [1,2], 2],
  17684. ["sk", "Slovak", [1,2,5],6],
  17685. ["sl", "Slovenian",[5,1,2,3],21],
  17686. ["so", "Somali", [1,2], 2],
  17687. ["son", "Songhay", [1,2], 2],
  17688. ["sq", "Albanian", [1,2], 2],
  17689. ["sr", "Serbian", [1,2,5],4],
  17690. ["su", "Sundanese",[1], 3],
  17691. ["sv", "Swedish", [1,2], 2],
  17692. ["sw", "Swahili", [1,2], 2],
  17693. ["ta", "Tamil", [1,2], 2],
  17694. ["te", "Telugu", [1,2], 2],
  17695. ["tg", "Tajik", [1,2], 1],
  17696. ["th", "Thai", [1], 3],
  17697. ["ti", "Tigrinya", [1,2], 1],
  17698. ["tk", "Turkmen", [1,2], 2],
  17699. ["tr", "Turkish", [1,2], 1],
  17700. ["tt", "Tatar", [1], 3],
  17701. ["ug", "Uyghur", [1], 3],
  17702. ["uk", "Ukrainian",[1,2,5],4],
  17703. ["ur", "Urdu", [1,2], 2],
  17704. ["uz", "Uzbek", [1,2], 1],
  17705. ["vi", "Vietnamese",[1], 3],
  17706. ["wa", "Walloon", [1,2], 1],
  17707. ["wo", "Wolof", [1], 3],
  17708. ["yo", "Yoruba", [1,2], 2],
  17709. ["zh", "Chinese", [1], 3]
  17710. ];
  17711. var _rulesPluralsTypes = {
  17712. 1: function(n) {return Number(n > 1);},
  17713. 2: function(n) {return Number(n != 1);},
  17714. 3: function(n) {return 0;},
  17715. 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);},
  17716. 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);},
  17717. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  17718. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  17719. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  17720. 9: function(n) {return Number(n >= 2);},
  17721. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  17722. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  17723. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  17724. 13: function(n) {return Number(n !== 0);},
  17725. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  17726. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  17727. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  17728. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  17729. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  17730. 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);},
  17731. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  17732. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  17733. };
  17734. var pluralExtensions = {
  17735. rules: (function () {
  17736. var l, rules = {};
  17737. for (l=_rules.length; l-- ;) {
  17738. rules[_rules[l][0]] = {
  17739. name: _rules[l][1],
  17740. numbers: _rules[l][2],
  17741. plurals: _rulesPluralsTypes[_rules[l][3]]
  17742. }
  17743. }
  17744. return rules;
  17745. }()),
  17746. // you can add your own pluralExtensions
  17747. addRule: function(lng, obj) {
  17748. pluralExtensions.rules[lng] = obj;
  17749. },
  17750. setCurrentLng: function(lng) {
  17751. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  17752. var parts = lng.split('-');
  17753. pluralExtensions.currentRule = {
  17754. lng: lng,
  17755. rule: pluralExtensions.rules[parts[0]]
  17756. };
  17757. }
  17758. },
  17759. needsPlural: function(lng, count) {
  17760. var parts = lng.split('-');
  17761. var ext;
  17762. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  17763. ext = pluralExtensions.currentRule.rule;
  17764. } else {
  17765. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  17766. }
  17767. if (ext && ext.numbers.length <= 1) {
  17768. return false;
  17769. } else {
  17770. return this.get(lng, count) !== 1;
  17771. }
  17772. },
  17773. get: function(lng, count) {
  17774. var parts = lng.split('-');
  17775. function getResult(l, c) {
  17776. var ext;
  17777. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  17778. ext = pluralExtensions.currentRule.rule;
  17779. } else {
  17780. ext = pluralExtensions.rules[l];
  17781. }
  17782. if (ext) {
  17783. var i;
  17784. if (ext.noAbs) {
  17785. i = ext.plurals(c);
  17786. } else {
  17787. i = ext.plurals(Math.abs(c));
  17788. }
  17789. var number = ext.numbers[i];
  17790. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  17791. if (number === 2) {
  17792. number = -1; // regular plural
  17793. } else if (number === 1) {
  17794. number = 1; // singular
  17795. }
  17796. }//console.log(count + '-' + number);
  17797. return number;
  17798. } else {
  17799. return c === 1 ? '1' : '-1';
  17800. }
  17801. }
  17802. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  17803. }
  17804. };
  17805. var postProcessors = {};
  17806. var addPostProcessor = function(name, fc) {
  17807. postProcessors[name] = fc;
  17808. };
  17809. // sprintf support
  17810. var sprintf = (function() {
  17811. function get_type(variable) {
  17812. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  17813. }
  17814. function str_repeat(input, multiplier) {
  17815. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  17816. return output.join('');
  17817. }
  17818. var str_format = function() {
  17819. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  17820. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  17821. }
  17822. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  17823. };
  17824. str_format.format = function(parse_tree, argv) {
  17825. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  17826. for (i = 0; i < tree_length; i++) {
  17827. node_type = get_type(parse_tree[i]);
  17828. if (node_type === 'string') {
  17829. output.push(parse_tree[i]);
  17830. }
  17831. else if (node_type === 'array') {
  17832. match = parse_tree[i]; // convenience purposes only
  17833. if (match[2]) { // keyword argument
  17834. arg = argv[cursor];
  17835. for (k = 0; k < match[2].length; k++) {
  17836. if (!arg.hasOwnProperty(match[2][k])) {
  17837. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  17838. }
  17839. arg = arg[match[2][k]];
  17840. }
  17841. }
  17842. else if (match[1]) { // positional argument (explicit)
  17843. arg = argv[match[1]];
  17844. }
  17845. else { // positional argument (implicit)
  17846. arg = argv[cursor++];
  17847. }
  17848. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  17849. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  17850. }
  17851. switch (match[8]) {
  17852. case 'b': arg = arg.toString(2); break;
  17853. case 'c': arg = String.fromCharCode(arg); break;
  17854. case 'd': arg = parseInt(arg, 10); break;
  17855. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  17856. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  17857. case 'o': arg = arg.toString(8); break;
  17858. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  17859. case 'u': arg = Math.abs(arg); break;
  17860. case 'x': arg = arg.toString(16); break;
  17861. case 'X': arg = arg.toString(16).toUpperCase(); break;
  17862. }
  17863. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  17864. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  17865. pad_length = match[6] - String(arg).length;
  17866. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  17867. output.push(match[5] ? arg + pad : pad + arg);
  17868. }
  17869. }
  17870. return output.join('');
  17871. };
  17872. str_format.cache = {};
  17873. str_format.parse = function(fmt) {
  17874. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  17875. while (_fmt) {
  17876. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  17877. parse_tree.push(match[0]);
  17878. }
  17879. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  17880. parse_tree.push('%');
  17881. }
  17882. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  17883. if (match[2]) {
  17884. arg_names |= 1;
  17885. var field_list = [], replacement_field = match[2], field_match = [];
  17886. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17887. field_list.push(field_match[1]);
  17888. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  17889. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17890. field_list.push(field_match[1]);
  17891. }
  17892. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  17893. field_list.push(field_match[1]);
  17894. }
  17895. else {
  17896. throw('[sprintf] huh?');
  17897. }
  17898. }
  17899. }
  17900. else {
  17901. throw('[sprintf] huh?');
  17902. }
  17903. match[2] = field_list;
  17904. }
  17905. else {
  17906. arg_names |= 2;
  17907. }
  17908. if (arg_names === 3) {
  17909. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  17910. }
  17911. parse_tree.push(match);
  17912. }
  17913. else {
  17914. throw('[sprintf] huh?');
  17915. }
  17916. _fmt = _fmt.substring(match[0].length);
  17917. }
  17918. return parse_tree;
  17919. };
  17920. return str_format;
  17921. })();
  17922. var vsprintf = function(fmt, argv) {
  17923. argv.unshift(fmt);
  17924. return sprintf.apply(null, argv);
  17925. };
  17926. addPostProcessor("sprintf", function(val, key, opts) {
  17927. if (!opts.sprintf) return val;
  17928. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  17929. return vsprintf(val, opts.sprintf);
  17930. } else if (typeof opts.sprintf === 'object') {
  17931. return sprintf(val, opts.sprintf);
  17932. }
  17933. return val;
  17934. });
  17935. // public api interface
  17936. i18n.init = init;
  17937. i18n.setLng = setLng;
  17938. i18n.preload = preload;
  17939. i18n.addResourceBundle = addResourceBundle;
  17940. i18n.hasResourceBundle = hasResourceBundle;
  17941. i18n.addResource = addResource;
  17942. i18n.addResources = addResources;
  17943. i18n.removeResourceBundle = removeResourceBundle;
  17944. i18n.loadNamespace = loadNamespace;
  17945. i18n.loadNamespaces = loadNamespaces;
  17946. i18n.setDefaultNamespace = setDefaultNamespace;
  17947. i18n.t = translate;
  17948. i18n.translate = translate;
  17949. i18n.exists = exists;
  17950. i18n.detectLanguage = f.detectLanguage;
  17951. i18n.pluralExtensions = pluralExtensions;
  17952. i18n.sync = sync;
  17953. i18n.functions = f;
  17954. i18n.lng = lng;
  17955. i18n.addPostProcessor = addPostProcessor;
  17956. i18n.options = o;
  17957. })();
  17958. },{"jquery":"jquery"}],69:[function(require,module,exports){
  17959. // Top level file is just a mixin of submodules & constants
  17960. 'use strict';
  17961. var assign = require('./lib/utils/common').assign;
  17962. var deflate = require('./lib/deflate');
  17963. var inflate = require('./lib/inflate');
  17964. var constants = require('./lib/zlib/constants');
  17965. var pako = {};
  17966. assign(pako, deflate, inflate, constants);
  17967. module.exports = pako;
  17968. },{"./lib/deflate":70,"./lib/inflate":71,"./lib/utils/common":72,"./lib/zlib/constants":75}],70:[function(require,module,exports){
  17969. 'use strict';
  17970. var zlib_deflate = require('./zlib/deflate.js');
  17971. var utils = require('./utils/common');
  17972. var strings = require('./utils/strings');
  17973. var msg = require('./zlib/messages');
  17974. var zstream = require('./zlib/zstream');
  17975. var toString = Object.prototype.toString;
  17976. /* Public constants ==========================================================*/
  17977. /* ===========================================================================*/
  17978. var Z_NO_FLUSH = 0;
  17979. var Z_FINISH = 4;
  17980. var Z_OK = 0;
  17981. var Z_STREAM_END = 1;
  17982. var Z_SYNC_FLUSH = 2;
  17983. var Z_DEFAULT_COMPRESSION = -1;
  17984. var Z_DEFAULT_STRATEGY = 0;
  17985. var Z_DEFLATED = 8;
  17986. /* ===========================================================================*/
  17987. /**
  17988. * class Deflate
  17989. *
  17990. * Generic JS-style wrapper for zlib calls. If you don't need
  17991. * streaming behaviour - use more simple functions: [[deflate]],
  17992. * [[deflateRaw]] and [[gzip]].
  17993. **/
  17994. /* internal
  17995. * Deflate.chunks -> Array
  17996. *
  17997. * Chunks of output data, if [[Deflate#onData]] not overriden.
  17998. **/
  17999. /**
  18000. * Deflate.result -> Uint8Array|Array
  18001. *
  18002. * Compressed result, generated by default [[Deflate#onData]]
  18003. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  18004. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  18005. * push a chunk with explicit flush (call [[Deflate#push]] with
  18006. * `Z_SYNC_FLUSH` param).
  18007. **/
  18008. /**
  18009. * Deflate.err -> Number
  18010. *
  18011. * Error code after deflate finished. 0 (Z_OK) on success.
  18012. * You will not need it in real life, because deflate errors
  18013. * are possible only on wrong options or bad `onData` / `onEnd`
  18014. * custom handlers.
  18015. **/
  18016. /**
  18017. * Deflate.msg -> String
  18018. *
  18019. * Error message, if [[Deflate.err]] != 0
  18020. **/
  18021. /**
  18022. * new Deflate(options)
  18023. * - options (Object): zlib deflate options.
  18024. *
  18025. * Creates new deflator instance with specified params. Throws exception
  18026. * on bad params. Supported options:
  18027. *
  18028. * - `level`
  18029. * - `windowBits`
  18030. * - `memLevel`
  18031. * - `strategy`
  18032. *
  18033. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18034. * for more information on these.
  18035. *
  18036. * Additional options, for internal needs:
  18037. *
  18038. * - `chunkSize` - size of generated data chunks (16K by default)
  18039. * - `raw` (Boolean) - do raw deflate
  18040. * - `gzip` (Boolean) - create gzip wrapper
  18041. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18042. * (each char code [0..255])
  18043. * - `header` (Object) - custom header for gzip
  18044. * - `text` (Boolean) - true if compressed data believed to be text
  18045. * - `time` (Number) - modification time, unix timestamp
  18046. * - `os` (Number) - operation system code
  18047. * - `extra` (Array) - array of bytes with extra data (max 65536)
  18048. * - `name` (String) - file name (binary string)
  18049. * - `comment` (String) - comment (binary string)
  18050. * - `hcrc` (Boolean) - true if header crc should be added
  18051. *
  18052. * ##### Example:
  18053. *
  18054. * ```javascript
  18055. * var pako = require('pako')
  18056. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18057. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18058. *
  18059. * var deflate = new pako.Deflate({ level: 3});
  18060. *
  18061. * deflate.push(chunk1, false);
  18062. * deflate.push(chunk2, true); // true -> last chunk
  18063. *
  18064. * if (deflate.err) { throw new Error(deflate.err); }
  18065. *
  18066. * console.log(deflate.result);
  18067. * ```
  18068. **/
  18069. var Deflate = function(options) {
  18070. this.options = utils.assign({
  18071. level: Z_DEFAULT_COMPRESSION,
  18072. method: Z_DEFLATED,
  18073. chunkSize: 16384,
  18074. windowBits: 15,
  18075. memLevel: 8,
  18076. strategy: Z_DEFAULT_STRATEGY,
  18077. to: ''
  18078. }, options || {});
  18079. var opt = this.options;
  18080. if (opt.raw && (opt.windowBits > 0)) {
  18081. opt.windowBits = -opt.windowBits;
  18082. }
  18083. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  18084. opt.windowBits += 16;
  18085. }
  18086. this.err = 0; // error code, if happens (0 = Z_OK)
  18087. this.msg = ''; // error message
  18088. this.ended = false; // used to avoid multiple onEnd() calls
  18089. this.chunks = []; // chunks of compressed data
  18090. this.strm = new zstream();
  18091. this.strm.avail_out = 0;
  18092. var status = zlib_deflate.deflateInit2(
  18093. this.strm,
  18094. opt.level,
  18095. opt.method,
  18096. opt.windowBits,
  18097. opt.memLevel,
  18098. opt.strategy
  18099. );
  18100. if (status !== Z_OK) {
  18101. throw new Error(msg[status]);
  18102. }
  18103. if (opt.header) {
  18104. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  18105. }
  18106. };
  18107. /**
  18108. * Deflate#push(data[, mode]) -> Boolean
  18109. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  18110. * converted to utf8 byte sequence.
  18111. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18112. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18113. *
  18114. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  18115. * new compressed chunks. Returns `true` on success. The last data block must have
  18116. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  18117. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  18118. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  18119. *
  18120. * On fail call [[Deflate#onEnd]] with error code and return false.
  18121. *
  18122. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18123. * array format is detected automatically). Also, don't skip last param and always
  18124. * use the same type in your code (boolean or number). That will improve JS speed.
  18125. *
  18126. * For regular `Array`-s make sure all elements are [0..255].
  18127. *
  18128. * ##### Example
  18129. *
  18130. * ```javascript
  18131. * push(chunk, false); // push one of data chunks
  18132. * ...
  18133. * push(chunk, true); // push last chunk
  18134. * ```
  18135. **/
  18136. Deflate.prototype.push = function(data, mode) {
  18137. var strm = this.strm;
  18138. var chunkSize = this.options.chunkSize;
  18139. var status, _mode;
  18140. if (this.ended) { return false; }
  18141. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  18142. // Convert data if needed
  18143. if (typeof data === 'string') {
  18144. // If we need to compress text, change encoding to utf8.
  18145. strm.input = strings.string2buf(data);
  18146. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18147. strm.input = new Uint8Array(data);
  18148. } else {
  18149. strm.input = data;
  18150. }
  18151. strm.next_in = 0;
  18152. strm.avail_in = strm.input.length;
  18153. do {
  18154. if (strm.avail_out === 0) {
  18155. strm.output = new utils.Buf8(chunkSize);
  18156. strm.next_out = 0;
  18157. strm.avail_out = chunkSize;
  18158. }
  18159. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  18160. if (status !== Z_STREAM_END && status !== Z_OK) {
  18161. this.onEnd(status);
  18162. this.ended = true;
  18163. return false;
  18164. }
  18165. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  18166. if (this.options.to === 'string') {
  18167. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  18168. } else {
  18169. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18170. }
  18171. }
  18172. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  18173. // Finalize on the last chunk.
  18174. if (_mode === Z_FINISH) {
  18175. status = zlib_deflate.deflateEnd(this.strm);
  18176. this.onEnd(status);
  18177. this.ended = true;
  18178. return status === Z_OK;
  18179. }
  18180. // callback interim results if Z_SYNC_FLUSH.
  18181. if (_mode === Z_SYNC_FLUSH) {
  18182. this.onEnd(Z_OK);
  18183. strm.avail_out = 0;
  18184. return true;
  18185. }
  18186. return true;
  18187. };
  18188. /**
  18189. * Deflate#onData(chunk) -> Void
  18190. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18191. * on js engine support. When string output requested, each chunk
  18192. * will be string.
  18193. *
  18194. * By default, stores data blocks in `chunks[]` property and glue
  18195. * those in `onEnd`. Override this handler, if you need another behaviour.
  18196. **/
  18197. Deflate.prototype.onData = function(chunk) {
  18198. this.chunks.push(chunk);
  18199. };
  18200. /**
  18201. * Deflate#onEnd(status) -> Void
  18202. * - status (Number): deflate status. 0 (Z_OK) on success,
  18203. * other if not.
  18204. *
  18205. * Called once after you tell deflate that the input stream is
  18206. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  18207. * or if an error happened. By default - join collected chunks,
  18208. * free memory and fill `results` / `err` properties.
  18209. **/
  18210. Deflate.prototype.onEnd = function(status) {
  18211. // On success - join
  18212. if (status === Z_OK) {
  18213. if (this.options.to === 'string') {
  18214. this.result = this.chunks.join('');
  18215. } else {
  18216. this.result = utils.flattenChunks(this.chunks);
  18217. }
  18218. }
  18219. this.chunks = [];
  18220. this.err = status;
  18221. this.msg = this.strm.msg;
  18222. };
  18223. /**
  18224. * deflate(data[, options]) -> Uint8Array|Array|String
  18225. * - data (Uint8Array|Array|String): input data to compress.
  18226. * - options (Object): zlib deflate options.
  18227. *
  18228. * Compress `data` with deflate alrorythm and `options`.
  18229. *
  18230. * Supported options are:
  18231. *
  18232. * - level
  18233. * - windowBits
  18234. * - memLevel
  18235. * - strategy
  18236. *
  18237. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18238. * for more information on these.
  18239. *
  18240. * Sugar (options):
  18241. *
  18242. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  18243. * negative windowBits implicitly.
  18244. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18245. * (each char code [0..255])
  18246. *
  18247. * ##### Example:
  18248. *
  18249. * ```javascript
  18250. * var pako = require('pako')
  18251. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  18252. *
  18253. * console.log(pako.deflate(data));
  18254. * ```
  18255. **/
  18256. function deflate(input, options) {
  18257. var deflator = new Deflate(options);
  18258. deflator.push(input, true);
  18259. // That will never happens, if you don't cheat with options :)
  18260. if (deflator.err) { throw deflator.msg; }
  18261. return deflator.result;
  18262. }
  18263. /**
  18264. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  18265. * - data (Uint8Array|Array|String): input data to compress.
  18266. * - options (Object): zlib deflate options.
  18267. *
  18268. * The same as [[deflate]], but creates raw data, without wrapper
  18269. * (header and adler32 crc).
  18270. **/
  18271. function deflateRaw(input, options) {
  18272. options = options || {};
  18273. options.raw = true;
  18274. return deflate(input, options);
  18275. }
  18276. /**
  18277. * gzip(data[, options]) -> Uint8Array|Array|String
  18278. * - data (Uint8Array|Array|String): input data to compress.
  18279. * - options (Object): zlib deflate options.
  18280. *
  18281. * The same as [[deflate]], but create gzip wrapper instead of
  18282. * deflate one.
  18283. **/
  18284. function gzip(input, options) {
  18285. options = options || {};
  18286. options.gzip = true;
  18287. return deflate(input, options);
  18288. }
  18289. exports.Deflate = Deflate;
  18290. exports.deflate = deflate;
  18291. exports.deflateRaw = deflateRaw;
  18292. exports.gzip = gzip;
  18293. },{"./utils/common":72,"./utils/strings":73,"./zlib/deflate.js":77,"./zlib/messages":82,"./zlib/zstream":84}],71:[function(require,module,exports){
  18294. 'use strict';
  18295. var zlib_inflate = require('./zlib/inflate.js');
  18296. var utils = require('./utils/common');
  18297. var strings = require('./utils/strings');
  18298. var c = require('./zlib/constants');
  18299. var msg = require('./zlib/messages');
  18300. var zstream = require('./zlib/zstream');
  18301. var gzheader = require('./zlib/gzheader');
  18302. var toString = Object.prototype.toString;
  18303. /**
  18304. * class Inflate
  18305. *
  18306. * Generic JS-style wrapper for zlib calls. If you don't need
  18307. * streaming behaviour - use more simple functions: [[inflate]]
  18308. * and [[inflateRaw]].
  18309. **/
  18310. /* internal
  18311. * inflate.chunks -> Array
  18312. *
  18313. * Chunks of output data, if [[Inflate#onData]] not overriden.
  18314. **/
  18315. /**
  18316. * Inflate.result -> Uint8Array|Array|String
  18317. *
  18318. * Uncompressed result, generated by default [[Inflate#onData]]
  18319. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  18320. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  18321. * push a chunk with explicit flush (call [[Inflate#push]] with
  18322. * `Z_SYNC_FLUSH` param).
  18323. **/
  18324. /**
  18325. * Inflate.err -> Number
  18326. *
  18327. * Error code after inflate finished. 0 (Z_OK) on success.
  18328. * Should be checked if broken data possible.
  18329. **/
  18330. /**
  18331. * Inflate.msg -> String
  18332. *
  18333. * Error message, if [[Inflate.err]] != 0
  18334. **/
  18335. /**
  18336. * new Inflate(options)
  18337. * - options (Object): zlib inflate options.
  18338. *
  18339. * Creates new inflator instance with specified params. Throws exception
  18340. * on bad params. Supported options:
  18341. *
  18342. * - `windowBits`
  18343. *
  18344. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18345. * for more information on these.
  18346. *
  18347. * Additional options, for internal needs:
  18348. *
  18349. * - `chunkSize` - size of generated data chunks (16K by default)
  18350. * - `raw` (Boolean) - do raw inflate
  18351. * - `to` (String) - if equal to 'string', then result will be converted
  18352. * from utf8 to utf16 (javascript) string. When string output requested,
  18353. * chunk length can differ from `chunkSize`, depending on content.
  18354. *
  18355. * By default, when no options set, autodetect deflate/gzip data format via
  18356. * wrapper header.
  18357. *
  18358. * ##### Example:
  18359. *
  18360. * ```javascript
  18361. * var pako = require('pako')
  18362. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18363. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18364. *
  18365. * var inflate = new pako.Inflate({ level: 3});
  18366. *
  18367. * inflate.push(chunk1, false);
  18368. * inflate.push(chunk2, true); // true -> last chunk
  18369. *
  18370. * if (inflate.err) { throw new Error(inflate.err); }
  18371. *
  18372. * console.log(inflate.result);
  18373. * ```
  18374. **/
  18375. var Inflate = function(options) {
  18376. this.options = utils.assign({
  18377. chunkSize: 16384,
  18378. windowBits: 0,
  18379. to: ''
  18380. }, options || {});
  18381. var opt = this.options;
  18382. // Force window size for `raw` data, if not set directly,
  18383. // because we have no header for autodetect.
  18384. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  18385. opt.windowBits = -opt.windowBits;
  18386. if (opt.windowBits === 0) { opt.windowBits = -15; }
  18387. }
  18388. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  18389. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  18390. !(options && options.windowBits)) {
  18391. opt.windowBits += 32;
  18392. }
  18393. // Gzip header has no info about windows size, we can do autodetect only
  18394. // for deflate. So, if window size not set, force it to max when gzip possible
  18395. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  18396. // bit 3 (16) -> gzipped data
  18397. // bit 4 (32) -> autodetect gzip/deflate
  18398. if ((opt.windowBits & 15) === 0) {
  18399. opt.windowBits |= 15;
  18400. }
  18401. }
  18402. this.err = 0; // error code, if happens (0 = Z_OK)
  18403. this.msg = ''; // error message
  18404. this.ended = false; // used to avoid multiple onEnd() calls
  18405. this.chunks = []; // chunks of compressed data
  18406. this.strm = new zstream();
  18407. this.strm.avail_out = 0;
  18408. var status = zlib_inflate.inflateInit2(
  18409. this.strm,
  18410. opt.windowBits
  18411. );
  18412. if (status !== c.Z_OK) {
  18413. throw new Error(msg[status]);
  18414. }
  18415. this.header = new gzheader();
  18416. zlib_inflate.inflateGetHeader(this.strm, this.header);
  18417. };
  18418. /**
  18419. * Inflate#push(data[, mode]) -> Boolean
  18420. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  18421. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18422. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18423. *
  18424. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  18425. * new output chunks. Returns `true` on success. The last data block must have
  18426. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  18427. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  18428. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  18429. *
  18430. * On fail call [[Inflate#onEnd]] with error code and return false.
  18431. *
  18432. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18433. * format is detected automatically). Also, don't skip last param and always
  18434. * use the same type in your code (boolean or number). That will improve JS speed.
  18435. *
  18436. * For regular `Array`-s make sure all elements are [0..255].
  18437. *
  18438. * ##### Example
  18439. *
  18440. * ```javascript
  18441. * push(chunk, false); // push one of data chunks
  18442. * ...
  18443. * push(chunk, true); // push last chunk
  18444. * ```
  18445. **/
  18446. Inflate.prototype.push = function(data, mode) {
  18447. var strm = this.strm;
  18448. var chunkSize = this.options.chunkSize;
  18449. var status, _mode;
  18450. var next_out_utf8, tail, utf8str;
  18451. if (this.ended) { return false; }
  18452. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  18453. // Convert data if needed
  18454. if (typeof data === 'string') {
  18455. // Only binary strings can be decompressed on practice
  18456. strm.input = strings.binstring2buf(data);
  18457. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18458. strm.input = new Uint8Array(data);
  18459. } else {
  18460. strm.input = data;
  18461. }
  18462. strm.next_in = 0;
  18463. strm.avail_in = strm.input.length;
  18464. do {
  18465. if (strm.avail_out === 0) {
  18466. strm.output = new utils.Buf8(chunkSize);
  18467. strm.next_out = 0;
  18468. strm.avail_out = chunkSize;
  18469. }
  18470. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  18471. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  18472. this.onEnd(status);
  18473. this.ended = true;
  18474. return false;
  18475. }
  18476. if (strm.next_out) {
  18477. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  18478. if (this.options.to === 'string') {
  18479. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  18480. tail = strm.next_out - next_out_utf8;
  18481. utf8str = strings.buf2string(strm.output, next_out_utf8);
  18482. // move tail
  18483. strm.next_out = tail;
  18484. strm.avail_out = chunkSize - tail;
  18485. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  18486. this.onData(utf8str);
  18487. } else {
  18488. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18489. }
  18490. }
  18491. }
  18492. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  18493. if (status === c.Z_STREAM_END) {
  18494. _mode = c.Z_FINISH;
  18495. }
  18496. // Finalize on the last chunk.
  18497. if (_mode === c.Z_FINISH) {
  18498. status = zlib_inflate.inflateEnd(this.strm);
  18499. this.onEnd(status);
  18500. this.ended = true;
  18501. return status === c.Z_OK;
  18502. }
  18503. // callback interim results if Z_SYNC_FLUSH.
  18504. if (_mode === c.Z_SYNC_FLUSH) {
  18505. this.onEnd(c.Z_OK);
  18506. strm.avail_out = 0;
  18507. return true;
  18508. }
  18509. return true;
  18510. };
  18511. /**
  18512. * Inflate#onData(chunk) -> Void
  18513. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18514. * on js engine support. When string output requested, each chunk
  18515. * will be string.
  18516. *
  18517. * By default, stores data blocks in `chunks[]` property and glue
  18518. * those in `onEnd`. Override this handler, if you need another behaviour.
  18519. **/
  18520. Inflate.prototype.onData = function(chunk) {
  18521. this.chunks.push(chunk);
  18522. };
  18523. /**
  18524. * Inflate#onEnd(status) -> Void
  18525. * - status (Number): inflate status. 0 (Z_OK) on success,
  18526. * other if not.
  18527. *
  18528. * Called either after you tell inflate that the input stream is
  18529. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  18530. * or if an error happened. By default - join collected chunks,
  18531. * free memory and fill `results` / `err` properties.
  18532. **/
  18533. Inflate.prototype.onEnd = function(status) {
  18534. // On success - join
  18535. if (status === c.Z_OK) {
  18536. if (this.options.to === 'string') {
  18537. // Glue & convert here, until we teach pako to send
  18538. // utf8 alligned strings to onData
  18539. this.result = this.chunks.join('');
  18540. } else {
  18541. this.result = utils.flattenChunks(this.chunks);
  18542. }
  18543. }
  18544. this.chunks = [];
  18545. this.err = status;
  18546. this.msg = this.strm.msg;
  18547. };
  18548. /**
  18549. * inflate(data[, options]) -> Uint8Array|Array|String
  18550. * - data (Uint8Array|Array|String): input data to decompress.
  18551. * - options (Object): zlib inflate options.
  18552. *
  18553. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  18554. * format via wrapper header by default. That's why we don't provide
  18555. * separate `ungzip` method.
  18556. *
  18557. * Supported options are:
  18558. *
  18559. * - windowBits
  18560. *
  18561. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18562. * for more information.
  18563. *
  18564. * Sugar (options):
  18565. *
  18566. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  18567. * negative windowBits implicitly.
  18568. * - `to` (String) - if equal to 'string', then result will be converted
  18569. * from utf8 to utf16 (javascript) string. When string output requested,
  18570. * chunk length can differ from `chunkSize`, depending on content.
  18571. *
  18572. *
  18573. * ##### Example:
  18574. *
  18575. * ```javascript
  18576. * var pako = require('pako')
  18577. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  18578. * , output;
  18579. *
  18580. * try {
  18581. * output = pako.inflate(input);
  18582. * } catch (err)
  18583. * console.log(err);
  18584. * }
  18585. * ```
  18586. **/
  18587. function inflate(input, options) {
  18588. var inflator = new Inflate(options);
  18589. inflator.push(input, true);
  18590. // That will never happens, if you don't cheat with options :)
  18591. if (inflator.err) { throw inflator.msg; }
  18592. return inflator.result;
  18593. }
  18594. /**
  18595. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  18596. * - data (Uint8Array|Array|String): input data to decompress.
  18597. * - options (Object): zlib inflate options.
  18598. *
  18599. * The same as [[inflate]], but creates raw data, without wrapper
  18600. * (header and adler32 crc).
  18601. **/
  18602. function inflateRaw(input, options) {
  18603. options = options || {};
  18604. options.raw = true;
  18605. return inflate(input, options);
  18606. }
  18607. /**
  18608. * ungzip(data[, options]) -> Uint8Array|Array|String
  18609. * - data (Uint8Array|Array|String): input data to decompress.
  18610. * - options (Object): zlib inflate options.
  18611. *
  18612. * Just shortcut to [[inflate]], because it autodetects format
  18613. * by header.content. Done for convenience.
  18614. **/
  18615. exports.Inflate = Inflate;
  18616. exports.inflate = inflate;
  18617. exports.inflateRaw = inflateRaw;
  18618. exports.ungzip = inflate;
  18619. },{"./utils/common":72,"./utils/strings":73,"./zlib/constants":75,"./zlib/gzheader":78,"./zlib/inflate.js":80,"./zlib/messages":82,"./zlib/zstream":84}],72:[function(require,module,exports){
  18620. 'use strict';
  18621. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  18622. (typeof Uint16Array !== 'undefined') &&
  18623. (typeof Int32Array !== 'undefined');
  18624. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  18625. var sources = Array.prototype.slice.call(arguments, 1);
  18626. while (sources.length) {
  18627. var source = sources.shift();
  18628. if (!source) { continue; }
  18629. if (typeof source !== 'object') {
  18630. throw new TypeError(source + 'must be non-object');
  18631. }
  18632. for (var p in source) {
  18633. if (source.hasOwnProperty(p)) {
  18634. obj[p] = source[p];
  18635. }
  18636. }
  18637. }
  18638. return obj;
  18639. };
  18640. // reduce buffer size, avoiding mem copy
  18641. exports.shrinkBuf = function (buf, size) {
  18642. if (buf.length === size) { return buf; }
  18643. if (buf.subarray) { return buf.subarray(0, size); }
  18644. buf.length = size;
  18645. return buf;
  18646. };
  18647. var fnTyped = {
  18648. arraySet: function (dest, src, src_offs, len, dest_offs) {
  18649. if (src.subarray && dest.subarray) {
  18650. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  18651. return;
  18652. }
  18653. // Fallback to ordinary array
  18654. for (var i=0; i<len; i++) {
  18655. dest[dest_offs + i] = src[src_offs + i];
  18656. }
  18657. },
  18658. // Join array of chunks to single array.
  18659. flattenChunks: function(chunks) {
  18660. var i, l, len, pos, chunk, result;
  18661. // calculate data length
  18662. len = 0;
  18663. for (i=0, l=chunks.length; i<l; i++) {
  18664. len += chunks[i].length;
  18665. }
  18666. // join chunks
  18667. result = new Uint8Array(len);
  18668. pos = 0;
  18669. for (i=0, l=chunks.length; i<l; i++) {
  18670. chunk = chunks[i];
  18671. result.set(chunk, pos);
  18672. pos += chunk.length;
  18673. }
  18674. return result;
  18675. }
  18676. };
  18677. var fnUntyped = {
  18678. arraySet: function (dest, src, src_offs, len, dest_offs) {
  18679. for (var i=0; i<len; i++) {
  18680. dest[dest_offs + i] = src[src_offs + i];
  18681. }
  18682. },
  18683. // Join array of chunks to single array.
  18684. flattenChunks: function(chunks) {
  18685. return [].concat.apply([], chunks);
  18686. }
  18687. };
  18688. // Enable/Disable typed arrays use, for testing
  18689. //
  18690. exports.setTyped = function (on) {
  18691. if (on) {
  18692. exports.Buf8 = Uint8Array;
  18693. exports.Buf16 = Uint16Array;
  18694. exports.Buf32 = Int32Array;
  18695. exports.assign(exports, fnTyped);
  18696. } else {
  18697. exports.Buf8 = Array;
  18698. exports.Buf16 = Array;
  18699. exports.Buf32 = Array;
  18700. exports.assign(exports, fnUntyped);
  18701. }
  18702. };
  18703. exports.setTyped(TYPED_OK);
  18704. },{}],73:[function(require,module,exports){
  18705. // String encode/decode helpers
  18706. 'use strict';
  18707. var utils = require('./common');
  18708. // Quick check if we can use fast array to bin string conversion
  18709. //
  18710. // - apply(Array) can fail on Android 2.2
  18711. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  18712. //
  18713. var STR_APPLY_OK = true;
  18714. var STR_APPLY_UIA_OK = true;
  18715. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  18716. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  18717. // Table with utf8 lengths (calculated by first byte of sequence)
  18718. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  18719. // because max possible codepoint is 0x10ffff
  18720. var _utf8len = new utils.Buf8(256);
  18721. for (var q=0; q<256; q++) {
  18722. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  18723. }
  18724. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  18725. // convert string to array (typed, when possible)
  18726. exports.string2buf = function (str) {
  18727. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  18728. // count binary size
  18729. for (m_pos = 0; m_pos < str_len; m_pos++) {
  18730. c = str.charCodeAt(m_pos);
  18731. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  18732. c2 = str.charCodeAt(m_pos+1);
  18733. if ((c2 & 0xfc00) === 0xdc00) {
  18734. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  18735. m_pos++;
  18736. }
  18737. }
  18738. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  18739. }
  18740. // allocate buffer
  18741. buf = new utils.Buf8(buf_len);
  18742. // convert
  18743. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  18744. c = str.charCodeAt(m_pos);
  18745. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  18746. c2 = str.charCodeAt(m_pos+1);
  18747. if ((c2 & 0xfc00) === 0xdc00) {
  18748. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  18749. m_pos++;
  18750. }
  18751. }
  18752. if (c < 0x80) {
  18753. /* one byte */
  18754. buf[i++] = c;
  18755. } else if (c < 0x800) {
  18756. /* two bytes */
  18757. buf[i++] = 0xC0 | (c >>> 6);
  18758. buf[i++] = 0x80 | (c & 0x3f);
  18759. } else if (c < 0x10000) {
  18760. /* three bytes */
  18761. buf[i++] = 0xE0 | (c >>> 12);
  18762. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  18763. buf[i++] = 0x80 | (c & 0x3f);
  18764. } else {
  18765. /* four bytes */
  18766. buf[i++] = 0xf0 | (c >>> 18);
  18767. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  18768. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  18769. buf[i++] = 0x80 | (c & 0x3f);
  18770. }
  18771. }
  18772. return buf;
  18773. };
  18774. // Helper (used in 2 places)
  18775. function buf2binstring(buf, len) {
  18776. // use fallback for big arrays to avoid stack overflow
  18777. if (len < 65537) {
  18778. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  18779. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  18780. }
  18781. }
  18782. var result = '';
  18783. for (var i=0; i < len; i++) {
  18784. result += String.fromCharCode(buf[i]);
  18785. }
  18786. return result;
  18787. }
  18788. // Convert byte array to binary string
  18789. exports.buf2binstring = function(buf) {
  18790. return buf2binstring(buf, buf.length);
  18791. };
  18792. // Convert binary string (typed, when possible)
  18793. exports.binstring2buf = function(str) {
  18794. var buf = new utils.Buf8(str.length);
  18795. for (var i=0, len=buf.length; i < len; i++) {
  18796. buf[i] = str.charCodeAt(i);
  18797. }
  18798. return buf;
  18799. };
  18800. // convert array to string
  18801. exports.buf2string = function (buf, max) {
  18802. var i, out, c, c_len;
  18803. var len = max || buf.length;
  18804. // Reserve max possible length (2 words per char)
  18805. // NB: by unknown reasons, Array is significantly faster for
  18806. // String.fromCharCode.apply than Uint16Array.
  18807. var utf16buf = new Array(len*2);
  18808. for (out=0, i=0; i<len;) {
  18809. c = buf[i++];
  18810. // quick process ascii
  18811. if (c < 0x80) { utf16buf[out++] = c; continue; }
  18812. c_len = _utf8len[c];
  18813. // skip 5 & 6 byte codes
  18814. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  18815. // apply mask on first byte
  18816. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  18817. // join the rest
  18818. while (c_len > 1 && i < len) {
  18819. c = (c << 6) | (buf[i++] & 0x3f);
  18820. c_len--;
  18821. }
  18822. // terminated by end of string?
  18823. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  18824. if (c < 0x10000) {
  18825. utf16buf[out++] = c;
  18826. } else {
  18827. c -= 0x10000;
  18828. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  18829. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  18830. }
  18831. }
  18832. return buf2binstring(utf16buf, out);
  18833. };
  18834. // Calculate max possible position in utf8 buffer,
  18835. // that will not break sequence. If that's not possible
  18836. // - (very small limits) return max size as is.
  18837. //
  18838. // buf[] - utf8 bytes array
  18839. // max - length limit (mandatory);
  18840. exports.utf8border = function(buf, max) {
  18841. var pos;
  18842. max = max || buf.length;
  18843. if (max > buf.length) { max = buf.length; }
  18844. // go back from last position, until start of sequence found
  18845. pos = max-1;
  18846. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  18847. // Fuckup - very small and broken sequence,
  18848. // return max, because we should return something anyway.
  18849. if (pos < 0) { return max; }
  18850. // If we came to start of buffer - that means vuffer is too small,
  18851. // return max too.
  18852. if (pos === 0) { return max; }
  18853. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  18854. };
  18855. },{"./common":72}],74:[function(require,module,exports){
  18856. 'use strict';
  18857. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  18858. // It doesn't worth to make additional optimizationa as in original.
  18859. // Small size is preferable.
  18860. function adler32(adler, buf, len, pos) {
  18861. var s1 = (adler & 0xffff) |0,
  18862. s2 = ((adler >>> 16) & 0xffff) |0,
  18863. n = 0;
  18864. while (len !== 0) {
  18865. // Set limit ~ twice less than 5552, to keep
  18866. // s2 in 31-bits, because we force signed ints.
  18867. // in other case %= will fail.
  18868. n = len > 2000 ? 2000 : len;
  18869. len -= n;
  18870. do {
  18871. s1 = (s1 + buf[pos++]) |0;
  18872. s2 = (s2 + s1) |0;
  18873. } while (--n);
  18874. s1 %= 65521;
  18875. s2 %= 65521;
  18876. }
  18877. return (s1 | (s2 << 16)) |0;
  18878. }
  18879. module.exports = adler32;
  18880. },{}],75:[function(require,module,exports){
  18881. module.exports = {
  18882. /* Allowed flush values; see deflate() and inflate() below for details */
  18883. Z_NO_FLUSH: 0,
  18884. Z_PARTIAL_FLUSH: 1,
  18885. Z_SYNC_FLUSH: 2,
  18886. Z_FULL_FLUSH: 3,
  18887. Z_FINISH: 4,
  18888. Z_BLOCK: 5,
  18889. Z_TREES: 6,
  18890. /* Return codes for the compression/decompression functions. Negative values
  18891. * are errors, positive values are used for special but normal events.
  18892. */
  18893. Z_OK: 0,
  18894. Z_STREAM_END: 1,
  18895. Z_NEED_DICT: 2,
  18896. Z_ERRNO: -1,
  18897. Z_STREAM_ERROR: -2,
  18898. Z_DATA_ERROR: -3,
  18899. //Z_MEM_ERROR: -4,
  18900. Z_BUF_ERROR: -5,
  18901. //Z_VERSION_ERROR: -6,
  18902. /* compression levels */
  18903. Z_NO_COMPRESSION: 0,
  18904. Z_BEST_SPEED: 1,
  18905. Z_BEST_COMPRESSION: 9,
  18906. Z_DEFAULT_COMPRESSION: -1,
  18907. Z_FILTERED: 1,
  18908. Z_HUFFMAN_ONLY: 2,
  18909. Z_RLE: 3,
  18910. Z_FIXED: 4,
  18911. Z_DEFAULT_STRATEGY: 0,
  18912. /* Possible values of the data_type field (though see inflate()) */
  18913. Z_BINARY: 0,
  18914. Z_TEXT: 1,
  18915. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  18916. Z_UNKNOWN: 2,
  18917. /* The deflate compression method */
  18918. Z_DEFLATED: 8
  18919. //Z_NULL: null // Use -1 or null inline, depending on var type
  18920. };
  18921. },{}],76:[function(require,module,exports){
  18922. 'use strict';
  18923. // Note: we can't get significant speed boost here.
  18924. // So write code to minimize size - no pregenerated tables
  18925. // and array tools dependencies.
  18926. // Use ordinary array, since untyped makes no boost here
  18927. function makeTable() {
  18928. var c, table = [];
  18929. for (var n =0; n < 256; n++) {
  18930. c = n;
  18931. for (var k =0; k < 8; k++) {
  18932. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  18933. }
  18934. table[n] = c;
  18935. }
  18936. return table;
  18937. }
  18938. // Create table on load. Just 255 signed longs. Not a problem.
  18939. var crcTable = makeTable();
  18940. function crc32(crc, buf, len, pos) {
  18941. var t = crcTable,
  18942. end = pos + len;
  18943. crc = crc ^ (-1);
  18944. for (var i = pos; i < end; i++) {
  18945. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  18946. }
  18947. return (crc ^ (-1)); // >>> 0;
  18948. }
  18949. module.exports = crc32;
  18950. },{}],77:[function(require,module,exports){
  18951. 'use strict';
  18952. var utils = require('../utils/common');
  18953. var trees = require('./trees');
  18954. var adler32 = require('./adler32');
  18955. var crc32 = require('./crc32');
  18956. var msg = require('./messages');
  18957. /* Public constants ==========================================================*/
  18958. /* ===========================================================================*/
  18959. /* Allowed flush values; see deflate() and inflate() below for details */
  18960. var Z_NO_FLUSH = 0;
  18961. var Z_PARTIAL_FLUSH = 1;
  18962. //var Z_SYNC_FLUSH = 2;
  18963. var Z_FULL_FLUSH = 3;
  18964. var Z_FINISH = 4;
  18965. var Z_BLOCK = 5;
  18966. //var Z_TREES = 6;
  18967. /* Return codes for the compression/decompression functions. Negative values
  18968. * are errors, positive values are used for special but normal events.
  18969. */
  18970. var Z_OK = 0;
  18971. var Z_STREAM_END = 1;
  18972. //var Z_NEED_DICT = 2;
  18973. //var Z_ERRNO = -1;
  18974. var Z_STREAM_ERROR = -2;
  18975. var Z_DATA_ERROR = -3;
  18976. //var Z_MEM_ERROR = -4;
  18977. var Z_BUF_ERROR = -5;
  18978. //var Z_VERSION_ERROR = -6;
  18979. /* compression levels */
  18980. //var Z_NO_COMPRESSION = 0;
  18981. //var Z_BEST_SPEED = 1;
  18982. //var Z_BEST_COMPRESSION = 9;
  18983. var Z_DEFAULT_COMPRESSION = -1;
  18984. var Z_FILTERED = 1;
  18985. var Z_HUFFMAN_ONLY = 2;
  18986. var Z_RLE = 3;
  18987. var Z_FIXED = 4;
  18988. var Z_DEFAULT_STRATEGY = 0;
  18989. /* Possible values of the data_type field (though see inflate()) */
  18990. //var Z_BINARY = 0;
  18991. //var Z_TEXT = 1;
  18992. //var Z_ASCII = 1; // = Z_TEXT
  18993. var Z_UNKNOWN = 2;
  18994. /* The deflate compression method */
  18995. var Z_DEFLATED = 8;
  18996. /*============================================================================*/
  18997. var MAX_MEM_LEVEL = 9;
  18998. /* Maximum value for memLevel in deflateInit2 */
  18999. var MAX_WBITS = 15;
  19000. /* 32K LZ77 window */
  19001. var DEF_MEM_LEVEL = 8;
  19002. var LENGTH_CODES = 29;
  19003. /* number of length codes, not counting the special END_BLOCK code */
  19004. var LITERALS = 256;
  19005. /* number of literal bytes 0..255 */
  19006. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19007. /* number of Literal or Length codes, including the END_BLOCK code */
  19008. var D_CODES = 30;
  19009. /* number of distance codes */
  19010. var BL_CODES = 19;
  19011. /* number of codes used to transfer the bit lengths */
  19012. var HEAP_SIZE = 2*L_CODES + 1;
  19013. /* maximum heap size */
  19014. var MAX_BITS = 15;
  19015. /* All codes must not exceed MAX_BITS bits */
  19016. var MIN_MATCH = 3;
  19017. var MAX_MATCH = 258;
  19018. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  19019. var PRESET_DICT = 0x20;
  19020. var INIT_STATE = 42;
  19021. var EXTRA_STATE = 69;
  19022. var NAME_STATE = 73;
  19023. var COMMENT_STATE = 91;
  19024. var HCRC_STATE = 103;
  19025. var BUSY_STATE = 113;
  19026. var FINISH_STATE = 666;
  19027. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  19028. var BS_BLOCK_DONE = 2; /* block flush performed */
  19029. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  19030. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  19031. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  19032. function err(strm, errorCode) {
  19033. strm.msg = msg[errorCode];
  19034. return errorCode;
  19035. }
  19036. function rank(f) {
  19037. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  19038. }
  19039. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19040. /* =========================================================================
  19041. * Flush as much pending output as possible. All deflate() output goes
  19042. * through this function so some applications may wish to modify it
  19043. * to avoid allocating a large strm->output buffer and copying into it.
  19044. * (See also read_buf()).
  19045. */
  19046. function flush_pending(strm) {
  19047. var s = strm.state;
  19048. //_tr_flush_bits(s);
  19049. var len = s.pending;
  19050. if (len > strm.avail_out) {
  19051. len = strm.avail_out;
  19052. }
  19053. if (len === 0) { return; }
  19054. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  19055. strm.next_out += len;
  19056. s.pending_out += len;
  19057. strm.total_out += len;
  19058. strm.avail_out -= len;
  19059. s.pending -= len;
  19060. if (s.pending === 0) {
  19061. s.pending_out = 0;
  19062. }
  19063. }
  19064. function flush_block_only (s, last) {
  19065. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  19066. s.block_start = s.strstart;
  19067. flush_pending(s.strm);
  19068. }
  19069. function put_byte(s, b) {
  19070. s.pending_buf[s.pending++] = b;
  19071. }
  19072. /* =========================================================================
  19073. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  19074. * IN assertion: the stream state is correct and there is enough room in
  19075. * pending_buf.
  19076. */
  19077. function putShortMSB(s, b) {
  19078. // put_byte(s, (Byte)(b >> 8));
  19079. // put_byte(s, (Byte)(b & 0xff));
  19080. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  19081. s.pending_buf[s.pending++] = b & 0xff;
  19082. }
  19083. /* ===========================================================================
  19084. * Read a new buffer from the current input stream, update the adler32
  19085. * and total number of bytes read. All deflate() input goes through
  19086. * this function so some applications may wish to modify it to avoid
  19087. * allocating a large strm->input buffer and copying from it.
  19088. * (See also flush_pending()).
  19089. */
  19090. function read_buf(strm, buf, start, size) {
  19091. var len = strm.avail_in;
  19092. if (len > size) { len = size; }
  19093. if (len === 0) { return 0; }
  19094. strm.avail_in -= len;
  19095. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  19096. if (strm.state.wrap === 1) {
  19097. strm.adler = adler32(strm.adler, buf, len, start);
  19098. }
  19099. else if (strm.state.wrap === 2) {
  19100. strm.adler = crc32(strm.adler, buf, len, start);
  19101. }
  19102. strm.next_in += len;
  19103. strm.total_in += len;
  19104. return len;
  19105. }
  19106. /* ===========================================================================
  19107. * Set match_start to the longest match starting at the given string and
  19108. * return its length. Matches shorter or equal to prev_length are discarded,
  19109. * in which case the result is equal to prev_length and match_start is
  19110. * garbage.
  19111. * IN assertions: cur_match is the head of the hash chain for the current
  19112. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  19113. * OUT assertion: the match length is not greater than s->lookahead.
  19114. */
  19115. function longest_match(s, cur_match) {
  19116. var chain_length = s.max_chain_length; /* max hash chain length */
  19117. var scan = s.strstart; /* current string */
  19118. var match; /* matched string */
  19119. var len; /* length of current match */
  19120. var best_len = s.prev_length; /* best match length so far */
  19121. var nice_match = s.nice_match; /* stop if match long enough */
  19122. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  19123. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  19124. var _win = s.window; // shortcut
  19125. var wmask = s.w_mask;
  19126. var prev = s.prev;
  19127. /* Stop when cur_match becomes <= limit. To simplify the code,
  19128. * we prevent matches with the string of window index 0.
  19129. */
  19130. var strend = s.strstart + MAX_MATCH;
  19131. var scan_end1 = _win[scan + best_len - 1];
  19132. var scan_end = _win[scan + best_len];
  19133. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  19134. * It is easy to get rid of this optimization if necessary.
  19135. */
  19136. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  19137. /* Do not waste too much time if we already have a good match: */
  19138. if (s.prev_length >= s.good_match) {
  19139. chain_length >>= 2;
  19140. }
  19141. /* Do not look for matches beyond the end of the input. This is necessary
  19142. * to make deflate deterministic.
  19143. */
  19144. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  19145. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  19146. do {
  19147. // Assert(cur_match < s->strstart, "no future");
  19148. match = cur_match;
  19149. /* Skip to next match if the match length cannot increase
  19150. * or if the match length is less than 2. Note that the checks below
  19151. * for insufficient lookahead only occur occasionally for performance
  19152. * reasons. Therefore uninitialized memory will be accessed, and
  19153. * conditional jumps will be made that depend on those values.
  19154. * However the length of the match is limited to the lookahead, so
  19155. * the output of deflate is not affected by the uninitialized values.
  19156. */
  19157. if (_win[match + best_len] !== scan_end ||
  19158. _win[match + best_len - 1] !== scan_end1 ||
  19159. _win[match] !== _win[scan] ||
  19160. _win[++match] !== _win[scan + 1]) {
  19161. continue;
  19162. }
  19163. /* The check at best_len-1 can be removed because it will be made
  19164. * again later. (This heuristic is not always a win.)
  19165. * It is not necessary to compare scan[2] and match[2] since they
  19166. * are always equal when the other bytes match, given that
  19167. * the hash keys are equal and that HASH_BITS >= 8.
  19168. */
  19169. scan += 2;
  19170. match++;
  19171. // Assert(*scan == *match, "match[2]?");
  19172. /* We check for insufficient lookahead only every 8th comparison;
  19173. * the 256th check will be made at strstart+258.
  19174. */
  19175. do {
  19176. /*jshint noempty:false*/
  19177. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19178. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19179. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19180. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19181. scan < strend);
  19182. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  19183. len = MAX_MATCH - (strend - scan);
  19184. scan = strend - MAX_MATCH;
  19185. if (len > best_len) {
  19186. s.match_start = cur_match;
  19187. best_len = len;
  19188. if (len >= nice_match) {
  19189. break;
  19190. }
  19191. scan_end1 = _win[scan + best_len - 1];
  19192. scan_end = _win[scan + best_len];
  19193. }
  19194. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  19195. if (best_len <= s.lookahead) {
  19196. return best_len;
  19197. }
  19198. return s.lookahead;
  19199. }
  19200. /* ===========================================================================
  19201. * Fill the window when the lookahead becomes insufficient.
  19202. * Updates strstart and lookahead.
  19203. *
  19204. * IN assertion: lookahead < MIN_LOOKAHEAD
  19205. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  19206. * At least one byte has been read, or avail_in == 0; reads are
  19207. * performed for at least two bytes (required for the zip translate_eol
  19208. * option -- not supported here).
  19209. */
  19210. function fill_window(s) {
  19211. var _w_size = s.w_size;
  19212. var p, n, m, more, str;
  19213. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  19214. do {
  19215. more = s.window_size - s.lookahead - s.strstart;
  19216. // JS ints have 32 bit, block below not needed
  19217. /* Deal with !@#$% 64K limit: */
  19218. //if (sizeof(int) <= 2) {
  19219. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  19220. // more = wsize;
  19221. //
  19222. // } else if (more == (unsigned)(-1)) {
  19223. // /* Very unlikely, but possible on 16 bit machine if
  19224. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  19225. // */
  19226. // more--;
  19227. // }
  19228. //}
  19229. /* If the window is almost full and there is insufficient lookahead,
  19230. * move the upper half to the lower one to make room in the upper half.
  19231. */
  19232. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  19233. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  19234. s.match_start -= _w_size;
  19235. s.strstart -= _w_size;
  19236. /* we now have strstart >= MAX_DIST */
  19237. s.block_start -= _w_size;
  19238. /* Slide the hash table (could be avoided with 32 bit values
  19239. at the expense of memory usage). We slide even when level == 0
  19240. to keep the hash table consistent if we switch back to level > 0
  19241. later. (Using level 0 permanently is not an optimal usage of
  19242. zlib, so we don't care about this pathological case.)
  19243. */
  19244. n = s.hash_size;
  19245. p = n;
  19246. do {
  19247. m = s.head[--p];
  19248. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  19249. } while (--n);
  19250. n = _w_size;
  19251. p = n;
  19252. do {
  19253. m = s.prev[--p];
  19254. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  19255. /* If n is not on any hash chain, prev[n] is garbage but
  19256. * its value will never be used.
  19257. */
  19258. } while (--n);
  19259. more += _w_size;
  19260. }
  19261. if (s.strm.avail_in === 0) {
  19262. break;
  19263. }
  19264. /* If there was no sliding:
  19265. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  19266. * more == window_size - lookahead - strstart
  19267. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  19268. * => more >= window_size - 2*WSIZE + 2
  19269. * In the BIG_MEM or MMAP case (not yet supported),
  19270. * window_size == input_size + MIN_LOOKAHEAD &&
  19271. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  19272. * Otherwise, window_size == 2*WSIZE so more >= 2.
  19273. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  19274. */
  19275. //Assert(more >= 2, "more < 2");
  19276. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  19277. s.lookahead += n;
  19278. /* Initialize the hash value now that we have some input: */
  19279. if (s.lookahead + s.insert >= MIN_MATCH) {
  19280. str = s.strstart - s.insert;
  19281. s.ins_h = s.window[str];
  19282. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  19283. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  19284. //#if MIN_MATCH != 3
  19285. // Call update_hash() MIN_MATCH-3 more times
  19286. //#endif
  19287. while (s.insert) {
  19288. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  19289. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  19290. s.prev[str & s.w_mask] = s.head[s.ins_h];
  19291. s.head[s.ins_h] = str;
  19292. str++;
  19293. s.insert--;
  19294. if (s.lookahead + s.insert < MIN_MATCH) {
  19295. break;
  19296. }
  19297. }
  19298. }
  19299. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  19300. * but this is not important since only literal bytes will be emitted.
  19301. */
  19302. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  19303. /* If the WIN_INIT bytes after the end of the current data have never been
  19304. * written, then zero those bytes in order to avoid memory check reports of
  19305. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  19306. * the longest match routines. Update the high water mark for the next
  19307. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  19308. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  19309. */
  19310. // if (s.high_water < s.window_size) {
  19311. // var curr = s.strstart + s.lookahead;
  19312. // var init = 0;
  19313. //
  19314. // if (s.high_water < curr) {
  19315. // /* Previous high water mark below current data -- zero WIN_INIT
  19316. // * bytes or up to end of window, whichever is less.
  19317. // */
  19318. // init = s.window_size - curr;
  19319. // if (init > WIN_INIT)
  19320. // init = WIN_INIT;
  19321. // zmemzero(s->window + curr, (unsigned)init);
  19322. // s->high_water = curr + init;
  19323. // }
  19324. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  19325. // /* High water mark at or above current data, but below current data
  19326. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  19327. // * to end of window, whichever is less.
  19328. // */
  19329. // init = (ulg)curr + WIN_INIT - s->high_water;
  19330. // if (init > s->window_size - s->high_water)
  19331. // init = s->window_size - s->high_water;
  19332. // zmemzero(s->window + s->high_water, (unsigned)init);
  19333. // s->high_water += init;
  19334. // }
  19335. // }
  19336. //
  19337. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  19338. // "not enough room for search");
  19339. }
  19340. /* ===========================================================================
  19341. * Copy without compression as much as possible from the input stream, return
  19342. * the current block state.
  19343. * This function does not insert new strings in the dictionary since
  19344. * uncompressible data is probably not useful. This function is used
  19345. * only for the level=0 compression option.
  19346. * NOTE: this function should be optimized to avoid extra copying from
  19347. * window to pending_buf.
  19348. */
  19349. function deflate_stored(s, flush) {
  19350. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  19351. * to pending_buf_size, and each stored block has a 5 byte header:
  19352. */
  19353. var max_block_size = 0xffff;
  19354. if (max_block_size > s.pending_buf_size - 5) {
  19355. max_block_size = s.pending_buf_size - 5;
  19356. }
  19357. /* Copy as much as possible from input to output: */
  19358. for (;;) {
  19359. /* Fill the window as much as possible: */
  19360. if (s.lookahead <= 1) {
  19361. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  19362. // s->block_start >= (long)s->w_size, "slide too late");
  19363. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  19364. // s.block_start >= s.w_size)) {
  19365. // throw new Error("slide too late");
  19366. // }
  19367. fill_window(s);
  19368. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  19369. return BS_NEED_MORE;
  19370. }
  19371. if (s.lookahead === 0) {
  19372. break;
  19373. }
  19374. /* flush the current block */
  19375. }
  19376. //Assert(s->block_start >= 0L, "block gone");
  19377. // if (s.block_start < 0) throw new Error("block gone");
  19378. s.strstart += s.lookahead;
  19379. s.lookahead = 0;
  19380. /* Emit a stored block if pending_buf will be full: */
  19381. var max_start = s.block_start + max_block_size;
  19382. if (s.strstart === 0 || s.strstart >= max_start) {
  19383. /* strstart == 0 is possible when wraparound on 16-bit machine */
  19384. s.lookahead = s.strstart - max_start;
  19385. s.strstart = max_start;
  19386. /*** FLUSH_BLOCK(s, 0); ***/
  19387. flush_block_only(s, false);
  19388. if (s.strm.avail_out === 0) {
  19389. return BS_NEED_MORE;
  19390. }
  19391. /***/
  19392. }
  19393. /* Flush if we may have to slide, otherwise block_start may become
  19394. * negative and the data will be gone:
  19395. */
  19396. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  19397. /*** FLUSH_BLOCK(s, 0); ***/
  19398. flush_block_only(s, false);
  19399. if (s.strm.avail_out === 0) {
  19400. return BS_NEED_MORE;
  19401. }
  19402. /***/
  19403. }
  19404. }
  19405. s.insert = 0;
  19406. if (flush === Z_FINISH) {
  19407. /*** FLUSH_BLOCK(s, 1); ***/
  19408. flush_block_only(s, true);
  19409. if (s.strm.avail_out === 0) {
  19410. return BS_FINISH_STARTED;
  19411. }
  19412. /***/
  19413. return BS_FINISH_DONE;
  19414. }
  19415. if (s.strstart > s.block_start) {
  19416. /*** FLUSH_BLOCK(s, 0); ***/
  19417. flush_block_only(s, false);
  19418. if (s.strm.avail_out === 0) {
  19419. return BS_NEED_MORE;
  19420. }
  19421. /***/
  19422. }
  19423. return BS_NEED_MORE;
  19424. }
  19425. /* ===========================================================================
  19426. * Compress as much as possible from the input stream, return the current
  19427. * block state.
  19428. * This function does not perform lazy evaluation of matches and inserts
  19429. * new strings in the dictionary only for unmatched strings or for short
  19430. * matches. It is used only for the fast compression options.
  19431. */
  19432. function deflate_fast(s, flush) {
  19433. var hash_head; /* head of the hash chain */
  19434. var bflush; /* set if current block must be flushed */
  19435. for (;;) {
  19436. /* Make sure that we always have enough lookahead, except
  19437. * at the end of the input file. We need MAX_MATCH bytes
  19438. * for the next match, plus MIN_MATCH bytes to insert the
  19439. * string following the next match.
  19440. */
  19441. if (s.lookahead < MIN_LOOKAHEAD) {
  19442. fill_window(s);
  19443. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  19444. return BS_NEED_MORE;
  19445. }
  19446. if (s.lookahead === 0) {
  19447. break; /* flush the current block */
  19448. }
  19449. }
  19450. /* Insert the string window[strstart .. strstart+2] in the
  19451. * dictionary, and set hash_head to the head of the hash chain:
  19452. */
  19453. hash_head = 0/*NIL*/;
  19454. if (s.lookahead >= MIN_MATCH) {
  19455. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19456. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19457. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19458. s.head[s.ins_h] = s.strstart;
  19459. /***/
  19460. }
  19461. /* Find the longest match, discarding those <= prev_length.
  19462. * At this point we have always match_length < MIN_MATCH
  19463. */
  19464. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  19465. /* To simplify the code, we prevent matches with the string
  19466. * of window index 0 (in particular we have to avoid a match
  19467. * of the string with itself at the start of the input file).
  19468. */
  19469. s.match_length = longest_match(s, hash_head);
  19470. /* longest_match() sets match_start */
  19471. }
  19472. if (s.match_length >= MIN_MATCH) {
  19473. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  19474. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  19475. s.match_length - MIN_MATCH, bflush); ***/
  19476. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  19477. s.lookahead -= s.match_length;
  19478. /* Insert new strings in the hash table only if the match length
  19479. * is not too large. This saves time but degrades compression.
  19480. */
  19481. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  19482. s.match_length--; /* string at strstart already in table */
  19483. do {
  19484. s.strstart++;
  19485. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19486. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19487. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19488. s.head[s.ins_h] = s.strstart;
  19489. /***/
  19490. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  19491. * always MIN_MATCH bytes ahead.
  19492. */
  19493. } while (--s.match_length !== 0);
  19494. s.strstart++;
  19495. } else
  19496. {
  19497. s.strstart += s.match_length;
  19498. s.match_length = 0;
  19499. s.ins_h = s.window[s.strstart];
  19500. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  19501. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  19502. //#if MIN_MATCH != 3
  19503. // Call UPDATE_HASH() MIN_MATCH-3 more times
  19504. //#endif
  19505. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  19506. * matter since it will be recomputed at next deflate call.
  19507. */
  19508. }
  19509. } else {
  19510. /* No match, output a literal byte */
  19511. //Tracevv((stderr,"%c", s.window[s.strstart]));
  19512. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  19513. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  19514. s.lookahead--;
  19515. s.strstart++;
  19516. }
  19517. if (bflush) {
  19518. /*** FLUSH_BLOCK(s, 0); ***/
  19519. flush_block_only(s, false);
  19520. if (s.strm.avail_out === 0) {
  19521. return BS_NEED_MORE;
  19522. }
  19523. /***/
  19524. }
  19525. }
  19526. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  19527. if (flush === Z_FINISH) {
  19528. /*** FLUSH_BLOCK(s, 1); ***/
  19529. flush_block_only(s, true);
  19530. if (s.strm.avail_out === 0) {
  19531. return BS_FINISH_STARTED;
  19532. }
  19533. /***/
  19534. return BS_FINISH_DONE;
  19535. }
  19536. if (s.last_lit) {
  19537. /*** FLUSH_BLOCK(s, 0); ***/
  19538. flush_block_only(s, false);
  19539. if (s.strm.avail_out === 0) {
  19540. return BS_NEED_MORE;
  19541. }
  19542. /***/
  19543. }
  19544. return BS_BLOCK_DONE;
  19545. }
  19546. /* ===========================================================================
  19547. * Same as above, but achieves better compression. We use a lazy
  19548. * evaluation for matches: a match is finally adopted only if there is
  19549. * no better match at the next window position.
  19550. */
  19551. function deflate_slow(s, flush) {
  19552. var hash_head; /* head of hash chain */
  19553. var bflush; /* set if current block must be flushed */
  19554. var max_insert;
  19555. /* Process the input block. */
  19556. for (;;) {
  19557. /* Make sure that we always have enough lookahead, except
  19558. * at the end of the input file. We need MAX_MATCH bytes
  19559. * for the next match, plus MIN_MATCH bytes to insert the
  19560. * string following the next match.
  19561. */
  19562. if (s.lookahead < MIN_LOOKAHEAD) {
  19563. fill_window(s);
  19564. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  19565. return BS_NEED_MORE;
  19566. }
  19567. if (s.lookahead === 0) { break; } /* flush the current block */
  19568. }
  19569. /* Insert the string window[strstart .. strstart+2] in the
  19570. * dictionary, and set hash_head to the head of the hash chain:
  19571. */
  19572. hash_head = 0/*NIL*/;
  19573. if (s.lookahead >= MIN_MATCH) {
  19574. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19575. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19576. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19577. s.head[s.ins_h] = s.strstart;
  19578. /***/
  19579. }
  19580. /* Find the longest match, discarding those <= prev_length.
  19581. */
  19582. s.prev_length = s.match_length;
  19583. s.prev_match = s.match_start;
  19584. s.match_length = MIN_MATCH-1;
  19585. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  19586. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  19587. /* To simplify the code, we prevent matches with the string
  19588. * of window index 0 (in particular we have to avoid a match
  19589. * of the string with itself at the start of the input file).
  19590. */
  19591. s.match_length = longest_match(s, hash_head);
  19592. /* longest_match() sets match_start */
  19593. if (s.match_length <= 5 &&
  19594. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  19595. /* If prev_match is also MIN_MATCH, match_start is garbage
  19596. * but we will ignore the current match anyway.
  19597. */
  19598. s.match_length = MIN_MATCH-1;
  19599. }
  19600. }
  19601. /* If there was a match at the previous step and the current
  19602. * match is not better, output the previous match:
  19603. */
  19604. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  19605. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  19606. /* Do not insert strings in hash table beyond this. */
  19607. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  19608. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  19609. s.prev_length - MIN_MATCH, bflush);***/
  19610. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  19611. /* Insert in hash table all strings up to the end of the match.
  19612. * strstart-1 and strstart are already inserted. If there is not
  19613. * enough lookahead, the last two strings are not inserted in
  19614. * the hash table.
  19615. */
  19616. s.lookahead -= s.prev_length-1;
  19617. s.prev_length -= 2;
  19618. do {
  19619. if (++s.strstart <= max_insert) {
  19620. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19621. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19622. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19623. s.head[s.ins_h] = s.strstart;
  19624. /***/
  19625. }
  19626. } while (--s.prev_length !== 0);
  19627. s.match_available = 0;
  19628. s.match_length = MIN_MATCH-1;
  19629. s.strstart++;
  19630. if (bflush) {
  19631. /*** FLUSH_BLOCK(s, 0); ***/
  19632. flush_block_only(s, false);
  19633. if (s.strm.avail_out === 0) {
  19634. return BS_NEED_MORE;
  19635. }
  19636. /***/
  19637. }
  19638. } else if (s.match_available) {
  19639. /* If there was no match at the previous position, output a
  19640. * single literal. If there was a match but the current match
  19641. * is longer, truncate the previous match to a single literal.
  19642. */
  19643. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  19644. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  19645. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  19646. if (bflush) {
  19647. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  19648. flush_block_only(s, false);
  19649. /***/
  19650. }
  19651. s.strstart++;
  19652. s.lookahead--;
  19653. if (s.strm.avail_out === 0) {
  19654. return BS_NEED_MORE;
  19655. }
  19656. } else {
  19657. /* There is no previous match to compare with, wait for
  19658. * the next step to decide.
  19659. */
  19660. s.match_available = 1;
  19661. s.strstart++;
  19662. s.lookahead--;
  19663. }
  19664. }
  19665. //Assert (flush != Z_NO_FLUSH, "no flush?");
  19666. if (s.match_available) {
  19667. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  19668. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  19669. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  19670. s.match_available = 0;
  19671. }
  19672. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  19673. if (flush === Z_FINISH) {
  19674. /*** FLUSH_BLOCK(s, 1); ***/
  19675. flush_block_only(s, true);
  19676. if (s.strm.avail_out === 0) {
  19677. return BS_FINISH_STARTED;
  19678. }
  19679. /***/
  19680. return BS_FINISH_DONE;
  19681. }
  19682. if (s.last_lit) {
  19683. /*** FLUSH_BLOCK(s, 0); ***/
  19684. flush_block_only(s, false);
  19685. if (s.strm.avail_out === 0) {
  19686. return BS_NEED_MORE;
  19687. }
  19688. /***/
  19689. }
  19690. return BS_BLOCK_DONE;
  19691. }
  19692. /* ===========================================================================
  19693. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  19694. * one. Do not maintain a hash table. (It will be regenerated if this run of
  19695. * deflate switches away from Z_RLE.)
  19696. */
  19697. function deflate_rle(s, flush) {
  19698. var bflush; /* set if current block must be flushed */
  19699. var prev; /* byte at distance one to match */
  19700. var scan, strend; /* scan goes up to strend for length of run */
  19701. var _win = s.window;
  19702. for (;;) {
  19703. /* Make sure that we always have enough lookahead, except
  19704. * at the end of the input file. We need MAX_MATCH bytes
  19705. * for the longest run, plus one for the unrolled loop.
  19706. */
  19707. if (s.lookahead <= MAX_MATCH) {
  19708. fill_window(s);
  19709. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  19710. return BS_NEED_MORE;
  19711. }
  19712. if (s.lookahead === 0) { break; } /* flush the current block */
  19713. }
  19714. /* See how many times the previous byte repeats */
  19715. s.match_length = 0;
  19716. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  19717. scan = s.strstart - 1;
  19718. prev = _win[scan];
  19719. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  19720. strend = s.strstart + MAX_MATCH;
  19721. do {
  19722. /*jshint noempty:false*/
  19723. } while (prev === _win[++scan] && prev === _win[++scan] &&
  19724. prev === _win[++scan] && prev === _win[++scan] &&
  19725. prev === _win[++scan] && prev === _win[++scan] &&
  19726. prev === _win[++scan] && prev === _win[++scan] &&
  19727. scan < strend);
  19728. s.match_length = MAX_MATCH - (strend - scan);
  19729. if (s.match_length > s.lookahead) {
  19730. s.match_length = s.lookahead;
  19731. }
  19732. }
  19733. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  19734. }
  19735. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  19736. if (s.match_length >= MIN_MATCH) {
  19737. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  19738. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  19739. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  19740. s.lookahead -= s.match_length;
  19741. s.strstart += s.match_length;
  19742. s.match_length = 0;
  19743. } else {
  19744. /* No match, output a literal byte */
  19745. //Tracevv((stderr,"%c", s->window[s->strstart]));
  19746. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  19747. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  19748. s.lookahead--;
  19749. s.strstart++;
  19750. }
  19751. if (bflush) {
  19752. /*** FLUSH_BLOCK(s, 0); ***/
  19753. flush_block_only(s, false);
  19754. if (s.strm.avail_out === 0) {
  19755. return BS_NEED_MORE;
  19756. }
  19757. /***/
  19758. }
  19759. }
  19760. s.insert = 0;
  19761. if (flush === Z_FINISH) {
  19762. /*** FLUSH_BLOCK(s, 1); ***/
  19763. flush_block_only(s, true);
  19764. if (s.strm.avail_out === 0) {
  19765. return BS_FINISH_STARTED;
  19766. }
  19767. /***/
  19768. return BS_FINISH_DONE;
  19769. }
  19770. if (s.last_lit) {
  19771. /*** FLUSH_BLOCK(s, 0); ***/
  19772. flush_block_only(s, false);
  19773. if (s.strm.avail_out === 0) {
  19774. return BS_NEED_MORE;
  19775. }
  19776. /***/
  19777. }
  19778. return BS_BLOCK_DONE;
  19779. }
  19780. /* ===========================================================================
  19781. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  19782. * (It will be regenerated if this run of deflate switches away from Huffman.)
  19783. */
  19784. function deflate_huff(s, flush) {
  19785. var bflush; /* set if current block must be flushed */
  19786. for (;;) {
  19787. /* Make sure that we have a literal to write. */
  19788. if (s.lookahead === 0) {
  19789. fill_window(s);
  19790. if (s.lookahead === 0) {
  19791. if (flush === Z_NO_FLUSH) {
  19792. return BS_NEED_MORE;
  19793. }
  19794. break; /* flush the current block */
  19795. }
  19796. }
  19797. /* Output a literal byte */
  19798. s.match_length = 0;
  19799. //Tracevv((stderr,"%c", s->window[s->strstart]));
  19800. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  19801. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  19802. s.lookahead--;
  19803. s.strstart++;
  19804. if (bflush) {
  19805. /*** FLUSH_BLOCK(s, 0); ***/
  19806. flush_block_only(s, false);
  19807. if (s.strm.avail_out === 0) {
  19808. return BS_NEED_MORE;
  19809. }
  19810. /***/
  19811. }
  19812. }
  19813. s.insert = 0;
  19814. if (flush === Z_FINISH) {
  19815. /*** FLUSH_BLOCK(s, 1); ***/
  19816. flush_block_only(s, true);
  19817. if (s.strm.avail_out === 0) {
  19818. return BS_FINISH_STARTED;
  19819. }
  19820. /***/
  19821. return BS_FINISH_DONE;
  19822. }
  19823. if (s.last_lit) {
  19824. /*** FLUSH_BLOCK(s, 0); ***/
  19825. flush_block_only(s, false);
  19826. if (s.strm.avail_out === 0) {
  19827. return BS_NEED_MORE;
  19828. }
  19829. /***/
  19830. }
  19831. return BS_BLOCK_DONE;
  19832. }
  19833. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  19834. * the desired pack level (0..9). The values given below have been tuned to
  19835. * exclude worst case performance for pathological files. Better values may be
  19836. * found for specific files.
  19837. */
  19838. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  19839. this.good_length = good_length;
  19840. this.max_lazy = max_lazy;
  19841. this.nice_length = nice_length;
  19842. this.max_chain = max_chain;
  19843. this.func = func;
  19844. };
  19845. var configuration_table;
  19846. configuration_table = [
  19847. /* good lazy nice chain */
  19848. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  19849. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  19850. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  19851. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  19852. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  19853. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  19854. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  19855. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  19856. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  19857. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  19858. ];
  19859. /* ===========================================================================
  19860. * Initialize the "longest match" routines for a new zlib stream
  19861. */
  19862. function lm_init(s) {
  19863. s.window_size = 2 * s.w_size;
  19864. /*** CLEAR_HASH(s); ***/
  19865. zero(s.head); // Fill with NIL (= 0);
  19866. /* Set the default configuration parameters:
  19867. */
  19868. s.max_lazy_match = configuration_table[s.level].max_lazy;
  19869. s.good_match = configuration_table[s.level].good_length;
  19870. s.nice_match = configuration_table[s.level].nice_length;
  19871. s.max_chain_length = configuration_table[s.level].max_chain;
  19872. s.strstart = 0;
  19873. s.block_start = 0;
  19874. s.lookahead = 0;
  19875. s.insert = 0;
  19876. s.match_length = s.prev_length = MIN_MATCH - 1;
  19877. s.match_available = 0;
  19878. s.ins_h = 0;
  19879. }
  19880. function DeflateState() {
  19881. this.strm = null; /* pointer back to this zlib stream */
  19882. this.status = 0; /* as the name implies */
  19883. this.pending_buf = null; /* output still pending */
  19884. this.pending_buf_size = 0; /* size of pending_buf */
  19885. this.pending_out = 0; /* next pending byte to output to the stream */
  19886. this.pending = 0; /* nb of bytes in the pending buffer */
  19887. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19888. this.gzhead = null; /* gzip header information to write */
  19889. this.gzindex = 0; /* where in extra, name, or comment */
  19890. this.method = Z_DEFLATED; /* can only be DEFLATED */
  19891. this.last_flush = -1; /* value of flush param for previous deflate call */
  19892. this.w_size = 0; /* LZ77 window size (32K by default) */
  19893. this.w_bits = 0; /* log2(w_size) (8..16) */
  19894. this.w_mask = 0; /* w_size - 1 */
  19895. this.window = null;
  19896. /* Sliding window. Input bytes are read into the second half of the window,
  19897. * and move to the first half later to keep a dictionary of at least wSize
  19898. * bytes. With this organization, matches are limited to a distance of
  19899. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  19900. * performed with a length multiple of the block size.
  19901. */
  19902. this.window_size = 0;
  19903. /* Actual size of window: 2*wSize, except when the user input buffer
  19904. * is directly used as sliding window.
  19905. */
  19906. this.prev = null;
  19907. /* Link to older string with same hash index. To limit the size of this
  19908. * array to 64K, this link is maintained only for the last 32K strings.
  19909. * An index in this array is thus a window index modulo 32K.
  19910. */
  19911. this.head = null; /* Heads of the hash chains or NIL. */
  19912. this.ins_h = 0; /* hash index of string to be inserted */
  19913. this.hash_size = 0; /* number of elements in hash table */
  19914. this.hash_bits = 0; /* log2(hash_size) */
  19915. this.hash_mask = 0; /* hash_size-1 */
  19916. this.hash_shift = 0;
  19917. /* Number of bits by which ins_h must be shifted at each input
  19918. * step. It must be such that after MIN_MATCH steps, the oldest
  19919. * byte no longer takes part in the hash key, that is:
  19920. * hash_shift * MIN_MATCH >= hash_bits
  19921. */
  19922. this.block_start = 0;
  19923. /* Window position at the beginning of the current output block. Gets
  19924. * negative when the window is moved backwards.
  19925. */
  19926. this.match_length = 0; /* length of best match */
  19927. this.prev_match = 0; /* previous match */
  19928. this.match_available = 0; /* set if previous match exists */
  19929. this.strstart = 0; /* start of string to insert */
  19930. this.match_start = 0; /* start of matching string */
  19931. this.lookahead = 0; /* number of valid bytes ahead in window */
  19932. this.prev_length = 0;
  19933. /* Length of the best match at previous step. Matches not greater than this
  19934. * are discarded. This is used in the lazy match evaluation.
  19935. */
  19936. this.max_chain_length = 0;
  19937. /* To speed up deflation, hash chains are never searched beyond this
  19938. * length. A higher limit improves compression ratio but degrades the
  19939. * speed.
  19940. */
  19941. this.max_lazy_match = 0;
  19942. /* Attempt to find a better match only when the current match is strictly
  19943. * smaller than this value. This mechanism is used only for compression
  19944. * levels >= 4.
  19945. */
  19946. // That's alias to max_lazy_match, don't use directly
  19947. //this.max_insert_length = 0;
  19948. /* Insert new strings in the hash table only if the match length is not
  19949. * greater than this length. This saves time but degrades compression.
  19950. * max_insert_length is used only for compression levels <= 3.
  19951. */
  19952. this.level = 0; /* compression level (1..9) */
  19953. this.strategy = 0; /* favor or force Huffman coding*/
  19954. this.good_match = 0;
  19955. /* Use a faster search when the previous match is longer than this */
  19956. this.nice_match = 0; /* Stop searching when current match exceeds this */
  19957. /* used by trees.c: */
  19958. /* Didn't use ct_data typedef below to suppress compiler warning */
  19959. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  19960. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  19961. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  19962. // Use flat array of DOUBLE size, with interleaved fata,
  19963. // because JS does not support effective
  19964. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  19965. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  19966. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  19967. zero(this.dyn_ltree);
  19968. zero(this.dyn_dtree);
  19969. zero(this.bl_tree);
  19970. this.l_desc = null; /* desc. for literal tree */
  19971. this.d_desc = null; /* desc. for distance tree */
  19972. this.bl_desc = null; /* desc. for bit length tree */
  19973. //ush bl_count[MAX_BITS+1];
  19974. this.bl_count = new utils.Buf16(MAX_BITS+1);
  19975. /* number of codes at each bit length for an optimal tree */
  19976. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  19977. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  19978. zero(this.heap);
  19979. this.heap_len = 0; /* number of elements in the heap */
  19980. this.heap_max = 0; /* element of largest frequency */
  19981. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  19982. * The same heap array is used to build all trees.
  19983. */
  19984. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  19985. zero(this.depth);
  19986. /* Depth of each subtree used as tie breaker for trees of equal frequency
  19987. */
  19988. this.l_buf = 0; /* buffer index for literals or lengths */
  19989. this.lit_bufsize = 0;
  19990. /* Size of match buffer for literals/lengths. There are 4 reasons for
  19991. * limiting lit_bufsize to 64K:
  19992. * - frequencies can be kept in 16 bit counters
  19993. * - if compression is not successful for the first block, all input
  19994. * data is still in the window so we can still emit a stored block even
  19995. * when input comes from standard input. (This can also be done for
  19996. * all blocks if lit_bufsize is not greater than 32K.)
  19997. * - if compression is not successful for a file smaller than 64K, we can
  19998. * even emit a stored file instead of a stored block (saving 5 bytes).
  19999. * This is applicable only for zip (not gzip or zlib).
  20000. * - creating new Huffman trees less frequently may not provide fast
  20001. * adaptation to changes in the input data statistics. (Take for
  20002. * example a binary file with poorly compressible code followed by
  20003. * a highly compressible string table.) Smaller buffer sizes give
  20004. * fast adaptation but have of course the overhead of transmitting
  20005. * trees more frequently.
  20006. * - I can't count above 4
  20007. */
  20008. this.last_lit = 0; /* running index in l_buf */
  20009. this.d_buf = 0;
  20010. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  20011. * the same number of elements. To use different lengths, an extra flag
  20012. * array would be necessary.
  20013. */
  20014. this.opt_len = 0; /* bit length of current block with optimal trees */
  20015. this.static_len = 0; /* bit length of current block with static trees */
  20016. this.matches = 0; /* number of string matches in current block */
  20017. this.insert = 0; /* bytes at end of window left to insert */
  20018. this.bi_buf = 0;
  20019. /* Output buffer. bits are inserted starting at the bottom (least
  20020. * significant bits).
  20021. */
  20022. this.bi_valid = 0;
  20023. /* Number of valid bits in bi_buf. All bits above the last valid bit
  20024. * are always zero.
  20025. */
  20026. // Used for window memory init. We safely ignore it for JS. That makes
  20027. // sense only for pointers and memory check tools.
  20028. //this.high_water = 0;
  20029. /* High water mark offset in window for initialized bytes -- bytes above
  20030. * this are set to zero in order to avoid memory check warnings when
  20031. * longest match routines access bytes past the input. This is then
  20032. * updated to the new high water mark.
  20033. */
  20034. }
  20035. function deflateResetKeep(strm) {
  20036. var s;
  20037. if (!strm || !strm.state) {
  20038. return err(strm, Z_STREAM_ERROR);
  20039. }
  20040. strm.total_in = strm.total_out = 0;
  20041. strm.data_type = Z_UNKNOWN;
  20042. s = strm.state;
  20043. s.pending = 0;
  20044. s.pending_out = 0;
  20045. if (s.wrap < 0) {
  20046. s.wrap = -s.wrap;
  20047. /* was made negative by deflate(..., Z_FINISH); */
  20048. }
  20049. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  20050. strm.adler = (s.wrap === 2) ?
  20051. 0 // crc32(0, Z_NULL, 0)
  20052. :
  20053. 1; // adler32(0, Z_NULL, 0)
  20054. s.last_flush = Z_NO_FLUSH;
  20055. trees._tr_init(s);
  20056. return Z_OK;
  20057. }
  20058. function deflateReset(strm) {
  20059. var ret = deflateResetKeep(strm);
  20060. if (ret === Z_OK) {
  20061. lm_init(strm.state);
  20062. }
  20063. return ret;
  20064. }
  20065. function deflateSetHeader(strm, head) {
  20066. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20067. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  20068. strm.state.gzhead = head;
  20069. return Z_OK;
  20070. }
  20071. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  20072. if (!strm) { // === Z_NULL
  20073. return Z_STREAM_ERROR;
  20074. }
  20075. var wrap = 1;
  20076. if (level === Z_DEFAULT_COMPRESSION) {
  20077. level = 6;
  20078. }
  20079. if (windowBits < 0) { /* suppress zlib wrapper */
  20080. wrap = 0;
  20081. windowBits = -windowBits;
  20082. }
  20083. else if (windowBits > 15) {
  20084. wrap = 2; /* write gzip wrapper instead */
  20085. windowBits -= 16;
  20086. }
  20087. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  20088. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  20089. strategy < 0 || strategy > Z_FIXED) {
  20090. return err(strm, Z_STREAM_ERROR);
  20091. }
  20092. if (windowBits === 8) {
  20093. windowBits = 9;
  20094. }
  20095. /* until 256-byte window bug fixed */
  20096. var s = new DeflateState();
  20097. strm.state = s;
  20098. s.strm = strm;
  20099. s.wrap = wrap;
  20100. s.gzhead = null;
  20101. s.w_bits = windowBits;
  20102. s.w_size = 1 << s.w_bits;
  20103. s.w_mask = s.w_size - 1;
  20104. s.hash_bits = memLevel + 7;
  20105. s.hash_size = 1 << s.hash_bits;
  20106. s.hash_mask = s.hash_size - 1;
  20107. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  20108. s.window = new utils.Buf8(s.w_size * 2);
  20109. s.head = new utils.Buf16(s.hash_size);
  20110. s.prev = new utils.Buf16(s.w_size);
  20111. // Don't need mem init magic for JS.
  20112. //s.high_water = 0; /* nothing written to s->window yet */
  20113. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  20114. s.pending_buf_size = s.lit_bufsize * 4;
  20115. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  20116. s.d_buf = s.lit_bufsize >> 1;
  20117. s.l_buf = (1 + 2) * s.lit_bufsize;
  20118. s.level = level;
  20119. s.strategy = strategy;
  20120. s.method = method;
  20121. return deflateReset(strm);
  20122. }
  20123. function deflateInit(strm, level) {
  20124. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  20125. }
  20126. function deflate(strm, flush) {
  20127. var old_flush, s;
  20128. var beg, val; // for gzip header write only
  20129. if (!strm || !strm.state ||
  20130. flush > Z_BLOCK || flush < 0) {
  20131. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  20132. }
  20133. s = strm.state;
  20134. if (!strm.output ||
  20135. (!strm.input && strm.avail_in !== 0) ||
  20136. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  20137. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  20138. }
  20139. s.strm = strm; /* just in case */
  20140. old_flush = s.last_flush;
  20141. s.last_flush = flush;
  20142. /* Write the header */
  20143. if (s.status === INIT_STATE) {
  20144. if (s.wrap === 2) { // GZIP header
  20145. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20146. put_byte(s, 31);
  20147. put_byte(s, 139);
  20148. put_byte(s, 8);
  20149. if (!s.gzhead) { // s->gzhead == Z_NULL
  20150. put_byte(s, 0);
  20151. put_byte(s, 0);
  20152. put_byte(s, 0);
  20153. put_byte(s, 0);
  20154. put_byte(s, 0);
  20155. put_byte(s, s.level === 9 ? 2 :
  20156. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20157. 4 : 0));
  20158. put_byte(s, OS_CODE);
  20159. s.status = BUSY_STATE;
  20160. }
  20161. else {
  20162. put_byte(s, (s.gzhead.text ? 1 : 0) +
  20163. (s.gzhead.hcrc ? 2 : 0) +
  20164. (!s.gzhead.extra ? 0 : 4) +
  20165. (!s.gzhead.name ? 0 : 8) +
  20166. (!s.gzhead.comment ? 0 : 16)
  20167. );
  20168. put_byte(s, s.gzhead.time & 0xff);
  20169. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  20170. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  20171. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  20172. put_byte(s, s.level === 9 ? 2 :
  20173. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20174. 4 : 0));
  20175. put_byte(s, s.gzhead.os & 0xff);
  20176. if (s.gzhead.extra && s.gzhead.extra.length) {
  20177. put_byte(s, s.gzhead.extra.length & 0xff);
  20178. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  20179. }
  20180. if (s.gzhead.hcrc) {
  20181. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  20182. }
  20183. s.gzindex = 0;
  20184. s.status = EXTRA_STATE;
  20185. }
  20186. }
  20187. else // DEFLATE header
  20188. {
  20189. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  20190. var level_flags = -1;
  20191. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  20192. level_flags = 0;
  20193. } else if (s.level < 6) {
  20194. level_flags = 1;
  20195. } else if (s.level === 6) {
  20196. level_flags = 2;
  20197. } else {
  20198. level_flags = 3;
  20199. }
  20200. header |= (level_flags << 6);
  20201. if (s.strstart !== 0) { header |= PRESET_DICT; }
  20202. header += 31 - (header % 31);
  20203. s.status = BUSY_STATE;
  20204. putShortMSB(s, header);
  20205. /* Save the adler32 of the preset dictionary: */
  20206. if (s.strstart !== 0) {
  20207. putShortMSB(s, strm.adler >>> 16);
  20208. putShortMSB(s, strm.adler & 0xffff);
  20209. }
  20210. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  20211. }
  20212. }
  20213. //#ifdef GZIP
  20214. if (s.status === EXTRA_STATE) {
  20215. if (s.gzhead.extra/* != Z_NULL*/) {
  20216. beg = s.pending; /* start of bytes to update crc */
  20217. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  20218. if (s.pending === s.pending_buf_size) {
  20219. if (s.gzhead.hcrc && s.pending > beg) {
  20220. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20221. }
  20222. flush_pending(strm);
  20223. beg = s.pending;
  20224. if (s.pending === s.pending_buf_size) {
  20225. break;
  20226. }
  20227. }
  20228. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  20229. s.gzindex++;
  20230. }
  20231. if (s.gzhead.hcrc && s.pending > beg) {
  20232. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20233. }
  20234. if (s.gzindex === s.gzhead.extra.length) {
  20235. s.gzindex = 0;
  20236. s.status = NAME_STATE;
  20237. }
  20238. }
  20239. else {
  20240. s.status = NAME_STATE;
  20241. }
  20242. }
  20243. if (s.status === NAME_STATE) {
  20244. if (s.gzhead.name/* != Z_NULL*/) {
  20245. beg = s.pending; /* start of bytes to update crc */
  20246. //int val;
  20247. do {
  20248. if (s.pending === s.pending_buf_size) {
  20249. if (s.gzhead.hcrc && s.pending > beg) {
  20250. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20251. }
  20252. flush_pending(strm);
  20253. beg = s.pending;
  20254. if (s.pending === s.pending_buf_size) {
  20255. val = 1;
  20256. break;
  20257. }
  20258. }
  20259. // JS specific: little magic to add zero terminator to end of string
  20260. if (s.gzindex < s.gzhead.name.length) {
  20261. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  20262. } else {
  20263. val = 0;
  20264. }
  20265. put_byte(s, val);
  20266. } while (val !== 0);
  20267. if (s.gzhead.hcrc && s.pending > beg) {
  20268. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20269. }
  20270. if (val === 0) {
  20271. s.gzindex = 0;
  20272. s.status = COMMENT_STATE;
  20273. }
  20274. }
  20275. else {
  20276. s.status = COMMENT_STATE;
  20277. }
  20278. }
  20279. if (s.status === COMMENT_STATE) {
  20280. if (s.gzhead.comment/* != Z_NULL*/) {
  20281. beg = s.pending; /* start of bytes to update crc */
  20282. //int val;
  20283. do {
  20284. if (s.pending === s.pending_buf_size) {
  20285. if (s.gzhead.hcrc && s.pending > beg) {
  20286. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20287. }
  20288. flush_pending(strm);
  20289. beg = s.pending;
  20290. if (s.pending === s.pending_buf_size) {
  20291. val = 1;
  20292. break;
  20293. }
  20294. }
  20295. // JS specific: little magic to add zero terminator to end of string
  20296. if (s.gzindex < s.gzhead.comment.length) {
  20297. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  20298. } else {
  20299. val = 0;
  20300. }
  20301. put_byte(s, val);
  20302. } while (val !== 0);
  20303. if (s.gzhead.hcrc && s.pending > beg) {
  20304. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20305. }
  20306. if (val === 0) {
  20307. s.status = HCRC_STATE;
  20308. }
  20309. }
  20310. else {
  20311. s.status = HCRC_STATE;
  20312. }
  20313. }
  20314. if (s.status === HCRC_STATE) {
  20315. if (s.gzhead.hcrc) {
  20316. if (s.pending + 2 > s.pending_buf_size) {
  20317. flush_pending(strm);
  20318. }
  20319. if (s.pending + 2 <= s.pending_buf_size) {
  20320. put_byte(s, strm.adler & 0xff);
  20321. put_byte(s, (strm.adler >> 8) & 0xff);
  20322. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20323. s.status = BUSY_STATE;
  20324. }
  20325. }
  20326. else {
  20327. s.status = BUSY_STATE;
  20328. }
  20329. }
  20330. //#endif
  20331. /* Flush as much pending output as possible */
  20332. if (s.pending !== 0) {
  20333. flush_pending(strm);
  20334. if (strm.avail_out === 0) {
  20335. /* Since avail_out is 0, deflate will be called again with
  20336. * more output space, but possibly with both pending and
  20337. * avail_in equal to zero. There won't be anything to do,
  20338. * but this is not an error situation so make sure we
  20339. * return OK instead of BUF_ERROR at next call of deflate:
  20340. */
  20341. s.last_flush = -1;
  20342. return Z_OK;
  20343. }
  20344. /* Make sure there is something to do and avoid duplicate consecutive
  20345. * flushes. For repeated and useless calls with Z_FINISH, we keep
  20346. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  20347. */
  20348. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  20349. flush !== Z_FINISH) {
  20350. return err(strm, Z_BUF_ERROR);
  20351. }
  20352. /* User must not provide more input after the first FINISH: */
  20353. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  20354. return err(strm, Z_BUF_ERROR);
  20355. }
  20356. /* Start a new block or continue the current one.
  20357. */
  20358. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  20359. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  20360. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  20361. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  20362. configuration_table[s.level].func(s, flush));
  20363. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  20364. s.status = FINISH_STATE;
  20365. }
  20366. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  20367. if (strm.avail_out === 0) {
  20368. s.last_flush = -1;
  20369. /* avoid BUF_ERROR next call, see above */
  20370. }
  20371. return Z_OK;
  20372. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  20373. * of deflate should use the same flush parameter to make sure
  20374. * that the flush is complete. So we don't have to output an
  20375. * empty block here, this will be done at next call. This also
  20376. * ensures that for a very small output buffer, we emit at most
  20377. * one empty block.
  20378. */
  20379. }
  20380. if (bstate === BS_BLOCK_DONE) {
  20381. if (flush === Z_PARTIAL_FLUSH) {
  20382. trees._tr_align(s);
  20383. }
  20384. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  20385. trees._tr_stored_block(s, 0, 0, false);
  20386. /* For a full flush, this empty block will be recognized
  20387. * as a special marker by inflate_sync().
  20388. */
  20389. if (flush === Z_FULL_FLUSH) {
  20390. /*** CLEAR_HASH(s); ***/ /* forget history */
  20391. zero(s.head); // Fill with NIL (= 0);
  20392. if (s.lookahead === 0) {
  20393. s.strstart = 0;
  20394. s.block_start = 0;
  20395. s.insert = 0;
  20396. }
  20397. }
  20398. }
  20399. flush_pending(strm);
  20400. if (strm.avail_out === 0) {
  20401. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  20402. return Z_OK;
  20403. }
  20404. }
  20405. }
  20406. //Assert(strm->avail_out > 0, "bug2");
  20407. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  20408. if (flush !== Z_FINISH) { return Z_OK; }
  20409. if (s.wrap <= 0) { return Z_STREAM_END; }
  20410. /* Write the trailer */
  20411. if (s.wrap === 2) {
  20412. put_byte(s, strm.adler & 0xff);
  20413. put_byte(s, (strm.adler >> 8) & 0xff);
  20414. put_byte(s, (strm.adler >> 16) & 0xff);
  20415. put_byte(s, (strm.adler >> 24) & 0xff);
  20416. put_byte(s, strm.total_in & 0xff);
  20417. put_byte(s, (strm.total_in >> 8) & 0xff);
  20418. put_byte(s, (strm.total_in >> 16) & 0xff);
  20419. put_byte(s, (strm.total_in >> 24) & 0xff);
  20420. }
  20421. else
  20422. {
  20423. putShortMSB(s, strm.adler >>> 16);
  20424. putShortMSB(s, strm.adler & 0xffff);
  20425. }
  20426. flush_pending(strm);
  20427. /* If avail_out is zero, the application will call deflate again
  20428. * to flush the rest.
  20429. */
  20430. if (s.wrap > 0) { s.wrap = -s.wrap; }
  20431. /* write the trailer only once! */
  20432. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  20433. }
  20434. function deflateEnd(strm) {
  20435. var status;
  20436. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  20437. return Z_STREAM_ERROR;
  20438. }
  20439. status = strm.state.status;
  20440. if (status !== INIT_STATE &&
  20441. status !== EXTRA_STATE &&
  20442. status !== NAME_STATE &&
  20443. status !== COMMENT_STATE &&
  20444. status !== HCRC_STATE &&
  20445. status !== BUSY_STATE &&
  20446. status !== FINISH_STATE
  20447. ) {
  20448. return err(strm, Z_STREAM_ERROR);
  20449. }
  20450. strm.state = null;
  20451. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  20452. }
  20453. /* =========================================================================
  20454. * Copy the source state to the destination state
  20455. */
  20456. //function deflateCopy(dest, source) {
  20457. //
  20458. //}
  20459. exports.deflateInit = deflateInit;
  20460. exports.deflateInit2 = deflateInit2;
  20461. exports.deflateReset = deflateReset;
  20462. exports.deflateResetKeep = deflateResetKeep;
  20463. exports.deflateSetHeader = deflateSetHeader;
  20464. exports.deflate = deflate;
  20465. exports.deflateEnd = deflateEnd;
  20466. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  20467. /* Not implemented
  20468. exports.deflateBound = deflateBound;
  20469. exports.deflateCopy = deflateCopy;
  20470. exports.deflateSetDictionary = deflateSetDictionary;
  20471. exports.deflateParams = deflateParams;
  20472. exports.deflatePending = deflatePending;
  20473. exports.deflatePrime = deflatePrime;
  20474. exports.deflateTune = deflateTune;
  20475. */
  20476. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./messages":82,"./trees":83}],78:[function(require,module,exports){
  20477. 'use strict';
  20478. function GZheader() {
  20479. /* true if compressed data believed to be text */
  20480. this.text = 0;
  20481. /* modification time */
  20482. this.time = 0;
  20483. /* extra flags (not used when writing a gzip file) */
  20484. this.xflags = 0;
  20485. /* operating system */
  20486. this.os = 0;
  20487. /* pointer to extra field or Z_NULL if none */
  20488. this.extra = null;
  20489. /* extra field length (valid if extra != Z_NULL) */
  20490. this.extra_len = 0; // Actually, we don't need it in JS,
  20491. // but leave for few code modifications
  20492. //
  20493. // Setup limits is not necessary because in js we should not preallocate memory
  20494. // for inflate use constant limit in 65536 bytes
  20495. //
  20496. /* space at extra (only when reading header) */
  20497. // this.extra_max = 0;
  20498. /* pointer to zero-terminated file name or Z_NULL */
  20499. this.name = '';
  20500. /* space at name (only when reading header) */
  20501. // this.name_max = 0;
  20502. /* pointer to zero-terminated comment or Z_NULL */
  20503. this.comment = '';
  20504. /* space at comment (only when reading header) */
  20505. // this.comm_max = 0;
  20506. /* true if there was or will be a header crc */
  20507. this.hcrc = 0;
  20508. /* true when done reading gzip header (not used when writing a gzip file) */
  20509. this.done = false;
  20510. }
  20511. module.exports = GZheader;
  20512. },{}],79:[function(require,module,exports){
  20513. 'use strict';
  20514. // See state defs from inflate.js
  20515. var BAD = 30; /* got a data error -- remain here until reset */
  20516. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  20517. /*
  20518. Decode literal, length, and distance codes and write out the resulting
  20519. literal and match bytes until either not enough input or output is
  20520. available, an end-of-block is encountered, or a data error is encountered.
  20521. When large enough input and output buffers are supplied to inflate(), for
  20522. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  20523. inflate execution time is spent in this routine.
  20524. Entry assumptions:
  20525. state.mode === LEN
  20526. strm.avail_in >= 6
  20527. strm.avail_out >= 258
  20528. start >= strm.avail_out
  20529. state.bits < 8
  20530. On return, state.mode is one of:
  20531. LEN -- ran out of enough output space or enough available input
  20532. TYPE -- reached end of block code, inflate() to interpret next block
  20533. BAD -- error in block data
  20534. Notes:
  20535. - The maximum input bits used by a length/distance pair is 15 bits for the
  20536. length code, 5 bits for the length extra, 15 bits for the distance code,
  20537. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  20538. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  20539. checking for available input while decoding.
  20540. - The maximum bytes that a single length/distance pair can output is 258
  20541. bytes, which is the maximum length that can be coded. inflate_fast()
  20542. requires strm.avail_out >= 258 for each loop to avoid checking for
  20543. output space.
  20544. */
  20545. module.exports = function inflate_fast(strm, start) {
  20546. var state;
  20547. var _in; /* local strm.input */
  20548. var last; /* have enough input while in < last */
  20549. var _out; /* local strm.output */
  20550. var beg; /* inflate()'s initial strm.output */
  20551. var end; /* while out < end, enough space available */
  20552. //#ifdef INFLATE_STRICT
  20553. var dmax; /* maximum distance from zlib header */
  20554. //#endif
  20555. var wsize; /* window size or zero if not using window */
  20556. var whave; /* valid bytes in the window */
  20557. var wnext; /* window write index */
  20558. var window; /* allocated sliding window, if wsize != 0 */
  20559. var hold; /* local strm.hold */
  20560. var bits; /* local strm.bits */
  20561. var lcode; /* local strm.lencode */
  20562. var dcode; /* local strm.distcode */
  20563. var lmask; /* mask for first level of length codes */
  20564. var dmask; /* mask for first level of distance codes */
  20565. var here; /* retrieved table entry */
  20566. var op; /* code bits, operation, extra bits, or */
  20567. /* window position, window bytes to copy */
  20568. var len; /* match length, unused bytes */
  20569. var dist; /* match distance */
  20570. var from; /* where to copy match from */
  20571. var from_source;
  20572. var input, output; // JS specific, because we have no pointers
  20573. /* copy state to local variables */
  20574. state = strm.state;
  20575. //here = state.here;
  20576. _in = strm.next_in;
  20577. input = strm.input;
  20578. last = _in + (strm.avail_in - 5);
  20579. _out = strm.next_out;
  20580. output = strm.output;
  20581. beg = _out - (start - strm.avail_out);
  20582. end = _out + (strm.avail_out - 257);
  20583. //#ifdef INFLATE_STRICT
  20584. dmax = state.dmax;
  20585. //#endif
  20586. wsize = state.wsize;
  20587. whave = state.whave;
  20588. wnext = state.wnext;
  20589. window = state.window;
  20590. hold = state.hold;
  20591. bits = state.bits;
  20592. lcode = state.lencode;
  20593. dcode = state.distcode;
  20594. lmask = (1 << state.lenbits) - 1;
  20595. dmask = (1 << state.distbits) - 1;
  20596. /* decode literals and length/distances until end-of-block or not enough
  20597. input data or output space */
  20598. top:
  20599. do {
  20600. if (bits < 15) {
  20601. hold += input[_in++] << bits;
  20602. bits += 8;
  20603. hold += input[_in++] << bits;
  20604. bits += 8;
  20605. }
  20606. here = lcode[hold & lmask];
  20607. dolen:
  20608. for (;;) { // Goto emulation
  20609. op = here >>> 24/*here.bits*/;
  20610. hold >>>= op;
  20611. bits -= op;
  20612. op = (here >>> 16) & 0xff/*here.op*/;
  20613. if (op === 0) { /* literal */
  20614. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20615. // "inflate: literal '%c'\n" :
  20616. // "inflate: literal 0x%02x\n", here.val));
  20617. output[_out++] = here & 0xffff/*here.val*/;
  20618. }
  20619. else if (op & 16) { /* length base */
  20620. len = here & 0xffff/*here.val*/;
  20621. op &= 15; /* number of extra bits */
  20622. if (op) {
  20623. if (bits < op) {
  20624. hold += input[_in++] << bits;
  20625. bits += 8;
  20626. }
  20627. len += hold & ((1 << op) - 1);
  20628. hold >>>= op;
  20629. bits -= op;
  20630. }
  20631. //Tracevv((stderr, "inflate: length %u\n", len));
  20632. if (bits < 15) {
  20633. hold += input[_in++] << bits;
  20634. bits += 8;
  20635. hold += input[_in++] << bits;
  20636. bits += 8;
  20637. }
  20638. here = dcode[hold & dmask];
  20639. dodist:
  20640. for (;;) { // goto emulation
  20641. op = here >>> 24/*here.bits*/;
  20642. hold >>>= op;
  20643. bits -= op;
  20644. op = (here >>> 16) & 0xff/*here.op*/;
  20645. if (op & 16) { /* distance base */
  20646. dist = here & 0xffff/*here.val*/;
  20647. op &= 15; /* number of extra bits */
  20648. if (bits < op) {
  20649. hold += input[_in++] << bits;
  20650. bits += 8;
  20651. if (bits < op) {
  20652. hold += input[_in++] << bits;
  20653. bits += 8;
  20654. }
  20655. }
  20656. dist += hold & ((1 << op) - 1);
  20657. //#ifdef INFLATE_STRICT
  20658. if (dist > dmax) {
  20659. strm.msg = 'invalid distance too far back';
  20660. state.mode = BAD;
  20661. break top;
  20662. }
  20663. //#endif
  20664. hold >>>= op;
  20665. bits -= op;
  20666. //Tracevv((stderr, "inflate: distance %u\n", dist));
  20667. op = _out - beg; /* max distance in output */
  20668. if (dist > op) { /* see if copy from window */
  20669. op = dist - op; /* distance back in window */
  20670. if (op > whave) {
  20671. if (state.sane) {
  20672. strm.msg = 'invalid distance too far back';
  20673. state.mode = BAD;
  20674. break top;
  20675. }
  20676. // (!) This block is disabled in zlib defailts,
  20677. // don't enable it for binary compatibility
  20678. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20679. // if (len <= op - whave) {
  20680. // do {
  20681. // output[_out++] = 0;
  20682. // } while (--len);
  20683. // continue top;
  20684. // }
  20685. // len -= op - whave;
  20686. // do {
  20687. // output[_out++] = 0;
  20688. // } while (--op > whave);
  20689. // if (op === 0) {
  20690. // from = _out - dist;
  20691. // do {
  20692. // output[_out++] = output[from++];
  20693. // } while (--len);
  20694. // continue top;
  20695. // }
  20696. //#endif
  20697. }
  20698. from = 0; // window index
  20699. from_source = window;
  20700. if (wnext === 0) { /* very common case */
  20701. from += wsize - op;
  20702. if (op < len) { /* some from window */
  20703. len -= op;
  20704. do {
  20705. output[_out++] = window[from++];
  20706. } while (--op);
  20707. from = _out - dist; /* rest from output */
  20708. from_source = output;
  20709. }
  20710. }
  20711. else if (wnext < op) { /* wrap around window */
  20712. from += wsize + wnext - op;
  20713. op -= wnext;
  20714. if (op < len) { /* some from end of window */
  20715. len -= op;
  20716. do {
  20717. output[_out++] = window[from++];
  20718. } while (--op);
  20719. from = 0;
  20720. if (wnext < len) { /* some from start of window */
  20721. op = wnext;
  20722. len -= op;
  20723. do {
  20724. output[_out++] = window[from++];
  20725. } while (--op);
  20726. from = _out - dist; /* rest from output */
  20727. from_source = output;
  20728. }
  20729. }
  20730. }
  20731. else { /* contiguous in window */
  20732. from += wnext - op;
  20733. if (op < len) { /* some from window */
  20734. len -= op;
  20735. do {
  20736. output[_out++] = window[from++];
  20737. } while (--op);
  20738. from = _out - dist; /* rest from output */
  20739. from_source = output;
  20740. }
  20741. }
  20742. while (len > 2) {
  20743. output[_out++] = from_source[from++];
  20744. output[_out++] = from_source[from++];
  20745. output[_out++] = from_source[from++];
  20746. len -= 3;
  20747. }
  20748. if (len) {
  20749. output[_out++] = from_source[from++];
  20750. if (len > 1) {
  20751. output[_out++] = from_source[from++];
  20752. }
  20753. }
  20754. }
  20755. else {
  20756. from = _out - dist; /* copy direct from output */
  20757. do { /* minimum length is three */
  20758. output[_out++] = output[from++];
  20759. output[_out++] = output[from++];
  20760. output[_out++] = output[from++];
  20761. len -= 3;
  20762. } while (len > 2);
  20763. if (len) {
  20764. output[_out++] = output[from++];
  20765. if (len > 1) {
  20766. output[_out++] = output[from++];
  20767. }
  20768. }
  20769. }
  20770. }
  20771. else if ((op & 64) === 0) { /* 2nd level distance code */
  20772. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  20773. continue dodist;
  20774. }
  20775. else {
  20776. strm.msg = 'invalid distance code';
  20777. state.mode = BAD;
  20778. break top;
  20779. }
  20780. break; // need to emulate goto via "continue"
  20781. }
  20782. }
  20783. else if ((op & 64) === 0) { /* 2nd level length code */
  20784. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  20785. continue dolen;
  20786. }
  20787. else if (op & 32) { /* end-of-block */
  20788. //Tracevv((stderr, "inflate: end of block\n"));
  20789. state.mode = TYPE;
  20790. break top;
  20791. }
  20792. else {
  20793. strm.msg = 'invalid literal/length code';
  20794. state.mode = BAD;
  20795. break top;
  20796. }
  20797. break; // need to emulate goto via "continue"
  20798. }
  20799. } while (_in < last && _out < end);
  20800. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  20801. len = bits >> 3;
  20802. _in -= len;
  20803. bits -= len << 3;
  20804. hold &= (1 << bits) - 1;
  20805. /* update state and return */
  20806. strm.next_in = _in;
  20807. strm.next_out = _out;
  20808. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  20809. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  20810. state.hold = hold;
  20811. state.bits = bits;
  20812. return;
  20813. };
  20814. },{}],80:[function(require,module,exports){
  20815. 'use strict';
  20816. var utils = require('../utils/common');
  20817. var adler32 = require('./adler32');
  20818. var crc32 = require('./crc32');
  20819. var inflate_fast = require('./inffast');
  20820. var inflate_table = require('./inftrees');
  20821. var CODES = 0;
  20822. var LENS = 1;
  20823. var DISTS = 2;
  20824. /* Public constants ==========================================================*/
  20825. /* ===========================================================================*/
  20826. /* Allowed flush values; see deflate() and inflate() below for details */
  20827. //var Z_NO_FLUSH = 0;
  20828. //var Z_PARTIAL_FLUSH = 1;
  20829. //var Z_SYNC_FLUSH = 2;
  20830. //var Z_FULL_FLUSH = 3;
  20831. var Z_FINISH = 4;
  20832. var Z_BLOCK = 5;
  20833. var Z_TREES = 6;
  20834. /* Return codes for the compression/decompression functions. Negative values
  20835. * are errors, positive values are used for special but normal events.
  20836. */
  20837. var Z_OK = 0;
  20838. var Z_STREAM_END = 1;
  20839. var Z_NEED_DICT = 2;
  20840. //var Z_ERRNO = -1;
  20841. var Z_STREAM_ERROR = -2;
  20842. var Z_DATA_ERROR = -3;
  20843. var Z_MEM_ERROR = -4;
  20844. var Z_BUF_ERROR = -5;
  20845. //var Z_VERSION_ERROR = -6;
  20846. /* The deflate compression method */
  20847. var Z_DEFLATED = 8;
  20848. /* STATES ====================================================================*/
  20849. /* ===========================================================================*/
  20850. var HEAD = 1; /* i: waiting for magic header */
  20851. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  20852. var TIME = 3; /* i: waiting for modification time (gzip) */
  20853. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  20854. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  20855. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  20856. var NAME = 7; /* i: waiting for end of file name (gzip) */
  20857. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  20858. var HCRC = 9; /* i: waiting for header crc (gzip) */
  20859. var DICTID = 10; /* i: waiting for dictionary check value */
  20860. var DICT = 11; /* waiting for inflateSetDictionary() call */
  20861. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  20862. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  20863. var STORED = 14; /* i: waiting for stored size (length and complement) */
  20864. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  20865. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  20866. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  20867. var LENLENS = 18; /* i: waiting for code length code lengths */
  20868. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  20869. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  20870. var LEN = 21; /* i: waiting for length/lit/eob code */
  20871. var LENEXT = 22; /* i: waiting for length extra bits */
  20872. var DIST = 23; /* i: waiting for distance code */
  20873. var DISTEXT = 24; /* i: waiting for distance extra bits */
  20874. var MATCH = 25; /* o: waiting for output space to copy string */
  20875. var LIT = 26; /* o: waiting for output space to write literal */
  20876. var CHECK = 27; /* i: waiting for 32-bit check value */
  20877. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  20878. var DONE = 29; /* finished check, done -- remain here until reset */
  20879. var BAD = 30; /* got a data error -- remain here until reset */
  20880. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  20881. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  20882. /* ===========================================================================*/
  20883. var ENOUGH_LENS = 852;
  20884. var ENOUGH_DISTS = 592;
  20885. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20886. var MAX_WBITS = 15;
  20887. /* 32K LZ77 window */
  20888. var DEF_WBITS = MAX_WBITS;
  20889. function ZSWAP32(q) {
  20890. return (((q >>> 24) & 0xff) +
  20891. ((q >>> 8) & 0xff00) +
  20892. ((q & 0xff00) << 8) +
  20893. ((q & 0xff) << 24));
  20894. }
  20895. function InflateState() {
  20896. this.mode = 0; /* current inflate mode */
  20897. this.last = false; /* true if processing last block */
  20898. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20899. this.havedict = false; /* true if dictionary provided */
  20900. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  20901. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  20902. this.check = 0; /* protected copy of check value */
  20903. this.total = 0; /* protected copy of output count */
  20904. // TODO: may be {}
  20905. this.head = null; /* where to save gzip header information */
  20906. /* sliding window */
  20907. this.wbits = 0; /* log base 2 of requested window size */
  20908. this.wsize = 0; /* window size or zero if not using window */
  20909. this.whave = 0; /* valid bytes in the window */
  20910. this.wnext = 0; /* window write index */
  20911. this.window = null; /* allocated sliding window, if needed */
  20912. /* bit accumulator */
  20913. this.hold = 0; /* input bit accumulator */
  20914. this.bits = 0; /* number of bits in "in" */
  20915. /* for string and stored block copying */
  20916. this.length = 0; /* literal or length of data to copy */
  20917. this.offset = 0; /* distance back to copy string from */
  20918. /* for table and code decoding */
  20919. this.extra = 0; /* extra bits needed */
  20920. /* fixed and dynamic code tables */
  20921. this.lencode = null; /* starting table for length/literal codes */
  20922. this.distcode = null; /* starting table for distance codes */
  20923. this.lenbits = 0; /* index bits for lencode */
  20924. this.distbits = 0; /* index bits for distcode */
  20925. /* dynamic table building */
  20926. this.ncode = 0; /* number of code length code lengths */
  20927. this.nlen = 0; /* number of length code lengths */
  20928. this.ndist = 0; /* number of distance code lengths */
  20929. this.have = 0; /* number of code lengths in lens[] */
  20930. this.next = null; /* next available space in codes[] */
  20931. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  20932. this.work = new utils.Buf16(288); /* work area for code table building */
  20933. /*
  20934. because we don't have pointers in js, we use lencode and distcode directly
  20935. as buffers so we don't need codes
  20936. */
  20937. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  20938. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  20939. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  20940. this.sane = 0; /* if false, allow invalid distance too far */
  20941. this.back = 0; /* bits back of last unprocessed length/lit */
  20942. this.was = 0; /* initial length of match */
  20943. }
  20944. function inflateResetKeep(strm) {
  20945. var state;
  20946. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20947. state = strm.state;
  20948. strm.total_in = strm.total_out = state.total = 0;
  20949. strm.msg = ''; /*Z_NULL*/
  20950. if (state.wrap) { /* to support ill-conceived Java test suite */
  20951. strm.adler = state.wrap & 1;
  20952. }
  20953. state.mode = HEAD;
  20954. state.last = 0;
  20955. state.havedict = 0;
  20956. state.dmax = 32768;
  20957. state.head = null/*Z_NULL*/;
  20958. state.hold = 0;
  20959. state.bits = 0;
  20960. //state.lencode = state.distcode = state.next = state.codes;
  20961. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  20962. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  20963. state.sane = 1;
  20964. state.back = -1;
  20965. //Tracev((stderr, "inflate: reset\n"));
  20966. return Z_OK;
  20967. }
  20968. function inflateReset(strm) {
  20969. var state;
  20970. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20971. state = strm.state;
  20972. state.wsize = 0;
  20973. state.whave = 0;
  20974. state.wnext = 0;
  20975. return inflateResetKeep(strm);
  20976. }
  20977. function inflateReset2(strm, windowBits) {
  20978. var wrap;
  20979. var state;
  20980. /* get the state */
  20981. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20982. state = strm.state;
  20983. /* extract wrap request from windowBits parameter */
  20984. if (windowBits < 0) {
  20985. wrap = 0;
  20986. windowBits = -windowBits;
  20987. }
  20988. else {
  20989. wrap = (windowBits >> 4) + 1;
  20990. if (windowBits < 48) {
  20991. windowBits &= 15;
  20992. }
  20993. }
  20994. /* set number of window bits, free window if different */
  20995. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  20996. return Z_STREAM_ERROR;
  20997. }
  20998. if (state.window !== null && state.wbits !== windowBits) {
  20999. state.window = null;
  21000. }
  21001. /* update state and reset the rest of it */
  21002. state.wrap = wrap;
  21003. state.wbits = windowBits;
  21004. return inflateReset(strm);
  21005. }
  21006. function inflateInit2(strm, windowBits) {
  21007. var ret;
  21008. var state;
  21009. if (!strm) { return Z_STREAM_ERROR; }
  21010. //strm.msg = Z_NULL; /* in case we return an error */
  21011. state = new InflateState();
  21012. //if (state === Z_NULL) return Z_MEM_ERROR;
  21013. //Tracev((stderr, "inflate: allocated\n"));
  21014. strm.state = state;
  21015. state.window = null/*Z_NULL*/;
  21016. ret = inflateReset2(strm, windowBits);
  21017. if (ret !== Z_OK) {
  21018. strm.state = null/*Z_NULL*/;
  21019. }
  21020. return ret;
  21021. }
  21022. function inflateInit(strm) {
  21023. return inflateInit2(strm, DEF_WBITS);
  21024. }
  21025. /*
  21026. Return state with length and distance decoding tables and index sizes set to
  21027. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  21028. If BUILDFIXED is defined, then instead this routine builds the tables the
  21029. first time it's called, and returns those tables the first time and
  21030. thereafter. This reduces the size of the code by about 2K bytes, in
  21031. exchange for a little execution time. However, BUILDFIXED should not be
  21032. used for threaded applications, since the rewriting of the tables and virgin
  21033. may not be thread-safe.
  21034. */
  21035. var virgin = true;
  21036. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  21037. function fixedtables(state) {
  21038. /* build fixed huffman tables if first call (may not be thread safe) */
  21039. if (virgin) {
  21040. var sym;
  21041. lenfix = new utils.Buf32(512);
  21042. distfix = new utils.Buf32(32);
  21043. /* literal/length table */
  21044. sym = 0;
  21045. while (sym < 144) { state.lens[sym++] = 8; }
  21046. while (sym < 256) { state.lens[sym++] = 9; }
  21047. while (sym < 280) { state.lens[sym++] = 7; }
  21048. while (sym < 288) { state.lens[sym++] = 8; }
  21049. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  21050. /* distance table */
  21051. sym = 0;
  21052. while (sym < 32) { state.lens[sym++] = 5; }
  21053. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  21054. /* do this just once */
  21055. virgin = false;
  21056. }
  21057. state.lencode = lenfix;
  21058. state.lenbits = 9;
  21059. state.distcode = distfix;
  21060. state.distbits = 5;
  21061. }
  21062. /*
  21063. Update the window with the last wsize (normally 32K) bytes written before
  21064. returning. If window does not exist yet, create it. This is only called
  21065. when a window is already in use, or when output has been written during this
  21066. inflate call, but the end of the deflate stream has not been reached yet.
  21067. It is also called to create a window for dictionary data when a dictionary
  21068. is loaded.
  21069. Providing output buffers larger than 32K to inflate() should provide a speed
  21070. advantage, since only the last 32K of output is copied to the sliding window
  21071. upon return from inflate(), and since all distances after the first 32K of
  21072. output will fall in the output data, making match copies simpler and faster.
  21073. The advantage may be dependent on the size of the processor's data caches.
  21074. */
  21075. function updatewindow(strm, src, end, copy) {
  21076. var dist;
  21077. var state = strm.state;
  21078. /* if it hasn't been done already, allocate space for the window */
  21079. if (state.window === null) {
  21080. state.wsize = 1 << state.wbits;
  21081. state.wnext = 0;
  21082. state.whave = 0;
  21083. state.window = new utils.Buf8(state.wsize);
  21084. }
  21085. /* copy state->wsize or less output bytes into the circular window */
  21086. if (copy >= state.wsize) {
  21087. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  21088. state.wnext = 0;
  21089. state.whave = state.wsize;
  21090. }
  21091. else {
  21092. dist = state.wsize - state.wnext;
  21093. if (dist > copy) {
  21094. dist = copy;
  21095. }
  21096. //zmemcpy(state->window + state->wnext, end - copy, dist);
  21097. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  21098. copy -= dist;
  21099. if (copy) {
  21100. //zmemcpy(state->window, end - copy, copy);
  21101. utils.arraySet(state.window,src, end - copy, copy, 0);
  21102. state.wnext = copy;
  21103. state.whave = state.wsize;
  21104. }
  21105. else {
  21106. state.wnext += dist;
  21107. if (state.wnext === state.wsize) { state.wnext = 0; }
  21108. if (state.whave < state.wsize) { state.whave += dist; }
  21109. }
  21110. }
  21111. return 0;
  21112. }
  21113. function inflate(strm, flush) {
  21114. var state;
  21115. var input, output; // input/output buffers
  21116. var next; /* next input INDEX */
  21117. var put; /* next output INDEX */
  21118. var have, left; /* available input and output */
  21119. var hold; /* bit buffer */
  21120. var bits; /* bits in bit buffer */
  21121. var _in, _out; /* save starting available input and output */
  21122. var copy; /* number of stored or match bytes to copy */
  21123. var from; /* where to copy match bytes from */
  21124. var from_source;
  21125. var here = 0; /* current decoding table entry */
  21126. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  21127. //var last; /* parent table entry */
  21128. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  21129. var len; /* length to copy for repeats, bits to drop */
  21130. var ret; /* return code */
  21131. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  21132. var opts;
  21133. var n; // temporary var for NEED_BITS
  21134. var order = /* permutation of code lengths */
  21135. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  21136. if (!strm || !strm.state || !strm.output ||
  21137. (!strm.input && strm.avail_in !== 0)) {
  21138. return Z_STREAM_ERROR;
  21139. }
  21140. state = strm.state;
  21141. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  21142. //--- LOAD() ---
  21143. put = strm.next_out;
  21144. output = strm.output;
  21145. left = strm.avail_out;
  21146. next = strm.next_in;
  21147. input = strm.input;
  21148. have = strm.avail_in;
  21149. hold = state.hold;
  21150. bits = state.bits;
  21151. //---
  21152. _in = have;
  21153. _out = left;
  21154. ret = Z_OK;
  21155. inf_leave: // goto emulation
  21156. for (;;) {
  21157. switch (state.mode) {
  21158. case HEAD:
  21159. if (state.wrap === 0) {
  21160. state.mode = TYPEDO;
  21161. break;
  21162. }
  21163. //=== NEEDBITS(16);
  21164. while (bits < 16) {
  21165. if (have === 0) { break inf_leave; }
  21166. have--;
  21167. hold += input[next++] << bits;
  21168. bits += 8;
  21169. }
  21170. //===//
  21171. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  21172. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  21173. //=== CRC2(state.check, hold);
  21174. hbuf[0] = hold & 0xff;
  21175. hbuf[1] = (hold >>> 8) & 0xff;
  21176. state.check = crc32(state.check, hbuf, 2, 0);
  21177. //===//
  21178. //=== INITBITS();
  21179. hold = 0;
  21180. bits = 0;
  21181. //===//
  21182. state.mode = FLAGS;
  21183. break;
  21184. }
  21185. state.flags = 0; /* expect zlib header */
  21186. if (state.head) {
  21187. state.head.done = false;
  21188. }
  21189. if (!(state.wrap & 1) || /* check if zlib header allowed */
  21190. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  21191. strm.msg = 'incorrect header check';
  21192. state.mode = BAD;
  21193. break;
  21194. }
  21195. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  21196. strm.msg = 'unknown compression method';
  21197. state.mode = BAD;
  21198. break;
  21199. }
  21200. //--- DROPBITS(4) ---//
  21201. hold >>>= 4;
  21202. bits -= 4;
  21203. //---//
  21204. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  21205. if (state.wbits === 0) {
  21206. state.wbits = len;
  21207. }
  21208. else if (len > state.wbits) {
  21209. strm.msg = 'invalid window size';
  21210. state.mode = BAD;
  21211. break;
  21212. }
  21213. state.dmax = 1 << len;
  21214. //Tracev((stderr, "inflate: zlib header ok\n"));
  21215. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  21216. state.mode = hold & 0x200 ? DICTID : TYPE;
  21217. //=== INITBITS();
  21218. hold = 0;
  21219. bits = 0;
  21220. //===//
  21221. break;
  21222. case FLAGS:
  21223. //=== NEEDBITS(16); */
  21224. while (bits < 16) {
  21225. if (have === 0) { break inf_leave; }
  21226. have--;
  21227. hold += input[next++] << bits;
  21228. bits += 8;
  21229. }
  21230. //===//
  21231. state.flags = hold;
  21232. if ((state.flags & 0xff) !== Z_DEFLATED) {
  21233. strm.msg = 'unknown compression method';
  21234. state.mode = BAD;
  21235. break;
  21236. }
  21237. if (state.flags & 0xe000) {
  21238. strm.msg = 'unknown header flags set';
  21239. state.mode = BAD;
  21240. break;
  21241. }
  21242. if (state.head) {
  21243. state.head.text = ((hold >> 8) & 1);
  21244. }
  21245. if (state.flags & 0x0200) {
  21246. //=== CRC2(state.check, hold);
  21247. hbuf[0] = hold & 0xff;
  21248. hbuf[1] = (hold >>> 8) & 0xff;
  21249. state.check = crc32(state.check, hbuf, 2, 0);
  21250. //===//
  21251. }
  21252. //=== INITBITS();
  21253. hold = 0;
  21254. bits = 0;
  21255. //===//
  21256. state.mode = TIME;
  21257. /* falls through */
  21258. case TIME:
  21259. //=== NEEDBITS(32); */
  21260. while (bits < 32) {
  21261. if (have === 0) { break inf_leave; }
  21262. have--;
  21263. hold += input[next++] << bits;
  21264. bits += 8;
  21265. }
  21266. //===//
  21267. if (state.head) {
  21268. state.head.time = hold;
  21269. }
  21270. if (state.flags & 0x0200) {
  21271. //=== CRC4(state.check, hold)
  21272. hbuf[0] = hold & 0xff;
  21273. hbuf[1] = (hold >>> 8) & 0xff;
  21274. hbuf[2] = (hold >>> 16) & 0xff;
  21275. hbuf[3] = (hold >>> 24) & 0xff;
  21276. state.check = crc32(state.check, hbuf, 4, 0);
  21277. //===
  21278. }
  21279. //=== INITBITS();
  21280. hold = 0;
  21281. bits = 0;
  21282. //===//
  21283. state.mode = OS;
  21284. /* falls through */
  21285. case OS:
  21286. //=== NEEDBITS(16); */
  21287. while (bits < 16) {
  21288. if (have === 0) { break inf_leave; }
  21289. have--;
  21290. hold += input[next++] << bits;
  21291. bits += 8;
  21292. }
  21293. //===//
  21294. if (state.head) {
  21295. state.head.xflags = (hold & 0xff);
  21296. state.head.os = (hold >> 8);
  21297. }
  21298. if (state.flags & 0x0200) {
  21299. //=== CRC2(state.check, hold);
  21300. hbuf[0] = hold & 0xff;
  21301. hbuf[1] = (hold >>> 8) & 0xff;
  21302. state.check = crc32(state.check, hbuf, 2, 0);
  21303. //===//
  21304. }
  21305. //=== INITBITS();
  21306. hold = 0;
  21307. bits = 0;
  21308. //===//
  21309. state.mode = EXLEN;
  21310. /* falls through */
  21311. case EXLEN:
  21312. if (state.flags & 0x0400) {
  21313. //=== NEEDBITS(16); */
  21314. while (bits < 16) {
  21315. if (have === 0) { break inf_leave; }
  21316. have--;
  21317. hold += input[next++] << bits;
  21318. bits += 8;
  21319. }
  21320. //===//
  21321. state.length = hold;
  21322. if (state.head) {
  21323. state.head.extra_len = hold;
  21324. }
  21325. if (state.flags & 0x0200) {
  21326. //=== CRC2(state.check, hold);
  21327. hbuf[0] = hold & 0xff;
  21328. hbuf[1] = (hold >>> 8) & 0xff;
  21329. state.check = crc32(state.check, hbuf, 2, 0);
  21330. //===//
  21331. }
  21332. //=== INITBITS();
  21333. hold = 0;
  21334. bits = 0;
  21335. //===//
  21336. }
  21337. else if (state.head) {
  21338. state.head.extra = null/*Z_NULL*/;
  21339. }
  21340. state.mode = EXTRA;
  21341. /* falls through */
  21342. case EXTRA:
  21343. if (state.flags & 0x0400) {
  21344. copy = state.length;
  21345. if (copy > have) { copy = have; }
  21346. if (copy) {
  21347. if (state.head) {
  21348. len = state.head.extra_len - state.length;
  21349. if (!state.head.extra) {
  21350. // Use untyped array for more conveniend processing later
  21351. state.head.extra = new Array(state.head.extra_len);
  21352. }
  21353. utils.arraySet(
  21354. state.head.extra,
  21355. input,
  21356. next,
  21357. // extra field is limited to 65536 bytes
  21358. // - no need for additional size check
  21359. copy,
  21360. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  21361. len
  21362. );
  21363. //zmemcpy(state.head.extra + len, next,
  21364. // len + copy > state.head.extra_max ?
  21365. // state.head.extra_max - len : copy);
  21366. }
  21367. if (state.flags & 0x0200) {
  21368. state.check = crc32(state.check, input, copy, next);
  21369. }
  21370. have -= copy;
  21371. next += copy;
  21372. state.length -= copy;
  21373. }
  21374. if (state.length) { break inf_leave; }
  21375. }
  21376. state.length = 0;
  21377. state.mode = NAME;
  21378. /* falls through */
  21379. case NAME:
  21380. if (state.flags & 0x0800) {
  21381. if (have === 0) { break inf_leave; }
  21382. copy = 0;
  21383. do {
  21384. // TODO: 2 or 1 bytes?
  21385. len = input[next + copy++];
  21386. /* use constant limit because in js we should not preallocate memory */
  21387. if (state.head && len &&
  21388. (state.length < 65536 /*state.head.name_max*/)) {
  21389. state.head.name += String.fromCharCode(len);
  21390. }
  21391. } while (len && copy < have);
  21392. if (state.flags & 0x0200) {
  21393. state.check = crc32(state.check, input, copy, next);
  21394. }
  21395. have -= copy;
  21396. next += copy;
  21397. if (len) { break inf_leave; }
  21398. }
  21399. else if (state.head) {
  21400. state.head.name = null;
  21401. }
  21402. state.length = 0;
  21403. state.mode = COMMENT;
  21404. /* falls through */
  21405. case COMMENT:
  21406. if (state.flags & 0x1000) {
  21407. if (have === 0) { break inf_leave; }
  21408. copy = 0;
  21409. do {
  21410. len = input[next + copy++];
  21411. /* use constant limit because in js we should not preallocate memory */
  21412. if (state.head && len &&
  21413. (state.length < 65536 /*state.head.comm_max*/)) {
  21414. state.head.comment += String.fromCharCode(len);
  21415. }
  21416. } while (len && copy < have);
  21417. if (state.flags & 0x0200) {
  21418. state.check = crc32(state.check, input, copy, next);
  21419. }
  21420. have -= copy;
  21421. next += copy;
  21422. if (len) { break inf_leave; }
  21423. }
  21424. else if (state.head) {
  21425. state.head.comment = null;
  21426. }
  21427. state.mode = HCRC;
  21428. /* falls through */
  21429. case HCRC:
  21430. if (state.flags & 0x0200) {
  21431. //=== NEEDBITS(16); */
  21432. while (bits < 16) {
  21433. if (have === 0) { break inf_leave; }
  21434. have--;
  21435. hold += input[next++] << bits;
  21436. bits += 8;
  21437. }
  21438. //===//
  21439. if (hold !== (state.check & 0xffff)) {
  21440. strm.msg = 'header crc mismatch';
  21441. state.mode = BAD;
  21442. break;
  21443. }
  21444. //=== INITBITS();
  21445. hold = 0;
  21446. bits = 0;
  21447. //===//
  21448. }
  21449. if (state.head) {
  21450. state.head.hcrc = ((state.flags >> 9) & 1);
  21451. state.head.done = true;
  21452. }
  21453. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  21454. state.mode = TYPE;
  21455. break;
  21456. case DICTID:
  21457. //=== NEEDBITS(32); */
  21458. while (bits < 32) {
  21459. if (have === 0) { break inf_leave; }
  21460. have--;
  21461. hold += input[next++] << bits;
  21462. bits += 8;
  21463. }
  21464. //===//
  21465. strm.adler = state.check = ZSWAP32(hold);
  21466. //=== INITBITS();
  21467. hold = 0;
  21468. bits = 0;
  21469. //===//
  21470. state.mode = DICT;
  21471. /* falls through */
  21472. case DICT:
  21473. if (state.havedict === 0) {
  21474. //--- RESTORE() ---
  21475. strm.next_out = put;
  21476. strm.avail_out = left;
  21477. strm.next_in = next;
  21478. strm.avail_in = have;
  21479. state.hold = hold;
  21480. state.bits = bits;
  21481. //---
  21482. return Z_NEED_DICT;
  21483. }
  21484. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  21485. state.mode = TYPE;
  21486. /* falls through */
  21487. case TYPE:
  21488. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  21489. /* falls through */
  21490. case TYPEDO:
  21491. if (state.last) {
  21492. //--- BYTEBITS() ---//
  21493. hold >>>= bits & 7;
  21494. bits -= bits & 7;
  21495. //---//
  21496. state.mode = CHECK;
  21497. break;
  21498. }
  21499. //=== NEEDBITS(3); */
  21500. while (bits < 3) {
  21501. if (have === 0) { break inf_leave; }
  21502. have--;
  21503. hold += input[next++] << bits;
  21504. bits += 8;
  21505. }
  21506. //===//
  21507. state.last = (hold & 0x01)/*BITS(1)*/;
  21508. //--- DROPBITS(1) ---//
  21509. hold >>>= 1;
  21510. bits -= 1;
  21511. //---//
  21512. switch ((hold & 0x03)/*BITS(2)*/) {
  21513. case 0: /* stored block */
  21514. //Tracev((stderr, "inflate: stored block%s\n",
  21515. // state.last ? " (last)" : ""));
  21516. state.mode = STORED;
  21517. break;
  21518. case 1: /* fixed block */
  21519. fixedtables(state);
  21520. //Tracev((stderr, "inflate: fixed codes block%s\n",
  21521. // state.last ? " (last)" : ""));
  21522. state.mode = LEN_; /* decode codes */
  21523. if (flush === Z_TREES) {
  21524. //--- DROPBITS(2) ---//
  21525. hold >>>= 2;
  21526. bits -= 2;
  21527. //---//
  21528. break inf_leave;
  21529. }
  21530. break;
  21531. case 2: /* dynamic block */
  21532. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  21533. // state.last ? " (last)" : ""));
  21534. state.mode = TABLE;
  21535. break;
  21536. case 3:
  21537. strm.msg = 'invalid block type';
  21538. state.mode = BAD;
  21539. }
  21540. //--- DROPBITS(2) ---//
  21541. hold >>>= 2;
  21542. bits -= 2;
  21543. //---//
  21544. break;
  21545. case STORED:
  21546. //--- BYTEBITS() ---// /* go to byte boundary */
  21547. hold >>>= bits & 7;
  21548. bits -= bits & 7;
  21549. //---//
  21550. //=== NEEDBITS(32); */
  21551. while (bits < 32) {
  21552. if (have === 0) { break inf_leave; }
  21553. have--;
  21554. hold += input[next++] << bits;
  21555. bits += 8;
  21556. }
  21557. //===//
  21558. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  21559. strm.msg = 'invalid stored block lengths';
  21560. state.mode = BAD;
  21561. break;
  21562. }
  21563. state.length = hold & 0xffff;
  21564. //Tracev((stderr, "inflate: stored length %u\n",
  21565. // state.length));
  21566. //=== INITBITS();
  21567. hold = 0;
  21568. bits = 0;
  21569. //===//
  21570. state.mode = COPY_;
  21571. if (flush === Z_TREES) { break inf_leave; }
  21572. /* falls through */
  21573. case COPY_:
  21574. state.mode = COPY;
  21575. /* falls through */
  21576. case COPY:
  21577. copy = state.length;
  21578. if (copy) {
  21579. if (copy > have) { copy = have; }
  21580. if (copy > left) { copy = left; }
  21581. if (copy === 0) { break inf_leave; }
  21582. //--- zmemcpy(put, next, copy); ---
  21583. utils.arraySet(output, input, next, copy, put);
  21584. //---//
  21585. have -= copy;
  21586. next += copy;
  21587. left -= copy;
  21588. put += copy;
  21589. state.length -= copy;
  21590. break;
  21591. }
  21592. //Tracev((stderr, "inflate: stored end\n"));
  21593. state.mode = TYPE;
  21594. break;
  21595. case TABLE:
  21596. //=== NEEDBITS(14); */
  21597. while (bits < 14) {
  21598. if (have === 0) { break inf_leave; }
  21599. have--;
  21600. hold += input[next++] << bits;
  21601. bits += 8;
  21602. }
  21603. //===//
  21604. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  21605. //--- DROPBITS(5) ---//
  21606. hold >>>= 5;
  21607. bits -= 5;
  21608. //---//
  21609. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  21610. //--- DROPBITS(5) ---//
  21611. hold >>>= 5;
  21612. bits -= 5;
  21613. //---//
  21614. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  21615. //--- DROPBITS(4) ---//
  21616. hold >>>= 4;
  21617. bits -= 4;
  21618. //---//
  21619. //#ifndef PKZIP_BUG_WORKAROUND
  21620. if (state.nlen > 286 || state.ndist > 30) {
  21621. strm.msg = 'too many length or distance symbols';
  21622. state.mode = BAD;
  21623. break;
  21624. }
  21625. //#endif
  21626. //Tracev((stderr, "inflate: table sizes ok\n"));
  21627. state.have = 0;
  21628. state.mode = LENLENS;
  21629. /* falls through */
  21630. case LENLENS:
  21631. while (state.have < state.ncode) {
  21632. //=== NEEDBITS(3);
  21633. while (bits < 3) {
  21634. if (have === 0) { break inf_leave; }
  21635. have--;
  21636. hold += input[next++] << bits;
  21637. bits += 8;
  21638. }
  21639. //===//
  21640. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  21641. //--- DROPBITS(3) ---//
  21642. hold >>>= 3;
  21643. bits -= 3;
  21644. //---//
  21645. }
  21646. while (state.have < 19) {
  21647. state.lens[order[state.have++]] = 0;
  21648. }
  21649. // We have separate tables & no pointers. 2 commented lines below not needed.
  21650. //state.next = state.codes;
  21651. //state.lencode = state.next;
  21652. // Switch to use dynamic table
  21653. state.lencode = state.lendyn;
  21654. state.lenbits = 7;
  21655. opts = {bits: state.lenbits};
  21656. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  21657. state.lenbits = opts.bits;
  21658. if (ret) {
  21659. strm.msg = 'invalid code lengths set';
  21660. state.mode = BAD;
  21661. break;
  21662. }
  21663. //Tracev((stderr, "inflate: code lengths ok\n"));
  21664. state.have = 0;
  21665. state.mode = CODELENS;
  21666. /* falls through */
  21667. case CODELENS:
  21668. while (state.have < state.nlen + state.ndist) {
  21669. for (;;) {
  21670. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  21671. here_bits = here >>> 24;
  21672. here_op = (here >>> 16) & 0xff;
  21673. here_val = here & 0xffff;
  21674. if ((here_bits) <= bits) { break; }
  21675. //--- PULLBYTE() ---//
  21676. if (have === 0) { break inf_leave; }
  21677. have--;
  21678. hold += input[next++] << bits;
  21679. bits += 8;
  21680. //---//
  21681. }
  21682. if (here_val < 16) {
  21683. //--- DROPBITS(here.bits) ---//
  21684. hold >>>= here_bits;
  21685. bits -= here_bits;
  21686. //---//
  21687. state.lens[state.have++] = here_val;
  21688. }
  21689. else {
  21690. if (here_val === 16) {
  21691. //=== NEEDBITS(here.bits + 2);
  21692. n = here_bits + 2;
  21693. while (bits < n) {
  21694. if (have === 0) { break inf_leave; }
  21695. have--;
  21696. hold += input[next++] << bits;
  21697. bits += 8;
  21698. }
  21699. //===//
  21700. //--- DROPBITS(here.bits) ---//
  21701. hold >>>= here_bits;
  21702. bits -= here_bits;
  21703. //---//
  21704. if (state.have === 0) {
  21705. strm.msg = 'invalid bit length repeat';
  21706. state.mode = BAD;
  21707. break;
  21708. }
  21709. len = state.lens[state.have - 1];
  21710. copy = 3 + (hold & 0x03);//BITS(2);
  21711. //--- DROPBITS(2) ---//
  21712. hold >>>= 2;
  21713. bits -= 2;
  21714. //---//
  21715. }
  21716. else if (here_val === 17) {
  21717. //=== NEEDBITS(here.bits + 3);
  21718. n = here_bits + 3;
  21719. while (bits < n) {
  21720. if (have === 0) { break inf_leave; }
  21721. have--;
  21722. hold += input[next++] << bits;
  21723. bits += 8;
  21724. }
  21725. //===//
  21726. //--- DROPBITS(here.bits) ---//
  21727. hold >>>= here_bits;
  21728. bits -= here_bits;
  21729. //---//
  21730. len = 0;
  21731. copy = 3 + (hold & 0x07);//BITS(3);
  21732. //--- DROPBITS(3) ---//
  21733. hold >>>= 3;
  21734. bits -= 3;
  21735. //---//
  21736. }
  21737. else {
  21738. //=== NEEDBITS(here.bits + 7);
  21739. n = here_bits + 7;
  21740. while (bits < n) {
  21741. if (have === 0) { break inf_leave; }
  21742. have--;
  21743. hold += input[next++] << bits;
  21744. bits += 8;
  21745. }
  21746. //===//
  21747. //--- DROPBITS(here.bits) ---//
  21748. hold >>>= here_bits;
  21749. bits -= here_bits;
  21750. //---//
  21751. len = 0;
  21752. copy = 11 + (hold & 0x7f);//BITS(7);
  21753. //--- DROPBITS(7) ---//
  21754. hold >>>= 7;
  21755. bits -= 7;
  21756. //---//
  21757. }
  21758. if (state.have + copy > state.nlen + state.ndist) {
  21759. strm.msg = 'invalid bit length repeat';
  21760. state.mode = BAD;
  21761. break;
  21762. }
  21763. while (copy--) {
  21764. state.lens[state.have++] = len;
  21765. }
  21766. }
  21767. }
  21768. /* handle error breaks in while */
  21769. if (state.mode === BAD) { break; }
  21770. /* check for end-of-block code (better have one) */
  21771. if (state.lens[256] === 0) {
  21772. strm.msg = 'invalid code -- missing end-of-block';
  21773. state.mode = BAD;
  21774. break;
  21775. }
  21776. /* build code tables -- note: do not change the lenbits or distbits
  21777. values here (9 and 6) without reading the comments in inftrees.h
  21778. concerning the ENOUGH constants, which depend on those values */
  21779. state.lenbits = 9;
  21780. opts = {bits: state.lenbits};
  21781. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  21782. // We have separate tables & no pointers. 2 commented lines below not needed.
  21783. // state.next_index = opts.table_index;
  21784. state.lenbits = opts.bits;
  21785. // state.lencode = state.next;
  21786. if (ret) {
  21787. strm.msg = 'invalid literal/lengths set';
  21788. state.mode = BAD;
  21789. break;
  21790. }
  21791. state.distbits = 6;
  21792. //state.distcode.copy(state.codes);
  21793. // Switch to use dynamic table
  21794. state.distcode = state.distdyn;
  21795. opts = {bits: state.distbits};
  21796. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  21797. // We have separate tables & no pointers. 2 commented lines below not needed.
  21798. // state.next_index = opts.table_index;
  21799. state.distbits = opts.bits;
  21800. // state.distcode = state.next;
  21801. if (ret) {
  21802. strm.msg = 'invalid distances set';
  21803. state.mode = BAD;
  21804. break;
  21805. }
  21806. //Tracev((stderr, 'inflate: codes ok\n'));
  21807. state.mode = LEN_;
  21808. if (flush === Z_TREES) { break inf_leave; }
  21809. /* falls through */
  21810. case LEN_:
  21811. state.mode = LEN;
  21812. /* falls through */
  21813. case LEN:
  21814. if (have >= 6 && left >= 258) {
  21815. //--- RESTORE() ---
  21816. strm.next_out = put;
  21817. strm.avail_out = left;
  21818. strm.next_in = next;
  21819. strm.avail_in = have;
  21820. state.hold = hold;
  21821. state.bits = bits;
  21822. //---
  21823. inflate_fast(strm, _out);
  21824. //--- LOAD() ---
  21825. put = strm.next_out;
  21826. output = strm.output;
  21827. left = strm.avail_out;
  21828. next = strm.next_in;
  21829. input = strm.input;
  21830. have = strm.avail_in;
  21831. hold = state.hold;
  21832. bits = state.bits;
  21833. //---
  21834. if (state.mode === TYPE) {
  21835. state.back = -1;
  21836. }
  21837. break;
  21838. }
  21839. state.back = 0;
  21840. for (;;) {
  21841. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  21842. here_bits = here >>> 24;
  21843. here_op = (here >>> 16) & 0xff;
  21844. here_val = here & 0xffff;
  21845. if (here_bits <= bits) { break; }
  21846. //--- PULLBYTE() ---//
  21847. if (have === 0) { break inf_leave; }
  21848. have--;
  21849. hold += input[next++] << bits;
  21850. bits += 8;
  21851. //---//
  21852. }
  21853. if (here_op && (here_op & 0xf0) === 0) {
  21854. last_bits = here_bits;
  21855. last_op = here_op;
  21856. last_val = here_val;
  21857. for (;;) {
  21858. here = state.lencode[last_val +
  21859. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  21860. here_bits = here >>> 24;
  21861. here_op = (here >>> 16) & 0xff;
  21862. here_val = here & 0xffff;
  21863. if ((last_bits + here_bits) <= bits) { break; }
  21864. //--- PULLBYTE() ---//
  21865. if (have === 0) { break inf_leave; }
  21866. have--;
  21867. hold += input[next++] << bits;
  21868. bits += 8;
  21869. //---//
  21870. }
  21871. //--- DROPBITS(last.bits) ---//
  21872. hold >>>= last_bits;
  21873. bits -= last_bits;
  21874. //---//
  21875. state.back += last_bits;
  21876. }
  21877. //--- DROPBITS(here.bits) ---//
  21878. hold >>>= here_bits;
  21879. bits -= here_bits;
  21880. //---//
  21881. state.back += here_bits;
  21882. state.length = here_val;
  21883. if (here_op === 0) {
  21884. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21885. // "inflate: literal '%c'\n" :
  21886. // "inflate: literal 0x%02x\n", here.val));
  21887. state.mode = LIT;
  21888. break;
  21889. }
  21890. if (here_op & 32) {
  21891. //Tracevv((stderr, "inflate: end of block\n"));
  21892. state.back = -1;
  21893. state.mode = TYPE;
  21894. break;
  21895. }
  21896. if (here_op & 64) {
  21897. strm.msg = 'invalid literal/length code';
  21898. state.mode = BAD;
  21899. break;
  21900. }
  21901. state.extra = here_op & 15;
  21902. state.mode = LENEXT;
  21903. /* falls through */
  21904. case LENEXT:
  21905. if (state.extra) {
  21906. //=== NEEDBITS(state.extra);
  21907. n = state.extra;
  21908. while (bits < n) {
  21909. if (have === 0) { break inf_leave; }
  21910. have--;
  21911. hold += input[next++] << bits;
  21912. bits += 8;
  21913. }
  21914. //===//
  21915. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21916. //--- DROPBITS(state.extra) ---//
  21917. hold >>>= state.extra;
  21918. bits -= state.extra;
  21919. //---//
  21920. state.back += state.extra;
  21921. }
  21922. //Tracevv((stderr, "inflate: length %u\n", state.length));
  21923. state.was = state.length;
  21924. state.mode = DIST;
  21925. /* falls through */
  21926. case DIST:
  21927. for (;;) {
  21928. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  21929. here_bits = here >>> 24;
  21930. here_op = (here >>> 16) & 0xff;
  21931. here_val = here & 0xffff;
  21932. if ((here_bits) <= bits) { break; }
  21933. //--- PULLBYTE() ---//
  21934. if (have === 0) { break inf_leave; }
  21935. have--;
  21936. hold += input[next++] << bits;
  21937. bits += 8;
  21938. //---//
  21939. }
  21940. if ((here_op & 0xf0) === 0) {
  21941. last_bits = here_bits;
  21942. last_op = here_op;
  21943. last_val = here_val;
  21944. for (;;) {
  21945. here = state.distcode[last_val +
  21946. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  21947. here_bits = here >>> 24;
  21948. here_op = (here >>> 16) & 0xff;
  21949. here_val = here & 0xffff;
  21950. if ((last_bits + here_bits) <= bits) { break; }
  21951. //--- PULLBYTE() ---//
  21952. if (have === 0) { break inf_leave; }
  21953. have--;
  21954. hold += input[next++] << bits;
  21955. bits += 8;
  21956. //---//
  21957. }
  21958. //--- DROPBITS(last.bits) ---//
  21959. hold >>>= last_bits;
  21960. bits -= last_bits;
  21961. //---//
  21962. state.back += last_bits;
  21963. }
  21964. //--- DROPBITS(here.bits) ---//
  21965. hold >>>= here_bits;
  21966. bits -= here_bits;
  21967. //---//
  21968. state.back += here_bits;
  21969. if (here_op & 64) {
  21970. strm.msg = 'invalid distance code';
  21971. state.mode = BAD;
  21972. break;
  21973. }
  21974. state.offset = here_val;
  21975. state.extra = (here_op) & 15;
  21976. state.mode = DISTEXT;
  21977. /* falls through */
  21978. case DISTEXT:
  21979. if (state.extra) {
  21980. //=== NEEDBITS(state.extra);
  21981. n = state.extra;
  21982. while (bits < n) {
  21983. if (have === 0) { break inf_leave; }
  21984. have--;
  21985. hold += input[next++] << bits;
  21986. bits += 8;
  21987. }
  21988. //===//
  21989. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21990. //--- DROPBITS(state.extra) ---//
  21991. hold >>>= state.extra;
  21992. bits -= state.extra;
  21993. //---//
  21994. state.back += state.extra;
  21995. }
  21996. //#ifdef INFLATE_STRICT
  21997. if (state.offset > state.dmax) {
  21998. strm.msg = 'invalid distance too far back';
  21999. state.mode = BAD;
  22000. break;
  22001. }
  22002. //#endif
  22003. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  22004. state.mode = MATCH;
  22005. /* falls through */
  22006. case MATCH:
  22007. if (left === 0) { break inf_leave; }
  22008. copy = _out - left;
  22009. if (state.offset > copy) { /* copy from window */
  22010. copy = state.offset - copy;
  22011. if (copy > state.whave) {
  22012. if (state.sane) {
  22013. strm.msg = 'invalid distance too far back';
  22014. state.mode = BAD;
  22015. break;
  22016. }
  22017. // (!) This block is disabled in zlib defailts,
  22018. // don't enable it for binary compatibility
  22019. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22020. // Trace((stderr, "inflate.c too far\n"));
  22021. // copy -= state.whave;
  22022. // if (copy > state.length) { copy = state.length; }
  22023. // if (copy > left) { copy = left; }
  22024. // left -= copy;
  22025. // state.length -= copy;
  22026. // do {
  22027. // output[put++] = 0;
  22028. // } while (--copy);
  22029. // if (state.length === 0) { state.mode = LEN; }
  22030. // break;
  22031. //#endif
  22032. }
  22033. if (copy > state.wnext) {
  22034. copy -= state.wnext;
  22035. from = state.wsize - copy;
  22036. }
  22037. else {
  22038. from = state.wnext - copy;
  22039. }
  22040. if (copy > state.length) { copy = state.length; }
  22041. from_source = state.window;
  22042. }
  22043. else { /* copy from output */
  22044. from_source = output;
  22045. from = put - state.offset;
  22046. copy = state.length;
  22047. }
  22048. if (copy > left) { copy = left; }
  22049. left -= copy;
  22050. state.length -= copy;
  22051. do {
  22052. output[put++] = from_source[from++];
  22053. } while (--copy);
  22054. if (state.length === 0) { state.mode = LEN; }
  22055. break;
  22056. case LIT:
  22057. if (left === 0) { break inf_leave; }
  22058. output[put++] = state.length;
  22059. left--;
  22060. state.mode = LEN;
  22061. break;
  22062. case CHECK:
  22063. if (state.wrap) {
  22064. //=== NEEDBITS(32);
  22065. while (bits < 32) {
  22066. if (have === 0) { break inf_leave; }
  22067. have--;
  22068. // Use '|' insdead of '+' to make sure that result is signed
  22069. hold |= input[next++] << bits;
  22070. bits += 8;
  22071. }
  22072. //===//
  22073. _out -= left;
  22074. strm.total_out += _out;
  22075. state.total += _out;
  22076. if (_out) {
  22077. strm.adler = state.check =
  22078. /*UPDATE(state.check, put - _out, _out);*/
  22079. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  22080. }
  22081. _out = left;
  22082. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  22083. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  22084. strm.msg = 'incorrect data check';
  22085. state.mode = BAD;
  22086. break;
  22087. }
  22088. //=== INITBITS();
  22089. hold = 0;
  22090. bits = 0;
  22091. //===//
  22092. //Tracev((stderr, "inflate: check matches trailer\n"));
  22093. }
  22094. state.mode = LENGTH;
  22095. /* falls through */
  22096. case LENGTH:
  22097. if (state.wrap && state.flags) {
  22098. //=== NEEDBITS(32);
  22099. while (bits < 32) {
  22100. if (have === 0) { break inf_leave; }
  22101. have--;
  22102. hold += input[next++] << bits;
  22103. bits += 8;
  22104. }
  22105. //===//
  22106. if (hold !== (state.total & 0xffffffff)) {
  22107. strm.msg = 'incorrect length check';
  22108. state.mode = BAD;
  22109. break;
  22110. }
  22111. //=== INITBITS();
  22112. hold = 0;
  22113. bits = 0;
  22114. //===//
  22115. //Tracev((stderr, "inflate: length matches trailer\n"));
  22116. }
  22117. state.mode = DONE;
  22118. /* falls through */
  22119. case DONE:
  22120. ret = Z_STREAM_END;
  22121. break inf_leave;
  22122. case BAD:
  22123. ret = Z_DATA_ERROR;
  22124. break inf_leave;
  22125. case MEM:
  22126. return Z_MEM_ERROR;
  22127. case SYNC:
  22128. /* falls through */
  22129. default:
  22130. return Z_STREAM_ERROR;
  22131. }
  22132. }
  22133. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  22134. /*
  22135. Return from inflate(), updating the total counts and the check value.
  22136. If there was no progress during the inflate() call, return a buffer
  22137. error. Call updatewindow() to create and/or update the window state.
  22138. Note: a memory error from inflate() is non-recoverable.
  22139. */
  22140. //--- RESTORE() ---
  22141. strm.next_out = put;
  22142. strm.avail_out = left;
  22143. strm.next_in = next;
  22144. strm.avail_in = have;
  22145. state.hold = hold;
  22146. state.bits = bits;
  22147. //---
  22148. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  22149. (state.mode < CHECK || flush !== Z_FINISH))) {
  22150. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  22151. state.mode = MEM;
  22152. return Z_MEM_ERROR;
  22153. }
  22154. }
  22155. _in -= strm.avail_in;
  22156. _out -= strm.avail_out;
  22157. strm.total_in += _in;
  22158. strm.total_out += _out;
  22159. state.total += _out;
  22160. if (state.wrap && _out) {
  22161. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  22162. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  22163. }
  22164. strm.data_type = state.bits + (state.last ? 64 : 0) +
  22165. (state.mode === TYPE ? 128 : 0) +
  22166. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  22167. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  22168. ret = Z_BUF_ERROR;
  22169. }
  22170. return ret;
  22171. }
  22172. function inflateEnd(strm) {
  22173. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  22174. return Z_STREAM_ERROR;
  22175. }
  22176. var state = strm.state;
  22177. if (state.window) {
  22178. state.window = null;
  22179. }
  22180. strm.state = null;
  22181. return Z_OK;
  22182. }
  22183. function inflateGetHeader(strm, head) {
  22184. var state;
  22185. /* check state */
  22186. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22187. state = strm.state;
  22188. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  22189. /* save header structure */
  22190. state.head = head;
  22191. head.done = false;
  22192. return Z_OK;
  22193. }
  22194. exports.inflateReset = inflateReset;
  22195. exports.inflateReset2 = inflateReset2;
  22196. exports.inflateResetKeep = inflateResetKeep;
  22197. exports.inflateInit = inflateInit;
  22198. exports.inflateInit2 = inflateInit2;
  22199. exports.inflate = inflate;
  22200. exports.inflateEnd = inflateEnd;
  22201. exports.inflateGetHeader = inflateGetHeader;
  22202. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  22203. /* Not implemented
  22204. exports.inflateCopy = inflateCopy;
  22205. exports.inflateGetDictionary = inflateGetDictionary;
  22206. exports.inflateMark = inflateMark;
  22207. exports.inflatePrime = inflatePrime;
  22208. exports.inflateSetDictionary = inflateSetDictionary;
  22209. exports.inflateSync = inflateSync;
  22210. exports.inflateSyncPoint = inflateSyncPoint;
  22211. exports.inflateUndermine = inflateUndermine;
  22212. */
  22213. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./inffast":79,"./inftrees":81}],81:[function(require,module,exports){
  22214. 'use strict';
  22215. var utils = require('../utils/common');
  22216. var MAXBITS = 15;
  22217. var ENOUGH_LENS = 852;
  22218. var ENOUGH_DISTS = 592;
  22219. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22220. var CODES = 0;
  22221. var LENS = 1;
  22222. var DISTS = 2;
  22223. var lbase = [ /* Length codes 257..285 base */
  22224. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  22225. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  22226. ];
  22227. var lext = [ /* Length codes 257..285 extra */
  22228. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  22229. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  22230. ];
  22231. var dbase = [ /* Distance codes 0..29 base */
  22232. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  22233. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  22234. 8193, 12289, 16385, 24577, 0, 0
  22235. ];
  22236. var dext = [ /* Distance codes 0..29 extra */
  22237. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  22238. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  22239. 28, 28, 29, 29, 64, 64
  22240. ];
  22241. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  22242. {
  22243. var bits = opts.bits;
  22244. //here = opts.here; /* table entry for duplication */
  22245. var len = 0; /* a code's length in bits */
  22246. var sym = 0; /* index of code symbols */
  22247. var min = 0, max = 0; /* minimum and maximum code lengths */
  22248. var root = 0; /* number of index bits for root table */
  22249. var curr = 0; /* number of index bits for current table */
  22250. var drop = 0; /* code bits to drop for sub-table */
  22251. var left = 0; /* number of prefix codes available */
  22252. var used = 0; /* code entries in table used */
  22253. var huff = 0; /* Huffman code */
  22254. var incr; /* for incrementing code, index */
  22255. var fill; /* index for replicating entries */
  22256. var low; /* low bits for current root entry */
  22257. var mask; /* mask for low root bits */
  22258. var next; /* next available space in table */
  22259. var base = null; /* base value table to use */
  22260. var base_index = 0;
  22261. // var shoextra; /* extra bits table to use */
  22262. var end; /* use base and extra for symbol > end */
  22263. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  22264. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  22265. var extra = null;
  22266. var extra_index = 0;
  22267. var here_bits, here_op, here_val;
  22268. /*
  22269. Process a set of code lengths to create a canonical Huffman code. The
  22270. code lengths are lens[0..codes-1]. Each length corresponds to the
  22271. symbols 0..codes-1. The Huffman code is generated by first sorting the
  22272. symbols by length from short to long, and retaining the symbol order
  22273. for codes with equal lengths. Then the code starts with all zero bits
  22274. for the first code of the shortest length, and the codes are integer
  22275. increments for the same length, and zeros are appended as the length
  22276. increases. For the deflate format, these bits are stored backwards
  22277. from their more natural integer increment ordering, and so when the
  22278. decoding tables are built in the large loop below, the integer codes
  22279. are incremented backwards.
  22280. This routine assumes, but does not check, that all of the entries in
  22281. lens[] are in the range 0..MAXBITS. The caller must assure this.
  22282. 1..MAXBITS is interpreted as that code length. zero means that that
  22283. symbol does not occur in this code.
  22284. The codes are sorted by computing a count of codes for each length,
  22285. creating from that a table of starting indices for each length in the
  22286. sorted table, and then entering the symbols in order in the sorted
  22287. table. The sorted table is work[], with that space being provided by
  22288. the caller.
  22289. The length counts are used for other purposes as well, i.e. finding
  22290. the minimum and maximum length codes, determining if there are any
  22291. codes at all, checking for a valid set of lengths, and looking ahead
  22292. at length counts to determine sub-table sizes when building the
  22293. decoding tables.
  22294. */
  22295. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  22296. for (len = 0; len <= MAXBITS; len++) {
  22297. count[len] = 0;
  22298. }
  22299. for (sym = 0; sym < codes; sym++) {
  22300. count[lens[lens_index + sym]]++;
  22301. }
  22302. /* bound code lengths, force root to be within code lengths */
  22303. root = bits;
  22304. for (max = MAXBITS; max >= 1; max--) {
  22305. if (count[max] !== 0) { break; }
  22306. }
  22307. if (root > max) {
  22308. root = max;
  22309. }
  22310. if (max === 0) { /* no symbols to code at all */
  22311. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  22312. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  22313. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  22314. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  22315. //table.op[opts.table_index] = 64;
  22316. //table.bits[opts.table_index] = 1;
  22317. //table.val[opts.table_index++] = 0;
  22318. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  22319. opts.bits = 1;
  22320. return 0; /* no symbols, but wait for decoding to report error */
  22321. }
  22322. for (min = 1; min < max; min++) {
  22323. if (count[min] !== 0) { break; }
  22324. }
  22325. if (root < min) {
  22326. root = min;
  22327. }
  22328. /* check for an over-subscribed or incomplete set of lengths */
  22329. left = 1;
  22330. for (len = 1; len <= MAXBITS; len++) {
  22331. left <<= 1;
  22332. left -= count[len];
  22333. if (left < 0) {
  22334. return -1;
  22335. } /* over-subscribed */
  22336. }
  22337. if (left > 0 && (type === CODES || max !== 1)) {
  22338. return -1; /* incomplete set */
  22339. }
  22340. /* generate offsets into symbol table for each length for sorting */
  22341. offs[1] = 0;
  22342. for (len = 1; len < MAXBITS; len++) {
  22343. offs[len + 1] = offs[len] + count[len];
  22344. }
  22345. /* sort symbols by length, by symbol order within each length */
  22346. for (sym = 0; sym < codes; sym++) {
  22347. if (lens[lens_index + sym] !== 0) {
  22348. work[offs[lens[lens_index + sym]]++] = sym;
  22349. }
  22350. }
  22351. /*
  22352. Create and fill in decoding tables. In this loop, the table being
  22353. filled is at next and has curr index bits. The code being used is huff
  22354. with length len. That code is converted to an index by dropping drop
  22355. bits off of the bottom. For codes where len is less than drop + curr,
  22356. those top drop + curr - len bits are incremented through all values to
  22357. fill the table with replicated entries.
  22358. root is the number of index bits for the root table. When len exceeds
  22359. root, sub-tables are created pointed to by the root entry with an index
  22360. of the low root bits of huff. This is saved in low to check for when a
  22361. new sub-table should be started. drop is zero when the root table is
  22362. being filled, and drop is root when sub-tables are being filled.
  22363. When a new sub-table is needed, it is necessary to look ahead in the
  22364. code lengths to determine what size sub-table is needed. The length
  22365. counts are used for this, and so count[] is decremented as codes are
  22366. entered in the tables.
  22367. used keeps track of how many table entries have been allocated from the
  22368. provided *table space. It is checked for LENS and DIST tables against
  22369. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  22370. the initial root table size constants. See the comments in inftrees.h
  22371. for more information.
  22372. sym increments through all symbols, and the loop terminates when
  22373. all codes of length max, i.e. all codes, have been processed. This
  22374. routine permits incomplete codes, so another loop after this one fills
  22375. in the rest of the decoding tables with invalid code markers.
  22376. */
  22377. /* set up for code type */
  22378. // poor man optimization - use if-else instead of switch,
  22379. // to avoid deopts in old v8
  22380. if (type === CODES) {
  22381. base = extra = work; /* dummy value--not used */
  22382. end = 19;
  22383. } else if (type === LENS) {
  22384. base = lbase;
  22385. base_index -= 257;
  22386. extra = lext;
  22387. extra_index -= 257;
  22388. end = 256;
  22389. } else { /* DISTS */
  22390. base = dbase;
  22391. extra = dext;
  22392. end = -1;
  22393. }
  22394. /* initialize opts for loop */
  22395. huff = 0; /* starting code */
  22396. sym = 0; /* starting code symbol */
  22397. len = min; /* starting code length */
  22398. next = table_index; /* current table to fill in */
  22399. curr = root; /* current table index bits */
  22400. drop = 0; /* current bits to drop from code for index */
  22401. low = -1; /* trigger new sub-table when len > root */
  22402. used = 1 << root; /* use root table entries */
  22403. mask = used - 1; /* mask for comparing low */
  22404. /* check available table space */
  22405. if ((type === LENS && used > ENOUGH_LENS) ||
  22406. (type === DISTS && used > ENOUGH_DISTS)) {
  22407. return 1;
  22408. }
  22409. var i=0;
  22410. /* process all codes and make table entries */
  22411. for (;;) {
  22412. i++;
  22413. /* create table entry */
  22414. here_bits = len - drop;
  22415. if (work[sym] < end) {
  22416. here_op = 0;
  22417. here_val = work[sym];
  22418. }
  22419. else if (work[sym] > end) {
  22420. here_op = extra[extra_index + work[sym]];
  22421. here_val = base[base_index + work[sym]];
  22422. }
  22423. else {
  22424. here_op = 32 + 64; /* end of block */
  22425. here_val = 0;
  22426. }
  22427. /* replicate for those indices with low len bits equal to huff */
  22428. incr = 1 << (len - drop);
  22429. fill = 1 << curr;
  22430. min = fill; /* save offset to next table */
  22431. do {
  22432. fill -= incr;
  22433. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  22434. } while (fill !== 0);
  22435. /* backwards increment the len-bit code huff */
  22436. incr = 1 << (len - 1);
  22437. while (huff & incr) {
  22438. incr >>= 1;
  22439. }
  22440. if (incr !== 0) {
  22441. huff &= incr - 1;
  22442. huff += incr;
  22443. } else {
  22444. huff = 0;
  22445. }
  22446. /* go to next symbol, update count, len */
  22447. sym++;
  22448. if (--count[len] === 0) {
  22449. if (len === max) { break; }
  22450. len = lens[lens_index + work[sym]];
  22451. }
  22452. /* create new sub-table if needed */
  22453. if (len > root && (huff & mask) !== low) {
  22454. /* if first time, transition to sub-tables */
  22455. if (drop === 0) {
  22456. drop = root;
  22457. }
  22458. /* increment past last table */
  22459. next += min; /* here min is 1 << curr */
  22460. /* determine length of next table */
  22461. curr = len - drop;
  22462. left = 1 << curr;
  22463. while (curr + drop < max) {
  22464. left -= count[curr + drop];
  22465. if (left <= 0) { break; }
  22466. curr++;
  22467. left <<= 1;
  22468. }
  22469. /* check for enough space */
  22470. used += 1 << curr;
  22471. if ((type === LENS && used > ENOUGH_LENS) ||
  22472. (type === DISTS && used > ENOUGH_DISTS)) {
  22473. return 1;
  22474. }
  22475. /* point entry in root table to sub-table */
  22476. low = huff & mask;
  22477. /*table.op[low] = curr;
  22478. table.bits[low] = root;
  22479. table.val[low] = next - opts.table_index;*/
  22480. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  22481. }
  22482. }
  22483. /* fill in remaining table entry if code is incomplete (guaranteed to have
  22484. at most one remaining entry, since if the code is incomplete, the
  22485. maximum code length that was allowed to get this far is one bit) */
  22486. if (huff !== 0) {
  22487. //table.op[next + huff] = 64; /* invalid code marker */
  22488. //table.bits[next + huff] = len - drop;
  22489. //table.val[next + huff] = 0;
  22490. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  22491. }
  22492. /* set return parameters */
  22493. //opts.table_index += used;
  22494. opts.bits = root;
  22495. return 0;
  22496. };
  22497. },{"../utils/common":72}],82:[function(require,module,exports){
  22498. 'use strict';
  22499. module.exports = {
  22500. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  22501. '1': 'stream end', /* Z_STREAM_END 1 */
  22502. '0': '', /* Z_OK 0 */
  22503. '-1': 'file error', /* Z_ERRNO (-1) */
  22504. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  22505. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  22506. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  22507. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  22508. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  22509. };
  22510. },{}],83:[function(require,module,exports){
  22511. 'use strict';
  22512. var utils = require('../utils/common');
  22513. /* Public constants ==========================================================*/
  22514. /* ===========================================================================*/
  22515. //var Z_FILTERED = 1;
  22516. //var Z_HUFFMAN_ONLY = 2;
  22517. //var Z_RLE = 3;
  22518. var Z_FIXED = 4;
  22519. //var Z_DEFAULT_STRATEGY = 0;
  22520. /* Possible values of the data_type field (though see inflate()) */
  22521. var Z_BINARY = 0;
  22522. var Z_TEXT = 1;
  22523. //var Z_ASCII = 1; // = Z_TEXT
  22524. var Z_UNKNOWN = 2;
  22525. /*============================================================================*/
  22526. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  22527. // From zutil.h
  22528. var STORED_BLOCK = 0;
  22529. var STATIC_TREES = 1;
  22530. var DYN_TREES = 2;
  22531. /* The three kinds of block type */
  22532. var MIN_MATCH = 3;
  22533. var MAX_MATCH = 258;
  22534. /* The minimum and maximum match lengths */
  22535. // From deflate.h
  22536. /* ===========================================================================
  22537. * Internal compression state.
  22538. */
  22539. var LENGTH_CODES = 29;
  22540. /* number of length codes, not counting the special END_BLOCK code */
  22541. var LITERALS = 256;
  22542. /* number of literal bytes 0..255 */
  22543. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  22544. /* number of Literal or Length codes, including the END_BLOCK code */
  22545. var D_CODES = 30;
  22546. /* number of distance codes */
  22547. var BL_CODES = 19;
  22548. /* number of codes used to transfer the bit lengths */
  22549. var HEAP_SIZE = 2*L_CODES + 1;
  22550. /* maximum heap size */
  22551. var MAX_BITS = 15;
  22552. /* All codes must not exceed MAX_BITS bits */
  22553. var Buf_size = 16;
  22554. /* size of bit buffer in bi_buf */
  22555. /* ===========================================================================
  22556. * Constants
  22557. */
  22558. var MAX_BL_BITS = 7;
  22559. /* Bit length codes must not exceed MAX_BL_BITS bits */
  22560. var END_BLOCK = 256;
  22561. /* end of block literal code */
  22562. var REP_3_6 = 16;
  22563. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  22564. var REPZ_3_10 = 17;
  22565. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  22566. var REPZ_11_138 = 18;
  22567. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  22568. var extra_lbits = /* extra bits for each length code */
  22569. [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];
  22570. var extra_dbits = /* extra bits for each distance code */
  22571. [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];
  22572. var extra_blbits = /* extra bits for each bit length code */
  22573. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  22574. var bl_order =
  22575. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  22576. /* The lengths of the bit length codes are sent in order of decreasing
  22577. * probability, to avoid transmitting the lengths for unused bit length codes.
  22578. */
  22579. /* ===========================================================================
  22580. * Local data. These are initialized only once.
  22581. */
  22582. // We pre-fill arrays with 0 to avoid uninitialized gaps
  22583. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  22584. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  22585. var static_ltree = new Array((L_CODES+2) * 2);
  22586. zero(static_ltree);
  22587. /* The static literal tree. Since the bit lengths are imposed, there is no
  22588. * need for the L_CODES extra codes used during heap construction. However
  22589. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  22590. * below).
  22591. */
  22592. var static_dtree = new Array(D_CODES * 2);
  22593. zero(static_dtree);
  22594. /* The static distance tree. (Actually a trivial tree since all codes use
  22595. * 5 bits.)
  22596. */
  22597. var _dist_code = new Array(DIST_CODE_LEN);
  22598. zero(_dist_code);
  22599. /* Distance codes. The first 256 values correspond to the distances
  22600. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  22601. * the 15 bit distances.
  22602. */
  22603. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  22604. zero(_length_code);
  22605. /* length code for each normalized match length (0 == MIN_MATCH) */
  22606. var base_length = new Array(LENGTH_CODES);
  22607. zero(base_length);
  22608. /* First normalized length for each code (0 = MIN_MATCH) */
  22609. var base_dist = new Array(D_CODES);
  22610. zero(base_dist);
  22611. /* First normalized distance for each code (0 = distance of 1) */
  22612. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  22613. this.static_tree = static_tree; /* static tree or NULL */
  22614. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  22615. this.extra_base = extra_base; /* base index for extra_bits */
  22616. this.elems = elems; /* max number of elements in the tree */
  22617. this.max_length = max_length; /* max bit length for the codes */
  22618. // show if `static_tree` has data or dummy - needed for monomorphic objects
  22619. this.has_stree = static_tree && static_tree.length;
  22620. };
  22621. var static_l_desc;
  22622. var static_d_desc;
  22623. var static_bl_desc;
  22624. var TreeDesc = function(dyn_tree, stat_desc) {
  22625. this.dyn_tree = dyn_tree; /* the dynamic tree */
  22626. this.max_code = 0; /* largest code with non zero frequency */
  22627. this.stat_desc = stat_desc; /* the corresponding static tree */
  22628. };
  22629. function d_code(dist) {
  22630. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  22631. }
  22632. /* ===========================================================================
  22633. * Output a short LSB first on the stream.
  22634. * IN assertion: there is enough room in pendingBuf.
  22635. */
  22636. function put_short (s, w) {
  22637. // put_byte(s, (uch)((w) & 0xff));
  22638. // put_byte(s, (uch)((ush)(w) >> 8));
  22639. s.pending_buf[s.pending++] = (w) & 0xff;
  22640. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  22641. }
  22642. /* ===========================================================================
  22643. * Send a value on a given number of bits.
  22644. * IN assertion: length <= 16 and value fits in length bits.
  22645. */
  22646. function send_bits(s, value, length) {
  22647. if (s.bi_valid > (Buf_size - length)) {
  22648. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  22649. put_short(s, s.bi_buf);
  22650. s.bi_buf = value >> (Buf_size - s.bi_valid);
  22651. s.bi_valid += length - Buf_size;
  22652. } else {
  22653. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  22654. s.bi_valid += length;
  22655. }
  22656. }
  22657. function send_code(s, c, tree) {
  22658. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  22659. }
  22660. /* ===========================================================================
  22661. * Reverse the first len bits of a code, using straightforward code (a faster
  22662. * method would use a table)
  22663. * IN assertion: 1 <= len <= 15
  22664. */
  22665. function bi_reverse(code, len) {
  22666. var res = 0;
  22667. do {
  22668. res |= code & 1;
  22669. code >>>= 1;
  22670. res <<= 1;
  22671. } while (--len > 0);
  22672. return res >>> 1;
  22673. }
  22674. /* ===========================================================================
  22675. * Flush the bit buffer, keeping at most 7 bits in it.
  22676. */
  22677. function bi_flush(s) {
  22678. if (s.bi_valid === 16) {
  22679. put_short(s, s.bi_buf);
  22680. s.bi_buf = 0;
  22681. s.bi_valid = 0;
  22682. } else if (s.bi_valid >= 8) {
  22683. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  22684. s.bi_buf >>= 8;
  22685. s.bi_valid -= 8;
  22686. }
  22687. }
  22688. /* ===========================================================================
  22689. * Compute the optimal bit lengths for a tree and update the total bit length
  22690. * for the current block.
  22691. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  22692. * above are the tree nodes sorted by increasing frequency.
  22693. * OUT assertions: the field len is set to the optimal bit length, the
  22694. * array bl_count contains the frequencies for each bit length.
  22695. * The length opt_len is updated; static_len is also updated if stree is
  22696. * not null.
  22697. */
  22698. function gen_bitlen(s, desc)
  22699. // deflate_state *s;
  22700. // tree_desc *desc; /* the tree descriptor */
  22701. {
  22702. var tree = desc.dyn_tree;
  22703. var max_code = desc.max_code;
  22704. var stree = desc.stat_desc.static_tree;
  22705. var has_stree = desc.stat_desc.has_stree;
  22706. var extra = desc.stat_desc.extra_bits;
  22707. var base = desc.stat_desc.extra_base;
  22708. var max_length = desc.stat_desc.max_length;
  22709. var h; /* heap index */
  22710. var n, m; /* iterate over the tree elements */
  22711. var bits; /* bit length */
  22712. var xbits; /* extra bits */
  22713. var f; /* frequency */
  22714. var overflow = 0; /* number of elements with bit length too large */
  22715. for (bits = 0; bits <= MAX_BITS; bits++) {
  22716. s.bl_count[bits] = 0;
  22717. }
  22718. /* In a first pass, compute the optimal bit lengths (which may
  22719. * overflow in the case of the bit length tree).
  22720. */
  22721. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  22722. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  22723. n = s.heap[h];
  22724. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  22725. if (bits > max_length) {
  22726. bits = max_length;
  22727. overflow++;
  22728. }
  22729. tree[n*2 + 1]/*.Len*/ = bits;
  22730. /* We overwrite tree[n].Dad which is no longer needed */
  22731. if (n > max_code) { continue; } /* not a leaf node */
  22732. s.bl_count[bits]++;
  22733. xbits = 0;
  22734. if (n >= base) {
  22735. xbits = extra[n-base];
  22736. }
  22737. f = tree[n * 2]/*.Freq*/;
  22738. s.opt_len += f * (bits + xbits);
  22739. if (has_stree) {
  22740. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  22741. }
  22742. }
  22743. if (overflow === 0) { return; }
  22744. // Trace((stderr,"\nbit length overflow\n"));
  22745. /* This happens for example on obj2 and pic of the Calgary corpus */
  22746. /* Find the first bit length which could increase: */
  22747. do {
  22748. bits = max_length-1;
  22749. while (s.bl_count[bits] === 0) { bits--; }
  22750. s.bl_count[bits]--; /* move one leaf down the tree */
  22751. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  22752. s.bl_count[max_length]--;
  22753. /* The brother of the overflow item also moves one step up,
  22754. * but this does not affect bl_count[max_length]
  22755. */
  22756. overflow -= 2;
  22757. } while (overflow > 0);
  22758. /* Now recompute all bit lengths, scanning in increasing frequency.
  22759. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  22760. * lengths instead of fixing only the wrong ones. This idea is taken
  22761. * from 'ar' written by Haruhiko Okumura.)
  22762. */
  22763. for (bits = max_length; bits !== 0; bits--) {
  22764. n = s.bl_count[bits];
  22765. while (n !== 0) {
  22766. m = s.heap[--h];
  22767. if (m > max_code) { continue; }
  22768. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  22769. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  22770. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  22771. tree[m*2 + 1]/*.Len*/ = bits;
  22772. }
  22773. n--;
  22774. }
  22775. }
  22776. }
  22777. /* ===========================================================================
  22778. * Generate the codes for a given tree and bit counts (which need not be
  22779. * optimal).
  22780. * IN assertion: the array bl_count contains the bit length statistics for
  22781. * the given tree and the field len is set for all tree elements.
  22782. * OUT assertion: the field code is set for all tree elements of non
  22783. * zero code length.
  22784. */
  22785. function gen_codes(tree, max_code, bl_count)
  22786. // ct_data *tree; /* the tree to decorate */
  22787. // int max_code; /* largest code with non zero frequency */
  22788. // ushf *bl_count; /* number of codes at each bit length */
  22789. {
  22790. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  22791. var code = 0; /* running code value */
  22792. var bits; /* bit index */
  22793. var n; /* code index */
  22794. /* The distribution counts are first used to generate the code values
  22795. * without bit reversal.
  22796. */
  22797. for (bits = 1; bits <= MAX_BITS; bits++) {
  22798. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  22799. }
  22800. /* Check that the bit counts in bl_count are consistent. The last code
  22801. * must be all ones.
  22802. */
  22803. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  22804. // "inconsistent bit counts");
  22805. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  22806. for (n = 0; n <= max_code; n++) {
  22807. var len = tree[n*2 + 1]/*.Len*/;
  22808. if (len === 0) { continue; }
  22809. /* Now reverse the bits */
  22810. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  22811. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  22812. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  22813. }
  22814. }
  22815. /* ===========================================================================
  22816. * Initialize the various 'constant' tables.
  22817. */
  22818. function tr_static_init() {
  22819. var n; /* iterates over tree elements */
  22820. var bits; /* bit counter */
  22821. var length; /* length value */
  22822. var code; /* code value */
  22823. var dist; /* distance index */
  22824. var bl_count = new Array(MAX_BITS+1);
  22825. /* number of codes at each bit length for an optimal tree */
  22826. // do check in _tr_init()
  22827. //if (static_init_done) return;
  22828. /* For some embedded targets, global variables are not initialized: */
  22829. /*#ifdef NO_INIT_GLOBAL_POINTERS
  22830. static_l_desc.static_tree = static_ltree;
  22831. static_l_desc.extra_bits = extra_lbits;
  22832. static_d_desc.static_tree = static_dtree;
  22833. static_d_desc.extra_bits = extra_dbits;
  22834. static_bl_desc.extra_bits = extra_blbits;
  22835. #endif*/
  22836. /* Initialize the mapping length (0..255) -> length code (0..28) */
  22837. length = 0;
  22838. for (code = 0; code < LENGTH_CODES-1; code++) {
  22839. base_length[code] = length;
  22840. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  22841. _length_code[length++] = code;
  22842. }
  22843. }
  22844. //Assert (length == 256, "tr_static_init: length != 256");
  22845. /* Note that the length 255 (match length 258) can be represented
  22846. * in two different ways: code 284 + 5 bits or code 285, so we
  22847. * overwrite length_code[255] to use the best encoding:
  22848. */
  22849. _length_code[length-1] = code;
  22850. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  22851. dist = 0;
  22852. for (code = 0 ; code < 16; code++) {
  22853. base_dist[code] = dist;
  22854. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  22855. _dist_code[dist++] = code;
  22856. }
  22857. }
  22858. //Assert (dist == 256, "tr_static_init: dist != 256");
  22859. dist >>= 7; /* from now on, all distances are divided by 128 */
  22860. for (; code < D_CODES; code++) {
  22861. base_dist[code] = dist << 7;
  22862. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  22863. _dist_code[256 + dist++] = code;
  22864. }
  22865. }
  22866. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  22867. /* Construct the codes of the static literal tree */
  22868. for (bits = 0; bits <= MAX_BITS; bits++) {
  22869. bl_count[bits] = 0;
  22870. }
  22871. n = 0;
  22872. while (n <= 143) {
  22873. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22874. n++;
  22875. bl_count[8]++;
  22876. }
  22877. while (n <= 255) {
  22878. static_ltree[n*2 + 1]/*.Len*/ = 9;
  22879. n++;
  22880. bl_count[9]++;
  22881. }
  22882. while (n <= 279) {
  22883. static_ltree[n*2 + 1]/*.Len*/ = 7;
  22884. n++;
  22885. bl_count[7]++;
  22886. }
  22887. while (n <= 287) {
  22888. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22889. n++;
  22890. bl_count[8]++;
  22891. }
  22892. /* Codes 286 and 287 do not exist, but we must include them in the
  22893. * tree construction to get a canonical Huffman tree (longest code
  22894. * all ones)
  22895. */
  22896. gen_codes(static_ltree, L_CODES+1, bl_count);
  22897. /* The static distance tree is trivial: */
  22898. for (n = 0; n < D_CODES; n++) {
  22899. static_dtree[n*2 + 1]/*.Len*/ = 5;
  22900. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  22901. }
  22902. // Now data ready and we can init static trees
  22903. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  22904. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  22905. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  22906. //static_init_done = true;
  22907. }
  22908. /* ===========================================================================
  22909. * Initialize a new block.
  22910. */
  22911. function init_block(s) {
  22912. var n; /* iterates over tree elements */
  22913. /* Initialize the trees. */
  22914. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  22915. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  22916. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  22917. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  22918. s.opt_len = s.static_len = 0;
  22919. s.last_lit = s.matches = 0;
  22920. }
  22921. /* ===========================================================================
  22922. * Flush the bit buffer and align the output on a byte boundary
  22923. */
  22924. function bi_windup(s)
  22925. {
  22926. if (s.bi_valid > 8) {
  22927. put_short(s, s.bi_buf);
  22928. } else if (s.bi_valid > 0) {
  22929. //put_byte(s, (Byte)s->bi_buf);
  22930. s.pending_buf[s.pending++] = s.bi_buf;
  22931. }
  22932. s.bi_buf = 0;
  22933. s.bi_valid = 0;
  22934. }
  22935. /* ===========================================================================
  22936. * Copy a stored block, storing first the length and its
  22937. * one's complement if requested.
  22938. */
  22939. function copy_block(s, buf, len, header)
  22940. //DeflateState *s;
  22941. //charf *buf; /* the input data */
  22942. //unsigned len; /* its length */
  22943. //int header; /* true if block header must be written */
  22944. {
  22945. bi_windup(s); /* align on byte boundary */
  22946. if (header) {
  22947. put_short(s, len);
  22948. put_short(s, ~len);
  22949. }
  22950. // while (len--) {
  22951. // put_byte(s, *buf++);
  22952. // }
  22953. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  22954. s.pending += len;
  22955. }
  22956. /* ===========================================================================
  22957. * Compares to subtrees, using the tree depth as tie breaker when
  22958. * the subtrees have equal frequency. This minimizes the worst case length.
  22959. */
  22960. function smaller(tree, n, m, depth) {
  22961. var _n2 = n*2;
  22962. var _m2 = m*2;
  22963. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  22964. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  22965. }
  22966. /* ===========================================================================
  22967. * Restore the heap property by moving down the tree starting at node k,
  22968. * exchanging a node with the smallest of its two sons if necessary, stopping
  22969. * when the heap property is re-established (each father smaller than its
  22970. * two sons).
  22971. */
  22972. function pqdownheap(s, tree, k)
  22973. // deflate_state *s;
  22974. // ct_data *tree; /* the tree to restore */
  22975. // int k; /* node to move down */
  22976. {
  22977. var v = s.heap[k];
  22978. var j = k << 1; /* left son of k */
  22979. while (j <= s.heap_len) {
  22980. /* Set j to the smallest of the two sons: */
  22981. if (j < s.heap_len &&
  22982. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  22983. j++;
  22984. }
  22985. /* Exit if v is smaller than both sons */
  22986. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  22987. /* Exchange v with the smallest son */
  22988. s.heap[k] = s.heap[j];
  22989. k = j;
  22990. /* And continue down the tree, setting j to the left son of k */
  22991. j <<= 1;
  22992. }
  22993. s.heap[k] = v;
  22994. }
  22995. // inlined manually
  22996. // var SMALLEST = 1;
  22997. /* ===========================================================================
  22998. * Send the block data compressed using the given Huffman trees
  22999. */
  23000. function compress_block(s, ltree, dtree)
  23001. // deflate_state *s;
  23002. // const ct_data *ltree; /* literal tree */
  23003. // const ct_data *dtree; /* distance tree */
  23004. {
  23005. var dist; /* distance of matched string */
  23006. var lc; /* match length or unmatched char (if dist == 0) */
  23007. var lx = 0; /* running index in l_buf */
  23008. var code; /* the code to send */
  23009. var extra; /* number of extra bits to send */
  23010. if (s.last_lit !== 0) {
  23011. do {
  23012. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  23013. lc = s.pending_buf[s.l_buf + lx];
  23014. lx++;
  23015. if (dist === 0) {
  23016. send_code(s, lc, ltree); /* send a literal byte */
  23017. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  23018. } else {
  23019. /* Here, lc is the match length - MIN_MATCH */
  23020. code = _length_code[lc];
  23021. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  23022. extra = extra_lbits[code];
  23023. if (extra !== 0) {
  23024. lc -= base_length[code];
  23025. send_bits(s, lc, extra); /* send the extra length bits */
  23026. }
  23027. dist--; /* dist is now the match distance - 1 */
  23028. code = d_code(dist);
  23029. //Assert (code < D_CODES, "bad d_code");
  23030. send_code(s, code, dtree); /* send the distance code */
  23031. extra = extra_dbits[code];
  23032. if (extra !== 0) {
  23033. dist -= base_dist[code];
  23034. send_bits(s, dist, extra); /* send the extra distance bits */
  23035. }
  23036. } /* literal or match pair ? */
  23037. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  23038. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  23039. // "pendingBuf overflow");
  23040. } while (lx < s.last_lit);
  23041. }
  23042. send_code(s, END_BLOCK, ltree);
  23043. }
  23044. /* ===========================================================================
  23045. * Construct one Huffman tree and assigns the code bit strings and lengths.
  23046. * Update the total bit length for the current block.
  23047. * IN assertion: the field freq is set for all tree elements.
  23048. * OUT assertions: the fields len and code are set to the optimal bit length
  23049. * and corresponding code. The length opt_len is updated; static_len is
  23050. * also updated if stree is not null. The field max_code is set.
  23051. */
  23052. function build_tree(s, desc)
  23053. // deflate_state *s;
  23054. // tree_desc *desc; /* the tree descriptor */
  23055. {
  23056. var tree = desc.dyn_tree;
  23057. var stree = desc.stat_desc.static_tree;
  23058. var has_stree = desc.stat_desc.has_stree;
  23059. var elems = desc.stat_desc.elems;
  23060. var n, m; /* iterate over heap elements */
  23061. var max_code = -1; /* largest code with non zero frequency */
  23062. var node; /* new node being created */
  23063. /* Construct the initial heap, with least frequent element in
  23064. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  23065. * heap[0] is not used.
  23066. */
  23067. s.heap_len = 0;
  23068. s.heap_max = HEAP_SIZE;
  23069. for (n = 0; n < elems; n++) {
  23070. if (tree[n * 2]/*.Freq*/ !== 0) {
  23071. s.heap[++s.heap_len] = max_code = n;
  23072. s.depth[n] = 0;
  23073. } else {
  23074. tree[n*2 + 1]/*.Len*/ = 0;
  23075. }
  23076. }
  23077. /* The pkzip format requires that at least one distance code exists,
  23078. * and that at least one bit should be sent even if there is only one
  23079. * possible code. So to avoid special checks later on we force at least
  23080. * two codes of non zero frequency.
  23081. */
  23082. while (s.heap_len < 2) {
  23083. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  23084. tree[node * 2]/*.Freq*/ = 1;
  23085. s.depth[node] = 0;
  23086. s.opt_len--;
  23087. if (has_stree) {
  23088. s.static_len -= stree[node*2 + 1]/*.Len*/;
  23089. }
  23090. /* node is 0 or 1 so it does not have extra bits */
  23091. }
  23092. desc.max_code = max_code;
  23093. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  23094. * establish sub-heaps of increasing lengths:
  23095. */
  23096. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  23097. /* Construct the Huffman tree by repeatedly combining the least two
  23098. * frequent nodes.
  23099. */
  23100. node = elems; /* next internal node of the tree */
  23101. do {
  23102. //pqremove(s, tree, n); /* n = node of least frequency */
  23103. /*** pqremove ***/
  23104. n = s.heap[1/*SMALLEST*/];
  23105. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  23106. pqdownheap(s, tree, 1/*SMALLEST*/);
  23107. /***/
  23108. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  23109. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  23110. s.heap[--s.heap_max] = m;
  23111. /* Create a new node father of n and m */
  23112. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  23113. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  23114. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  23115. /* and insert the new node in the heap */
  23116. s.heap[1/*SMALLEST*/] = node++;
  23117. pqdownheap(s, tree, 1/*SMALLEST*/);
  23118. } while (s.heap_len >= 2);
  23119. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  23120. /* At this point, the fields freq and dad are set. We can now
  23121. * generate the bit lengths.
  23122. */
  23123. gen_bitlen(s, desc);
  23124. /* The field len is now set, we can generate the bit codes */
  23125. gen_codes(tree, max_code, s.bl_count);
  23126. }
  23127. /* ===========================================================================
  23128. * Scan a literal or distance tree to determine the frequencies of the codes
  23129. * in the bit length tree.
  23130. */
  23131. function scan_tree(s, tree, max_code)
  23132. // deflate_state *s;
  23133. // ct_data *tree; /* the tree to be scanned */
  23134. // int max_code; /* and its largest code of non zero frequency */
  23135. {
  23136. var n; /* iterates over all tree elements */
  23137. var prevlen = -1; /* last emitted length */
  23138. var curlen; /* length of current code */
  23139. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23140. var count = 0; /* repeat count of the current code */
  23141. var max_count = 7; /* max repeat count */
  23142. var min_count = 4; /* min repeat count */
  23143. if (nextlen === 0) {
  23144. max_count = 138;
  23145. min_count = 3;
  23146. }
  23147. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  23148. for (n = 0; n <= max_code; n++) {
  23149. curlen = nextlen;
  23150. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23151. if (++count < max_count && curlen === nextlen) {
  23152. continue;
  23153. } else if (count < min_count) {
  23154. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  23155. } else if (curlen !== 0) {
  23156. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  23157. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  23158. } else if (count <= 10) {
  23159. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  23160. } else {
  23161. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  23162. }
  23163. count = 0;
  23164. prevlen = curlen;
  23165. if (nextlen === 0) {
  23166. max_count = 138;
  23167. min_count = 3;
  23168. } else if (curlen === nextlen) {
  23169. max_count = 6;
  23170. min_count = 3;
  23171. } else {
  23172. max_count = 7;
  23173. min_count = 4;
  23174. }
  23175. }
  23176. }
  23177. /* ===========================================================================
  23178. * Send a literal or distance tree in compressed form, using the codes in
  23179. * bl_tree.
  23180. */
  23181. function send_tree(s, tree, max_code)
  23182. // deflate_state *s;
  23183. // ct_data *tree; /* the tree to be scanned */
  23184. // int max_code; /* and its largest code of non zero frequency */
  23185. {
  23186. var n; /* iterates over all tree elements */
  23187. var prevlen = -1; /* last emitted length */
  23188. var curlen; /* length of current code */
  23189. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23190. var count = 0; /* repeat count of the current code */
  23191. var max_count = 7; /* max repeat count */
  23192. var min_count = 4; /* min repeat count */
  23193. /* tree[max_code+1].Len = -1; */ /* guard already set */
  23194. if (nextlen === 0) {
  23195. max_count = 138;
  23196. min_count = 3;
  23197. }
  23198. for (n = 0; n <= max_code; n++) {
  23199. curlen = nextlen;
  23200. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23201. if (++count < max_count && curlen === nextlen) {
  23202. continue;
  23203. } else if (count < min_count) {
  23204. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  23205. } else if (curlen !== 0) {
  23206. if (curlen !== prevlen) {
  23207. send_code(s, curlen, s.bl_tree);
  23208. count--;
  23209. }
  23210. //Assert(count >= 3 && count <= 6, " 3_6?");
  23211. send_code(s, REP_3_6, s.bl_tree);
  23212. send_bits(s, count-3, 2);
  23213. } else if (count <= 10) {
  23214. send_code(s, REPZ_3_10, s.bl_tree);
  23215. send_bits(s, count-3, 3);
  23216. } else {
  23217. send_code(s, REPZ_11_138, s.bl_tree);
  23218. send_bits(s, count-11, 7);
  23219. }
  23220. count = 0;
  23221. prevlen = curlen;
  23222. if (nextlen === 0) {
  23223. max_count = 138;
  23224. min_count = 3;
  23225. } else if (curlen === nextlen) {
  23226. max_count = 6;
  23227. min_count = 3;
  23228. } else {
  23229. max_count = 7;
  23230. min_count = 4;
  23231. }
  23232. }
  23233. }
  23234. /* ===========================================================================
  23235. * Construct the Huffman tree for the bit lengths and return the index in
  23236. * bl_order of the last bit length code to send.
  23237. */
  23238. function build_bl_tree(s) {
  23239. var max_blindex; /* index of last bit length code of non zero freq */
  23240. /* Determine the bit length frequencies for literal and distance trees */
  23241. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  23242. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  23243. /* Build the bit length tree: */
  23244. build_tree(s, s.bl_desc);
  23245. /* opt_len now includes the length of the tree representations, except
  23246. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  23247. */
  23248. /* Determine the number of bit length codes to send. The pkzip format
  23249. * requires that at least 4 bit length codes be sent. (appnote.txt says
  23250. * 3 but the actual value used is 4.)
  23251. */
  23252. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  23253. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  23254. break;
  23255. }
  23256. }
  23257. /* Update opt_len to include the bit length tree and counts */
  23258. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  23259. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  23260. // s->opt_len, s->static_len));
  23261. return max_blindex;
  23262. }
  23263. /* ===========================================================================
  23264. * Send the header for a block using dynamic Huffman trees: the counts, the
  23265. * lengths of the bit length codes, the literal tree and the distance tree.
  23266. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  23267. */
  23268. function send_all_trees(s, lcodes, dcodes, blcodes)
  23269. // deflate_state *s;
  23270. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  23271. {
  23272. var rank; /* index in bl_order */
  23273. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  23274. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  23275. // "too many codes");
  23276. //Tracev((stderr, "\nbl counts: "));
  23277. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  23278. send_bits(s, dcodes-1, 5);
  23279. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  23280. for (rank = 0; rank < blcodes; rank++) {
  23281. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  23282. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  23283. }
  23284. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  23285. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  23286. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  23287. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  23288. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  23289. }
  23290. /* ===========================================================================
  23291. * Check if the data type is TEXT or BINARY, using the following algorithm:
  23292. * - TEXT if the two conditions below are satisfied:
  23293. * a) There are no non-portable control characters belonging to the
  23294. * "black list" (0..6, 14..25, 28..31).
  23295. * b) There is at least one printable character belonging to the
  23296. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  23297. * - BINARY otherwise.
  23298. * - The following partially-portable control characters form a
  23299. * "gray list" that is ignored in this detection algorithm:
  23300. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  23301. * IN assertion: the fields Freq of dyn_ltree are set.
  23302. */
  23303. function detect_data_type(s) {
  23304. /* black_mask is the bit mask of black-listed bytes
  23305. * set bits 0..6, 14..25, and 28..31
  23306. * 0xf3ffc07f = binary 11110011111111111100000001111111
  23307. */
  23308. var black_mask = 0xf3ffc07f;
  23309. var n;
  23310. /* Check for non-textual ("black-listed") bytes. */
  23311. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  23312. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  23313. return Z_BINARY;
  23314. }
  23315. }
  23316. /* Check for textual ("white-listed") bytes. */
  23317. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  23318. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  23319. return Z_TEXT;
  23320. }
  23321. for (n = 32; n < LITERALS; n++) {
  23322. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  23323. return Z_TEXT;
  23324. }
  23325. }
  23326. /* There are no "black-listed" or "white-listed" bytes:
  23327. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  23328. */
  23329. return Z_BINARY;
  23330. }
  23331. var static_init_done = false;
  23332. /* ===========================================================================
  23333. * Initialize the tree data structures for a new zlib stream.
  23334. */
  23335. function _tr_init(s)
  23336. {
  23337. if (!static_init_done) {
  23338. tr_static_init();
  23339. static_init_done = true;
  23340. }
  23341. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  23342. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  23343. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  23344. s.bi_buf = 0;
  23345. s.bi_valid = 0;
  23346. /* Initialize the first block of the first file: */
  23347. init_block(s);
  23348. }
  23349. /* ===========================================================================
  23350. * Send a stored block
  23351. */
  23352. function _tr_stored_block(s, buf, stored_len, last)
  23353. //DeflateState *s;
  23354. //charf *buf; /* input block */
  23355. //ulg stored_len; /* length of input block */
  23356. //int last; /* one if this is the last block for a file */
  23357. {
  23358. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  23359. copy_block(s, buf, stored_len, true); /* with header */
  23360. }
  23361. /* ===========================================================================
  23362. * Send one empty static block to give enough lookahead for inflate.
  23363. * This takes 10 bits, of which 7 may remain in the bit buffer.
  23364. */
  23365. function _tr_align(s) {
  23366. send_bits(s, STATIC_TREES<<1, 3);
  23367. send_code(s, END_BLOCK, static_ltree);
  23368. bi_flush(s);
  23369. }
  23370. /* ===========================================================================
  23371. * Determine the best encoding for the current block: dynamic trees, static
  23372. * trees or store, and output the encoded block to the zip file.
  23373. */
  23374. function _tr_flush_block(s, buf, stored_len, last)
  23375. //DeflateState *s;
  23376. //charf *buf; /* input block, or NULL if too old */
  23377. //ulg stored_len; /* length of input block */
  23378. //int last; /* one if this is the last block for a file */
  23379. {
  23380. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  23381. var max_blindex = 0; /* index of last bit length code of non zero freq */
  23382. /* Build the Huffman trees unless a stored block is forced */
  23383. if (s.level > 0) {
  23384. /* Check if the file is binary or text */
  23385. if (s.strm.data_type === Z_UNKNOWN) {
  23386. s.strm.data_type = detect_data_type(s);
  23387. }
  23388. /* Construct the literal and distance trees */
  23389. build_tree(s, s.l_desc);
  23390. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  23391. // s->static_len));
  23392. build_tree(s, s.d_desc);
  23393. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  23394. // s->static_len));
  23395. /* At this point, opt_len and static_len are the total bit lengths of
  23396. * the compressed block data, excluding the tree representations.
  23397. */
  23398. /* Build the bit length tree for the above two trees, and get the index
  23399. * in bl_order of the last bit length code to send.
  23400. */
  23401. max_blindex = build_bl_tree(s);
  23402. /* Determine the best encoding. Compute the block lengths in bytes. */
  23403. opt_lenb = (s.opt_len+3+7) >>> 3;
  23404. static_lenb = (s.static_len+3+7) >>> 3;
  23405. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  23406. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  23407. // s->last_lit));
  23408. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  23409. } else {
  23410. // Assert(buf != (char*)0, "lost buf");
  23411. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  23412. }
  23413. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  23414. /* 4: two words for the lengths */
  23415. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  23416. * Otherwise we can't have processed more than WSIZE input bytes since
  23417. * the last block flush, because compression would have been
  23418. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  23419. * transform a block into a stored block.
  23420. */
  23421. _tr_stored_block(s, buf, stored_len, last);
  23422. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  23423. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  23424. compress_block(s, static_ltree, static_dtree);
  23425. } else {
  23426. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  23427. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  23428. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  23429. }
  23430. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  23431. /* The above check is made mod 2^32, for files larger than 512 MB
  23432. * and uLong implemented on 32 bits.
  23433. */
  23434. init_block(s);
  23435. if (last) {
  23436. bi_windup(s);
  23437. }
  23438. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  23439. // s->compressed_len-7*last));
  23440. }
  23441. /* ===========================================================================
  23442. * Save the match info and tally the frequency counts. Return true if
  23443. * the current block must be flushed.
  23444. */
  23445. function _tr_tally(s, dist, lc)
  23446. // deflate_state *s;
  23447. // unsigned dist; /* distance of matched string */
  23448. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  23449. {
  23450. //var out_length, in_length, dcode;
  23451. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  23452. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  23453. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  23454. s.last_lit++;
  23455. if (dist === 0) {
  23456. /* lc is the unmatched char */
  23457. s.dyn_ltree[lc*2]/*.Freq*/++;
  23458. } else {
  23459. s.matches++;
  23460. /* Here, lc is the match length - MIN_MATCH */
  23461. dist--; /* dist = match distance - 1 */
  23462. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  23463. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  23464. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  23465. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  23466. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  23467. }
  23468. // (!) This block is disabled in zlib defailts,
  23469. // don't enable it for binary compatibility
  23470. //#ifdef TRUNCATE_BLOCK
  23471. // /* Try to guess if it is profitable to stop the current block here */
  23472. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  23473. // /* Compute an upper bound for the compressed length */
  23474. // out_length = s.last_lit*8;
  23475. // in_length = s.strstart - s.block_start;
  23476. //
  23477. // for (dcode = 0; dcode < D_CODES; dcode++) {
  23478. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  23479. // }
  23480. // out_length >>>= 3;
  23481. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  23482. // // s->last_lit, in_length, out_length,
  23483. // // 100L - out_length*100L/in_length));
  23484. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  23485. // return true;
  23486. // }
  23487. // }
  23488. //#endif
  23489. return (s.last_lit === s.lit_bufsize-1);
  23490. /* We avoid equality with lit_bufsize because of wraparound at 64K
  23491. * on 16 bit machines and because stored blocks are restricted to
  23492. * 64K-1 bytes.
  23493. */
  23494. }
  23495. exports._tr_init = _tr_init;
  23496. exports._tr_stored_block = _tr_stored_block;
  23497. exports._tr_flush_block = _tr_flush_block;
  23498. exports._tr_tally = _tr_tally;
  23499. exports._tr_align = _tr_align;
  23500. },{"../utils/common":72}],84:[function(require,module,exports){
  23501. 'use strict';
  23502. function ZStream() {
  23503. /* next input byte */
  23504. this.input = null; // JS specific, because we have no pointers
  23505. this.next_in = 0;
  23506. /* number of bytes available at input */
  23507. this.avail_in = 0;
  23508. /* total number of input bytes read so far */
  23509. this.total_in = 0;
  23510. /* next output byte should be put there */
  23511. this.output = null; // JS specific, because we have no pointers
  23512. this.next_out = 0;
  23513. /* remaining free space at output */
  23514. this.avail_out = 0;
  23515. /* total number of bytes output so far */
  23516. this.total_out = 0;
  23517. /* last error message, NULL if no error */
  23518. this.msg = ''/*Z_NULL*/;
  23519. /* not visible by applications */
  23520. this.state = null;
  23521. /* best guess about the data type: binary or text */
  23522. this.data_type = 2/*Z_UNKNOWN*/;
  23523. /* adler32 value of the uncompressed data */
  23524. this.adler = 0;
  23525. }
  23526. module.exports = ZStream;
  23527. },{}],85:[function(require,module,exports){
  23528. module.exports = require('./lib/retry');
  23529. },{"./lib/retry":86}],86:[function(require,module,exports){
  23530. var RetryOperation = require('./retry_operation');
  23531. exports.operation = function(options) {
  23532. var timeouts = exports.timeouts(options);
  23533. return new RetryOperation(timeouts);
  23534. };
  23535. exports.timeouts = function(options) {
  23536. if (options instanceof Array) {
  23537. return [].concat(options);
  23538. }
  23539. var opts = {
  23540. retries: 10,
  23541. factor: 2,
  23542. minTimeout: 1 * 1000,
  23543. maxTimeout: Infinity,
  23544. randomize: false
  23545. };
  23546. for (var key in options) {
  23547. opts[key] = options[key];
  23548. }
  23549. if (opts.minTimeout > opts.maxTimeout) {
  23550. throw new Error('minTimeout is greater than maxTimeout');
  23551. }
  23552. var timeouts = [];
  23553. for (var i = 0; i < opts.retries; i++) {
  23554. timeouts.push(this._createTimeout(i, opts));
  23555. }
  23556. // sort the array numerically ascending
  23557. timeouts.sort(function(a,b) {
  23558. return a - b;
  23559. });
  23560. return timeouts;
  23561. };
  23562. exports._createTimeout = function(attempt, opts) {
  23563. var random = (opts.randomize)
  23564. ? (Math.random() + 1)
  23565. : 1;
  23566. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  23567. timeout = Math.min(timeout, opts.maxTimeout);
  23568. return timeout;
  23569. };
  23570. },{"./retry_operation":87}],87:[function(require,module,exports){
  23571. function RetryOperation(timeouts) {
  23572. this._timeouts = timeouts;
  23573. this._fn = null;
  23574. this._errors = [];
  23575. this._attempts = 1;
  23576. this._operationTimeout = null;
  23577. this._operationTimeoutCb = null;
  23578. this._timeout = null;
  23579. }
  23580. module.exports = RetryOperation;
  23581. RetryOperation.prototype.retry = function(err) {
  23582. if (this._timeout) {
  23583. clearTimeout(this._timeout);
  23584. }
  23585. if (!err) {
  23586. return false;
  23587. }
  23588. this._errors.push(err);
  23589. var timeout = this._timeouts.shift();
  23590. if (timeout === undefined) {
  23591. return false;
  23592. }
  23593. this._attempts++;
  23594. var self = this;
  23595. setTimeout(function() {
  23596. self._fn(self._attempts);
  23597. if (self._operationTimeoutCb) {
  23598. self._timeout = setTimeout(function() {
  23599. self._operationTimeoutCb(self._attempts);
  23600. }, self._operationTimeout);
  23601. }
  23602. }, timeout);
  23603. return true;
  23604. };
  23605. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  23606. this._fn = fn;
  23607. if (timeoutOps) {
  23608. if (timeoutOps.timeout) {
  23609. this._operationTimeout = timeoutOps.timeout;
  23610. }
  23611. if (timeoutOps.cb) {
  23612. this._operationTimeoutCb = timeoutOps.cb;
  23613. }
  23614. }
  23615. this._fn(this._attempts);
  23616. var self = this;
  23617. if (this._operationTimeoutCb) {
  23618. this._timeout = setTimeout(function() {
  23619. self._operationTimeoutCb();
  23620. }, self._operationTimeout);
  23621. }
  23622. };
  23623. RetryOperation.prototype.try = function(fn) {
  23624. console.log('Using RetryOperation.try() is deprecated');
  23625. this.attempt(fn);
  23626. };
  23627. RetryOperation.prototype.start = function(fn) {
  23628. console.log('Using RetryOperation.start() is deprecated');
  23629. this.attempt(fn);
  23630. };
  23631. RetryOperation.prototype.start = RetryOperation.prototype.try;
  23632. RetryOperation.prototype.errors = function() {
  23633. return this._errors;
  23634. };
  23635. RetryOperation.prototype.attempts = function() {
  23636. return this._attempts;
  23637. };
  23638. RetryOperation.prototype.mainError = function() {
  23639. if (this._errors.length === 0) {
  23640. return null;
  23641. }
  23642. var counts = {};
  23643. var mainError = null;
  23644. var mainErrorCount = 0;
  23645. for (var i = 0; i < this._errors.length; i++) {
  23646. var error = this._errors[i];
  23647. var message = error.message;
  23648. var count = (counts[message] || 0) + 1;
  23649. counts[message] = count;
  23650. if (count >= mainErrorCount) {
  23651. mainError = error;
  23652. mainErrorCount = count;
  23653. }
  23654. }
  23655. return mainError;
  23656. };
  23657. },{}],88:[function(require,module,exports){
  23658. module.exports = function arrayEquals(array) {
  23659. // if the other array is a falsy value, return
  23660. if (!array)
  23661. return false;
  23662. // compare lengths - can save a lot of time
  23663. if (this.length != array.length)
  23664. return false;
  23665. for (var i = 0, l = this.length; i < l; i++) {
  23666. // Check if we have nested arrays
  23667. if (this[i] instanceof Array && array[i] instanceof Array) {
  23668. // recurse into the nested arrays
  23669. if (!arrayEquals.apply(this[i], [array[i]]))
  23670. return false;
  23671. } else if (this[i] != array[i]) {
  23672. // Warning - two different object instances will never be equal:
  23673. // {x:20} != {x:20}
  23674. return false;
  23675. }
  23676. }
  23677. return true;
  23678. }
  23679. },{}],89:[function(require,module,exports){
  23680. exports.Interop = require('./interop');
  23681. },{"./interop":90}],90:[function(require,module,exports){
  23682. "use strict";
  23683. var transform = require('./transform');
  23684. var arrayEquals = require('./array-equals');
  23685. function Interop() {
  23686. /**
  23687. * This map holds the most recent Unified Plan offer/answer SDP that was
  23688. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  23689. * the SDP string as values.
  23690. *
  23691. * @type {{}}
  23692. */
  23693. this.cache = {};
  23694. }
  23695. module.exports = Interop;
  23696. /**
  23697. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  23698. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  23699. * application.
  23700. *
  23701. * @param desc
  23702. * @returns {*}
  23703. */
  23704. Interop.prototype.toPlanB = function(desc) {
  23705. //#region Preliminary input validation.
  23706. if (typeof desc !== 'object' || desc === null ||
  23707. typeof desc.sdp !== 'string') {
  23708. console.warn('An empty description was passed as an argument.');
  23709. return desc;
  23710. }
  23711. // Objectify the SDP for easier manipulation.
  23712. var session = transform.parse(desc.sdp);
  23713. // If the SDP contains no media, there's nothing to transform.
  23714. if (typeof session.media === 'undefined' ||
  23715. !Array.isArray(session.media) || session.media.length === 0) {
  23716. console.warn('The description has no media.');
  23717. return desc;
  23718. }
  23719. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  23720. // SDP has a video, an audio and a data "channel" at most.
  23721. if (session.media.length <= 3 && session.media.every(function(m) {
  23722. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  23723. })) {
  23724. console.warn('This description does not look like Unified Plan.');
  23725. return desc;
  23726. }
  23727. //#endregion
  23728. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  23729. // -> Unified Plan transformation.
  23730. this.cache[desc.type] = desc.sdp;
  23731. //#region Convert from Unified Plan to Plan B.
  23732. // We rebuild the session.media array.
  23733. var media = session.media;
  23734. session.media = [];
  23735. // Associative array that maps channel types to channel objects for fast
  23736. // access to channel objects by their type, e.g. type2bl['audio']->channel
  23737. // obj.
  23738. var type2bl = {};
  23739. // Used to build the group:BUNDLE value after the channels construction
  23740. // loop.
  23741. var types = [];
  23742. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  23743. media.forEach(function(unifiedLine) {
  23744. // rtcp-mux is required in the Plan B SDP.
  23745. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  23746. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  23747. unifiedLine.direction !== 'inactive') {
  23748. throw new Error('Cannot convert to Plan B because m-lines ' +
  23749. 'without the rtcp-mux attribute were found.');
  23750. }
  23751. if (unifiedLine.type === 'application') {
  23752. session.media.push(unifiedLine);
  23753. types.push(unifiedLine.mid);
  23754. return;
  23755. }
  23756. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  23757. // as the channel basis.
  23758. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  23759. type2bl[unifiedLine.type] = unifiedLine;
  23760. }
  23761. // Add sources to the channel and handle a=msid.
  23762. if (typeof unifiedLine.sources === 'object') {
  23763. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  23764. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  23765. type2bl[unifiedLine.type].sources = {};
  23766. // Assign the sources to the channel.
  23767. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  23768. if (typeof unifiedLine.msid !== 'undefined') {
  23769. // In Plan B the msid is an SSRC attribute. Also, we don't
  23770. // care about the obsolete label and mslabel attributes.
  23771. //
  23772. // Note that it is not guaranteed that the unifiedLine will have
  23773. // an msid. recvonly channels in particular don't have one.
  23774. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  23775. }
  23776. // NOTE ssrcs in ssrc groups will share msids, as
  23777. // draft-uberti-rtcweb-plan-00 mandates.
  23778. });
  23779. }
  23780. // Add ssrc groups to the channel.
  23781. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  23782. Array.isArray(unifiedLine.ssrcGroups)) {
  23783. // Create the ssrcGroups array, if it's not defined.
  23784. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  23785. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  23786. type2bl[unifiedLine.type].ssrcGroups = [];
  23787. }
  23788. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  23789. }
  23790. if (type2bl[unifiedLine.type] === unifiedLine) {
  23791. // Copy ICE related stuff from the principal media line.
  23792. unifiedLine.candidates = media[0].candidates;
  23793. unifiedLine.iceUfrag = media[0].iceUfrag;
  23794. unifiedLine.icePwd = media[0].icePwd;
  23795. unifiedLine.fingerprint = media[0].fingerprint;
  23796. // Plan B mids are in ['audio', 'video', 'data']
  23797. unifiedLine.mid = unifiedLine.type;
  23798. // Plan B doesn't support/need the bundle-only attribute.
  23799. delete unifiedLine.bundleOnly;
  23800. // In Plan B the msid is an SSRC attribute.
  23801. delete unifiedLine.msid;
  23802. // Used to build the group:BUNDLE value after this loop.
  23803. types.push(unifiedLine.type);
  23804. // Add the channel to the new media array.
  23805. session.media.push(unifiedLine);
  23806. }
  23807. });
  23808. // We regenerate the BUNDLE group with the new mids.
  23809. session.groups.some(function(group) {
  23810. if (group.type === 'BUNDLE') {
  23811. group.mids = types.join(' ');
  23812. return true;
  23813. }
  23814. });
  23815. // msid semantic
  23816. session.msidSemantic = {
  23817. semantic: 'WMS',
  23818. token: '*'
  23819. };
  23820. var resStr = transform.write(session);
  23821. return new RTCSessionDescription({
  23822. type: desc.type,
  23823. sdp: resStr
  23824. });
  23825. //#endregion
  23826. };
  23827. /**
  23828. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  23829. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  23830. * to FF.
  23831. *
  23832. * @param desc
  23833. * @returns {*}
  23834. */
  23835. Interop.prototype.toUnifiedPlan = function(desc) {
  23836. //#region Preliminary input validation.
  23837. if (typeof desc !== 'object' || desc === null ||
  23838. typeof desc.sdp !== 'string') {
  23839. console.warn('An empty description was passed as an argument.');
  23840. return desc;
  23841. }
  23842. var session = transform.parse(desc.sdp);
  23843. // If the SDP contains no media, there's nothing to transform.
  23844. if (typeof session.media === 'undefined' ||
  23845. !Array.isArray(session.media) || session.media.length === 0) {
  23846. console.warn('The description has no media.');
  23847. return desc;
  23848. }
  23849. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  23850. // a video, an audio and a data "channel" at most.
  23851. if (session.media.length > 3 || !session.media.every(function(m) {
  23852. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  23853. })) {
  23854. console.warn('This description does not look like Plan B.');
  23855. return desc;
  23856. }
  23857. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  23858. var mids = [];
  23859. session.media.forEach(function(m) {
  23860. mids.push(m.mid);
  23861. });
  23862. var hasBundle = false;
  23863. if (typeof session.groups !== 'undefined' &&
  23864. Array.isArray(session.groups)) {
  23865. hasBundle = session.groups.every(function(g) {
  23866. return g.type !== 'BUNDLE' ||
  23867. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  23868. });
  23869. }
  23870. if (!hasBundle) {
  23871. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  23872. " are not bundled were found.");
  23873. }
  23874. //#endregion
  23875. //#region Convert from Plan B to Unified Plan.
  23876. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  23877. // rebuild an equivalent Unified Plan offer/answer.
  23878. //
  23879. // For example, if this is a local answer (in Unified Plan style) that we
  23880. // convert to Plan B prior to handing it over to the application (the
  23881. // PeerConnection wrapper called us, for instance, after a successful
  23882. // createAnswer), we want to remember the m-line at which we've seen the
  23883. // (local) SSRC. That's because when the application wants to do call the
  23884. // SLD method, forcing us to do the inverse transformation (from Plan B to
  23885. // Unified Plan), we need to know to which m-line to assign the (local)
  23886. // SSRC. We also need to know all the other m-lines that the original
  23887. // answer had and include them in the transformed answer as well.
  23888. //
  23889. // Another example is if this is a remote offer that we convert to Plan B
  23890. // prior to giving it to the application, we want to remember the mid at
  23891. // which we've seen the (remote) SSRC.
  23892. //
  23893. // In the iteration that follows, we use the cached Unified Plan (if it
  23894. // exists) to assign mids to ssrcs.
  23895. var cached;
  23896. if (typeof this.cache[desc.type] !== 'undefined') {
  23897. cached = transform.parse(this.cache[desc.type]);
  23898. }
  23899. // A helper map that sends mids to m-line objects. We use it later to
  23900. // rebuild the Unified Plan style session.media array.
  23901. var mid2ul = {};
  23902. session.media.forEach(function(bLine) {
  23903. if ((typeof bLine.rtcpMux !== 'string' ||
  23904. bLine.rtcpMux !== 'rtcp-mux') &&
  23905. bLine.direction !== 'inactive') {
  23906. throw new Error("Cannot convert to Unified Plan because m-lines " +
  23907. "without the rtcp-mux attribute were found.");
  23908. }
  23909. if (bLine.type === 'application') {
  23910. mid2ul[bLine.mid] = bLine;
  23911. return;
  23912. }
  23913. // With rtcp-mux and bundle all the channels should have the same ICE
  23914. // stuff.
  23915. var sources = bLine.sources;
  23916. var ssrcGroups = bLine.ssrcGroups;
  23917. var candidates = bLine.candidates;
  23918. var iceUfrag = bLine.iceUfrag;
  23919. var icePwd = bLine.icePwd;
  23920. var fingerprint = bLine.fingerprint;
  23921. var port = bLine.port;
  23922. // We'll use the "bLine" object as a prototype for each new "mLine"
  23923. // that we create, but first we need to clean it up a bit.
  23924. delete bLine.sources;
  23925. delete bLine.ssrcGroups;
  23926. delete bLine.candidates;
  23927. delete bLine.iceUfrag;
  23928. delete bLine.icePwd;
  23929. delete bLine.fingerprint;
  23930. delete bLine.port;
  23931. delete bLine.mid;
  23932. // inverted ssrc group map
  23933. var ssrc2group = {};
  23934. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  23935. ssrcGroups.forEach(function (ssrcGroup) {
  23936. // TODO(gp) find out how to receive simulcast with FF. For the
  23937. // time being, hide it.
  23938. if (ssrcGroup.semantics === 'SIM') {
  23939. return;
  23940. }
  23941. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  23942. Array.isArray(ssrcGroup.ssrcs)) {
  23943. ssrcGroup.ssrcs.forEach(function (ssrc) {
  23944. if (typeof ssrc2group[ssrc] === 'undefined') {
  23945. ssrc2group[ssrc] = [];
  23946. }
  23947. ssrc2group[ssrc].push(ssrcGroup);
  23948. });
  23949. }
  23950. });
  23951. }
  23952. // ssrc to m-line index.
  23953. var ssrc2ml = {};
  23954. if (typeof sources === 'object') {
  23955. // Explode the Plan B channel sources with one m-line per source.
  23956. Object.keys(sources).forEach(function(ssrc) {
  23957. // The (unified) m-line for this SSRC. We either create it from
  23958. // scratch or, if it's a grouped SSRC, we re-use a related
  23959. // mline. In other words, if the source is grouped with another
  23960. // source, put the two together in the same m-line.
  23961. var unifiedLine;
  23962. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  23963. Array.isArray(ssrc2group[ssrc])) {
  23964. ssrc2group[ssrc].some(function (ssrcGroup) {
  23965. // ssrcGroup.ssrcs *is* an Array, no need to check
  23966. // again here.
  23967. return ssrcGroup.ssrcs.some(function (related) {
  23968. if (typeof ssrc2ml[related] === 'object') {
  23969. unifiedLine = ssrc2ml[related];
  23970. return true;
  23971. }
  23972. });
  23973. });
  23974. }
  23975. if (typeof unifiedLine === 'object') {
  23976. // the m-line already exists. Just add the source.
  23977. unifiedLine.sources[ssrc] = sources[ssrc];
  23978. delete sources[ssrc].msid;
  23979. } else {
  23980. // Use the "bLine" as a prototype for the "unifiedLine".
  23981. unifiedLine = Object.create(bLine);
  23982. ssrc2ml[ssrc] = unifiedLine;
  23983. if (typeof sources[ssrc].msid !== 'undefined') {
  23984. // Assign the msid of the source to the m-line. Note
  23985. // that it is not guaranteed that the source will have
  23986. // msid. In particular "recvonly" sources don't have an
  23987. // msid. Note that "recvonly" is a term only defined
  23988. // for m-lines.
  23989. unifiedLine.msid = sources[ssrc].msid;
  23990. delete sources[ssrc].msid;
  23991. }
  23992. // We assign one SSRC per media line.
  23993. unifiedLine.sources = {};
  23994. unifiedLine.sources[ssrc] = sources[ssrc];
  23995. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  23996. // Use the cached Unified Plan SDP (if it exists) to assign
  23997. // SSRCs to mids.
  23998. if (typeof cached !== 'undefined' &&
  23999. typeof cached.media !== 'undefined' &&
  24000. Array.isArray(cached.media)) {
  24001. cached.media.forEach(function (m) {
  24002. if (typeof m.sources === 'object') {
  24003. Object.keys(m.sources).forEach(function (s) {
  24004. if (s === ssrc) {
  24005. unifiedLine.mid = m.mid;
  24006. }
  24007. });
  24008. }
  24009. });
  24010. }
  24011. if (typeof unifiedLine.mid === 'undefined') {
  24012. // If this is an SSRC that we see for the first time
  24013. // assign it a new mid. This is typically the case when
  24014. // this method is called to transform a remote
  24015. // description for the first time or when there is a
  24016. // new SSRC in the remote description because a new
  24017. // peer has joined the conference. Local SSRCs should
  24018. // have already been added to the map in the toPlanB
  24019. // method.
  24020. //
  24021. // Because FF generates answers in Unified Plan style,
  24022. // we MUST already have a cached answer with all the
  24023. // local SSRCs mapped to some m-line/mid.
  24024. if (desc.type === 'answer') {
  24025. throw new Error("An unmapped SSRC was found.");
  24026. }
  24027. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  24028. }
  24029. // Include the candidates in the 1st media line.
  24030. unifiedLine.candidates = candidates;
  24031. unifiedLine.iceUfrag = iceUfrag;
  24032. unifiedLine.icePwd = icePwd;
  24033. unifiedLine.fingerprint = fingerprint;
  24034. unifiedLine.port = port;
  24035. mid2ul[unifiedLine.mid] = unifiedLine;
  24036. }
  24037. });
  24038. }
  24039. });
  24040. // Rebuild the media array in the right order and add the missing mLines
  24041. // (missing from the Plan B SDP).
  24042. session.media = [];
  24043. mids = []; // reuse
  24044. if (desc.type === 'answer') {
  24045. // The media lines in the answer must match the media lines in the
  24046. // offer. The order is important too. Here we assume that Firefox is the
  24047. // answerer, so we merely have to use the reconstructed (unified) answer
  24048. // to update the cached (unified) answer accordingly.
  24049. //
  24050. // In the general case, one would have to use the cached (unified) offer
  24051. // to find the m-lines that are missing from the reconstructed answer,
  24052. // potentially grabbing them from the cached (unified) answer. One has
  24053. // to be carefull with this approach because inactive m-lines do not
  24054. // always have an mid, making it tricky (impossible?) to find where
  24055. // exactly and which m-lines are missing from the reconstructed answer.
  24056. for (var i = 0; i < cached.media.length; i++) {
  24057. var unifiedLine = cached.media[i];
  24058. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  24059. // The mid isn't in the reconstructed (unified) answer.
  24060. // This is either a (unified) m-line containing a remote
  24061. // track only, or a (unified) m-line containing a remote
  24062. // track and a local track that has been removed.
  24063. // In either case, it MUST exist in the cached
  24064. // (unified) answer.
  24065. //
  24066. // In case this is a removed local track, clean-up
  24067. // the (unified) m-line and make sure it's 'recvonly' or
  24068. // 'inactive'.
  24069. delete unifiedLine.msid;
  24070. delete unifiedLine.sources;
  24071. delete unifiedLine.ssrcGroups;
  24072. if (!unifiedLine.direction
  24073. || unifiedLine.direction === 'sendrecv')
  24074. unifiedLine.direction = 'recvonly';
  24075. if (!unifiedLine.direction
  24076. || unifiedLine.direction === 'sendonly')
  24077. unifiedLine.direction = 'inactive';
  24078. } else {
  24079. // This is an (unified) m-line/channel that contains a local
  24080. // track (sendrecv or sendonly channel) or it's a unified
  24081. // recvonly m-line/channel. In either case, since we're
  24082. // going from PlanB -> Unified Plan this m-line MUST
  24083. // exist in the cached answer.
  24084. }
  24085. session.media.push(unifiedLine);
  24086. if (typeof unifiedLine.mid === 'string') {
  24087. // inactive lines don't/may not have an mid.
  24088. mids.push(unifiedLine.mid);
  24089. }
  24090. }
  24091. } else {
  24092. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  24093. // under any circumstances. If we are no longer interested in sending a
  24094. // track, we just remove the msid and ssrc attributes and set it to
  24095. // either a=recvonly (as the reofferer, we must use recvonly if the
  24096. // other side was previously sending on the m-section, but we can also
  24097. // leave the possibility open if it wasn't previously in use), or
  24098. // a=inacive.
  24099. if (typeof cached !== 'undefined' &&
  24100. typeof cached.media !== 'undefined' &&
  24101. Array.isArray(cached.media)) {
  24102. cached.media.forEach(function(unifiedLine) {
  24103. mids.push(unifiedLine.mid);
  24104. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  24105. session.media.push(mid2ul[unifiedLine.mid]);
  24106. } else {
  24107. delete unifiedLine.msid;
  24108. delete unifiedLine.sources;
  24109. delete unifiedLine.ssrcGroups;
  24110. if (!unifiedLine.direction
  24111. || unifiedLine.direction === 'sendrecv')
  24112. unifiedLine.direction = 'recvonly';
  24113. if (!unifiedLine.direction
  24114. || unifiedLine.direction === 'sendonly')
  24115. unifiedLine.direction = 'inactive';
  24116. session.media.push(unifiedLine);
  24117. }
  24118. });
  24119. }
  24120. // Add all the remaining (new) m-lines of the transformed SDP.
  24121. Object.keys(mid2ul).forEach(function(mid) {
  24122. if (mids.indexOf(mid) === -1) {
  24123. mids.push(mid);
  24124. if (typeof mid2ul[mid].direction === 'recvonly') {
  24125. // This is a remote recvonly channel. Add its SSRC to the
  24126. // appropriate sendrecv or sendonly channel.
  24127. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  24128. session.media.some(function (unifiedLine) {
  24129. if ((unifiedLine.direction === 'sendrecv' ||
  24130. unifiedLine.direction === 'sendonly') &&
  24131. unifiedLine.type === mid2ul[mid].type) {
  24132. // mid2ul[mid] shouldn't have any ssrc-groups
  24133. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  24134. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  24135. });
  24136. return true;
  24137. }
  24138. });
  24139. } else {
  24140. session.media.push(mid2ul[mid]);
  24141. }
  24142. }
  24143. });
  24144. }
  24145. // We regenerate the BUNDLE group (since we regenerated the mids)
  24146. session.groups.some(function(group) {
  24147. if (group.type === 'BUNDLE') {
  24148. group.mids = mids.join(' ');
  24149. return true;
  24150. }
  24151. });
  24152. // msid semantic
  24153. session.msidSemantic = {
  24154. semantic: 'WMS',
  24155. token: '*'
  24156. };
  24157. var resStr = transform.write(session);
  24158. // Cache the transformed SDP (Unified Plan) for later re-use in this
  24159. // function.
  24160. this.cache[desc.type] = resStr;
  24161. return new RTCSessionDescription({
  24162. type: desc.type,
  24163. sdp: resStr
  24164. });
  24165. //#endregion
  24166. };
  24167. },{"./array-equals":88,"./transform":91}],91:[function(require,module,exports){
  24168. var transform = require('sdp-transform');
  24169. exports.write = function(session, opts) {
  24170. if (typeof session !== 'undefined' &&
  24171. typeof session.media !== 'undefined' &&
  24172. Array.isArray(session.media)) {
  24173. session.media.forEach(function (mLine) {
  24174. // expand sources to ssrcs
  24175. if (typeof mLine.sources !== 'undefined' &&
  24176. Object.keys(mLine.sources).length !== 0) {
  24177. mLine.ssrcs = [];
  24178. Object.keys(mLine.sources).forEach(function (ssrc) {
  24179. var source = mLine.sources[ssrc];
  24180. Object.keys(source).forEach(function (attribute) {
  24181. mLine.ssrcs.push({
  24182. id: ssrc,
  24183. attribute: attribute,
  24184. value: source[attribute]
  24185. });
  24186. });
  24187. });
  24188. delete mLine.sources;
  24189. }
  24190. // join ssrcs in ssrc groups
  24191. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24192. Array.isArray(mLine.ssrcGroups)) {
  24193. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24194. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24195. Array.isArray(ssrcGroup.ssrcs)) {
  24196. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  24197. }
  24198. });
  24199. }
  24200. });
  24201. }
  24202. // join group mids
  24203. if (typeof session !== 'undefined' &&
  24204. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  24205. session.groups.forEach(function (g) {
  24206. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  24207. g.mids = g.mids.join(' ');
  24208. }
  24209. });
  24210. }
  24211. return transform.write(session, opts);
  24212. };
  24213. exports.parse = function(sdp) {
  24214. var session = transform.parse(sdp);
  24215. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  24216. Array.isArray(session.media)) {
  24217. session.media.forEach(function (mLine) {
  24218. // group sources attributes by ssrc
  24219. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  24220. mLine.sources = {};
  24221. mLine.ssrcs.forEach(function (ssrc) {
  24222. if (!mLine.sources[ssrc.id])
  24223. mLine.sources[ssrc.id] = {};
  24224. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  24225. });
  24226. delete mLine.ssrcs;
  24227. }
  24228. // split ssrcs in ssrc groups
  24229. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24230. Array.isArray(mLine.ssrcGroups)) {
  24231. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24232. if (typeof ssrcGroup.ssrcs === 'string') {
  24233. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  24234. }
  24235. });
  24236. }
  24237. });
  24238. }
  24239. // split group mids
  24240. if (typeof session !== 'undefined' &&
  24241. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  24242. session.groups.forEach(function (g) {
  24243. if (typeof g.mids === 'string') {
  24244. g.mids = g.mids.split(' ');
  24245. }
  24246. });
  24247. }
  24248. return session;
  24249. };
  24250. },{"sdp-transform":95}],92:[function(require,module,exports){
  24251. var transform = require('sdp-transform');
  24252. var transformUtils = require('./transform-utils');
  24253. var parseSsrcs = transformUtils.parseSsrcs;
  24254. var writeSsrcs = transformUtils.writeSsrcs;
  24255. //region Constants
  24256. var DEFAULT_NUM_OF_LAYERS = 3;
  24257. //endregion
  24258. //region Ctor
  24259. function Simulcast(options) {
  24260. this.options = options ? options : {};
  24261. if (!this.options.numOfLayers) {
  24262. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  24263. }
  24264. this.layers = [];
  24265. }
  24266. //endregion
  24267. //region Stateless private utility functions
  24268. /**
  24269. * Returns a random integer between min (included) and max (excluded)
  24270. * Using Math.round() gives a non-uniform distribution!
  24271. * @returns {number}
  24272. */
  24273. function generateSSRC() {
  24274. var min = 0, max = 0xffffffff;
  24275. return Math.floor(Math.random() * (max - min)) + min;
  24276. };
  24277. function processVideo(session, action) {
  24278. if (session == null || !Array.isArray(session.media)) {
  24279. return;
  24280. }
  24281. session.media.forEach(function (mLine) {
  24282. if (mLine.type === 'video') {
  24283. action(mLine);
  24284. }
  24285. });
  24286. }
  24287. function validateDescription(desc)
  24288. {
  24289. return desc && desc != null
  24290. && desc.type && desc.type != ''
  24291. && desc.sdp && desc.sdp != '';
  24292. }
  24293. function explodeRemoteSimulcast(mLine) {
  24294. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  24295. return;
  24296. }
  24297. var sources = parseSsrcs(mLine);
  24298. var order = [];
  24299. // Find the SIM group and explode its sources.
  24300. var j = mLine.ssrcGroups.length;
  24301. while (j--) {
  24302. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  24303. continue;
  24304. }
  24305. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  24306. for (var i = 0; i < simulcastSsrcs.length; i++) {
  24307. var ssrc = simulcastSsrcs[i];
  24308. order.push(ssrc);
  24309. var parts = sources[ssrc].msid.split(' ');
  24310. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  24311. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  24312. // Remove all the groups that this SSRC participates in.
  24313. mLine.ssrcGroups.forEach(function (relatedGroup) {
  24314. if (relatedGroup.semantics === 'SIM') {
  24315. return;
  24316. }
  24317. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  24318. if (relatedSsrcs.indexOf(ssrc) === -1) {
  24319. return;
  24320. }
  24321. // Nuke all the related SSRCs.
  24322. relatedSsrcs.forEach(function (relatedSSRC) {
  24323. sources[relatedSSRC].msid = sources[ssrc].msid;
  24324. sources[relatedSSRC].cname = sources[ssrc].cname;
  24325. if (relatedSSRC !== ssrc) {
  24326. order.push(relatedSSRC);
  24327. }
  24328. });
  24329. // Schedule the related group for nuking.
  24330. })
  24331. }
  24332. mLine.ssrcs = writeSsrcs(sources, order);
  24333. mLine.ssrcGroups.splice(j, 1);
  24334. };
  24335. }
  24336. function squeezeRemoteSimulcast(mLine) {
  24337. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  24338. return;
  24339. }
  24340. var sources = parseSsrcs(mLine);
  24341. // Find the SIM group and nuke it.
  24342. mLine.ssrcGroups.some(function (simulcastGroup) {
  24343. if (simulcastGroup.semantics !== 'SIM') {
  24344. return false;
  24345. }
  24346. // Schedule the SIM group for nuking.
  24347. simulcastGroup.nuke = true;
  24348. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  24349. // Nuke all the higher layer SSRCs.
  24350. for (var i = 1; i < simulcastSsrcs.length; i++) {
  24351. var ssrc = simulcastSsrcs[i];
  24352. delete sources[ssrc];
  24353. // Remove all the groups that this SSRC participates in.
  24354. mLine.ssrcGroups.forEach(function (relatedGroup) {
  24355. if (relatedGroup.semantics === 'SIM') {
  24356. return;
  24357. }
  24358. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  24359. if (relatedSsrcs.indexOf(ssrc) === -1) {
  24360. return;
  24361. }
  24362. // Nuke all the related SSRCs.
  24363. relatedSsrcs.forEach(function (relatedSSRC) {
  24364. delete sources[relatedSSRC];
  24365. });
  24366. // Schedule the related group for nuking.
  24367. relatedGroup.nuke = true;
  24368. })
  24369. }
  24370. return true;
  24371. });
  24372. mLine.ssrcs = writeSsrcs(sources);
  24373. // Nuke all the scheduled groups.
  24374. var i = mLine.ssrcGroups.length;
  24375. while (i--) {
  24376. if (mLine.ssrcGroups[i].nuke) {
  24377. mLine.ssrcGroups.splice(i, 1);
  24378. }
  24379. }
  24380. }
  24381. function removeGoogConference(mLine) {
  24382. if (!mLine || !Array.isArray(mLine.invalid)) {
  24383. return;
  24384. }
  24385. var i = mLine.invalid.length;
  24386. while (i--) {
  24387. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  24388. mLine.invalid.splice(i, 1);
  24389. }
  24390. }
  24391. }
  24392. function assertGoogConference(mLine) {
  24393. if (!mLine) {
  24394. return;
  24395. }
  24396. if (!Array.isArray(mLine.invalid)) {
  24397. mLine.invalid = [];
  24398. }
  24399. if (!mLine.invalid.some(
  24400. function (i) { return i.value === 'x-google-flag:conference' })) {
  24401. mLine.invalid.push({'value': 'x-google-flag:conference'});
  24402. }
  24403. }
  24404. //endregion
  24405. //region "Private" functions
  24406. /**
  24407. *
  24408. * @param mLine
  24409. * @private
  24410. */
  24411. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  24412. if (!mLine || mLine.type !== 'video') {
  24413. return;
  24414. }
  24415. var sources = parseSsrcs(mLine);
  24416. if (Object.keys(sources).length === 0) {
  24417. // no sources, disable simulcast.
  24418. if (this.layers.length !== 0) {
  24419. this.layers = [];
  24420. }
  24421. return;
  24422. }
  24423. // find the base layer (we'll reuse its msid and cname).
  24424. var baseLayerSSRC = Object.keys(sources)[0];
  24425. var baseLayer = sources[baseLayerSSRC];
  24426. // todo(gp) handle screen sharing.
  24427. // check if base CNAME has changed and reinitialise layers.
  24428. if (this.layers.length > 0
  24429. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  24430. this.layers = [];
  24431. }
  24432. // (re)initialise layers
  24433. if (this.layers.length < 1) {
  24434. // first push the base layer.
  24435. this.layers.push({
  24436. ssrc: baseLayerSSRC,
  24437. msid: baseLayer.msid,
  24438. cname: baseLayer.cname
  24439. });
  24440. var rtx = false; // RFC 4588
  24441. if (Array.isArray(mLine.rtp)) {
  24442. rtx = mLine.rtp.some(
  24443. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  24444. }
  24445. if (rtx) {
  24446. this.layers[0].rtx = generateSSRC();
  24447. }
  24448. // now push additional layers.
  24449. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  24450. var layer = { ssrc: generateSSRC() };
  24451. if (rtx) {
  24452. layer.rtx = generateSSRC();
  24453. }
  24454. this.layers.push(layer);
  24455. }
  24456. }
  24457. };
  24458. /**
  24459. *
  24460. * @param mLine
  24461. * @private
  24462. */
  24463. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  24464. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  24465. var sources = {};
  24466. var msid = this.layers[0].msid;
  24467. var cname = this.layers[0].cname;
  24468. var simulcastSsrcs = [];
  24469. var ssrcGroups = [];
  24470. for (var i = 0; i < this.layers.length; i++) {
  24471. var layer = this.layers[i];
  24472. sources[layer.ssrc] = { msid: msid, cname: cname };
  24473. simulcastSsrcs.push(layer.ssrc);
  24474. if (layer.rtx) {
  24475. sources[layer.rtx] = {
  24476. msid: msid,
  24477. cname: cname
  24478. }
  24479. ssrcGroups.push({
  24480. semantics: 'FID',
  24481. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  24482. });
  24483. }
  24484. }
  24485. ssrcGroups.push({
  24486. semantics: 'SIM',
  24487. ssrcs: simulcastSsrcs.join(' ')
  24488. });
  24489. mLine.ssrcGroups = ssrcGroups;
  24490. mLine.ssrcs = writeSsrcs(sources);
  24491. }
  24492. }
  24493. //endregion
  24494. //region "Public" functions
  24495. Simulcast.prototype.isSupported = function () {
  24496. return window.chrome;
  24497. // TODO this needs improvements. For example I doubt that Chrome in Android
  24498. // has simulcast support. Also, only recent versions of Chromium have native
  24499. // simulcast support.
  24500. }
  24501. /**
  24502. *
  24503. * @param desc
  24504. * @returns {RTCSessionDescription}
  24505. */
  24506. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  24507. if (!validateDescription(desc)) {
  24508. return desc;
  24509. }
  24510. var session = transform.parse(desc.sdp);
  24511. var self = this;
  24512. processVideo(session, function (mLine) {
  24513. // Handle simulcast reception.
  24514. if (self.options.explodeRemoteSimulcast) {
  24515. explodeRemoteSimulcast(mLine);
  24516. } else {
  24517. squeezeRemoteSimulcast(mLine);
  24518. }
  24519. // If native simulcast is enabled, we must append the x-goog-conference
  24520. // attribute to the SDP.
  24521. if (self.layers.length < 1) {
  24522. removeGoogConference(mLine);
  24523. } else {
  24524. assertGoogConference(mLine);
  24525. }
  24526. });
  24527. return new RTCSessionDescription({
  24528. type: desc.type,
  24529. sdp: transform.write(session)
  24530. });
  24531. };
  24532. /**
  24533. *
  24534. * @param desc
  24535. * @returns {RTCSessionDescription}
  24536. */
  24537. Simulcast.prototype.mungeLocalDescription = function (desc) {
  24538. if (!validateDescription(desc) || !this.isSupported()) {
  24539. return desc;
  24540. }
  24541. var session = transform.parse(desc.sdp);
  24542. var self = this;
  24543. processVideo(session, function (mLine) {
  24544. // Initialize native simulcast layers, if not already done.
  24545. self._maybeInitializeLayers(mLine);
  24546. // Update the SDP with the simulcast layers.
  24547. self._restoreSimulcastView(mLine);
  24548. });
  24549. return new RTCSessionDescription({
  24550. type: desc.type,
  24551. sdp: transform.write(session)
  24552. });
  24553. };
  24554. //endregion
  24555. module.exports = Simulcast;
  24556. },{"./transform-utils":93,"sdp-transform":95}],93:[function(require,module,exports){
  24557. exports.writeSsrcs = function(sources, order) {
  24558. var ssrcs = [];
  24559. // expand sources to ssrcs
  24560. if (typeof sources !== 'undefined' &&
  24561. Object.keys(sources).length !== 0) {
  24562. if (Array.isArray(order)) {
  24563. for (var i = 0; i < order.length; i++) {
  24564. var ssrc = order[i];
  24565. var source = sources[ssrc];
  24566. Object.keys(source).forEach(function (attribute) {
  24567. ssrcs.push({
  24568. id: ssrc,
  24569. attribute: attribute,
  24570. value: source[attribute]
  24571. });
  24572. });
  24573. }
  24574. } else {
  24575. Object.keys(sources).forEach(function (ssrc) {
  24576. var source = sources[ssrc];
  24577. Object.keys(source).forEach(function (attribute) {
  24578. ssrcs.push({
  24579. id: ssrc,
  24580. attribute: attribute,
  24581. value: source[attribute]
  24582. });
  24583. });
  24584. });
  24585. }
  24586. }
  24587. return ssrcs;
  24588. };
  24589. exports.parseSsrcs = function (mLine) {
  24590. var sources = {};
  24591. // group sources attributes by ssrc.
  24592. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  24593. mLine.ssrcs.forEach(function (ssrc) {
  24594. if (!sources[ssrc.id])
  24595. sources[ssrc.id] = {};
  24596. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  24597. });
  24598. }
  24599. return sources;
  24600. };
  24601. },{}],94:[function(require,module,exports){
  24602. var grammar = module.exports = {
  24603. v: [{
  24604. name: 'version',
  24605. reg: /^(\d*)$/
  24606. }],
  24607. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  24608. // NB: sessionId will be a String in most cases because it is huge
  24609. name: 'origin',
  24610. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  24611. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  24612. format: "%s %s %d %s IP%d %s"
  24613. }],
  24614. // default parsing of these only (though some of these feel outdated)
  24615. s: [{ name: 'name' }],
  24616. i: [{ name: 'description' }],
  24617. u: [{ name: 'uri' }],
  24618. e: [{ name: 'email' }],
  24619. p: [{ name: 'phone' }],
  24620. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  24621. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  24622. //k: [{}], // outdated thing ignored
  24623. t: [{ //t=0 0
  24624. name: 'timing',
  24625. reg: /^(\d*) (\d*)/,
  24626. names: ['start', 'stop'],
  24627. format: "%d %d"
  24628. }],
  24629. c: [{ //c=IN IP4 10.47.197.26
  24630. name: 'connection',
  24631. reg: /^IN IP(\d) (\S*)/,
  24632. names: ['version', 'ip'],
  24633. format: "IN IP%d %s"
  24634. }],
  24635. b: [{ //b=AS:4000
  24636. push: 'bandwidth',
  24637. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  24638. names: ['type', 'limit'],
  24639. format: "%s:%s"
  24640. }],
  24641. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  24642. // NB: special - pushes to session
  24643. // TODO: rtp/fmtp should be filtered by the payloads found here?
  24644. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  24645. names: ['type', 'port', 'protocol', 'payloads'],
  24646. format: "%s %d %s %s"
  24647. }],
  24648. a: [
  24649. { //a=rtpmap:110 opus/48000/2
  24650. push: 'rtp',
  24651. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  24652. names: ['payload', 'codec', 'rate', 'encoding'],
  24653. format: function (o) {
  24654. return (o.encoding) ?
  24655. "rtpmap:%d %s/%s/%s":
  24656. "rtpmap:%d %s/%s";
  24657. }
  24658. },
  24659. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  24660. push: 'fmtp',
  24661. reg: /^fmtp:(\d*) (\S*)/,
  24662. names: ['payload', 'config'],
  24663. format: "fmtp:%d %s"
  24664. },
  24665. { //a=control:streamid=0
  24666. name: 'control',
  24667. reg: /^control:(.*)/,
  24668. format: "control:%s"
  24669. },
  24670. { //a=rtcp:65179 IN IP4 193.84.77.194
  24671. name: 'rtcp',
  24672. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  24673. names: ['port', 'netType', 'ipVer', 'address'],
  24674. format: function (o) {
  24675. return (o.address != null) ?
  24676. "rtcp:%d %s IP%d %s":
  24677. "rtcp:%d";
  24678. }
  24679. },
  24680. { //a=rtcp-fb:98 trr-int 100
  24681. push: 'rtcpFbTrrInt',
  24682. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  24683. names: ['payload', 'value'],
  24684. format: "rtcp-fb:%d trr-int %d"
  24685. },
  24686. { //a=rtcp-fb:98 nack rpsi
  24687. push: 'rtcpFb',
  24688. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  24689. names: ['payload', 'type', 'subtype'],
  24690. format: function (o) {
  24691. return (o.subtype != null) ?
  24692. "rtcp-fb:%s %s %s":
  24693. "rtcp-fb:%s %s";
  24694. }
  24695. },
  24696. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  24697. //a=extmap:1/recvonly URI-gps-string
  24698. push: 'ext',
  24699. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  24700. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  24701. format: function (o) {
  24702. return (o.config != null) ?
  24703. "extmap:%s %s %s":
  24704. "extmap:%s %s";
  24705. }
  24706. },
  24707. {
  24708. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  24709. push: 'crypto',
  24710. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  24711. names: ['id', 'suite', 'config', 'sessionConfig'],
  24712. format: function (o) {
  24713. return (o.sessionConfig != null) ?
  24714. "crypto:%d %s %s %s":
  24715. "crypto:%d %s %s";
  24716. }
  24717. },
  24718. { //a=setup:actpass
  24719. name: 'setup',
  24720. reg: /^setup:(\w*)/,
  24721. format: "setup:%s"
  24722. },
  24723. { //a=mid:1
  24724. name: 'mid',
  24725. reg: /^mid:([^\s]*)/,
  24726. format: "mid:%s"
  24727. },
  24728. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  24729. name: 'msid',
  24730. reg: /^msid:(.*)/,
  24731. format: "msid:%s"
  24732. },
  24733. { //a=ptime:20
  24734. name: 'ptime',
  24735. reg: /^ptime:(\d*)/,
  24736. format: "ptime:%d"
  24737. },
  24738. { //a=maxptime:60
  24739. name: 'maxptime',
  24740. reg: /^maxptime:(\d*)/,
  24741. format: "maxptime:%d"
  24742. },
  24743. { //a=sendrecv
  24744. name: 'direction',
  24745. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  24746. },
  24747. { //a=ice-lite
  24748. name: 'icelite',
  24749. reg: /^(ice-lite)/
  24750. },
  24751. { //a=ice-ufrag:F7gI
  24752. name: 'iceUfrag',
  24753. reg: /^ice-ufrag:(\S*)/,
  24754. format: "ice-ufrag:%s"
  24755. },
  24756. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  24757. name: 'icePwd',
  24758. reg: /^ice-pwd:(\S*)/,
  24759. format: "ice-pwd:%s"
  24760. },
  24761. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  24762. name: 'fingerprint',
  24763. reg: /^fingerprint:(\S*) (\S*)/,
  24764. names: ['type', 'hash'],
  24765. format: "fingerprint:%s %s"
  24766. },
  24767. {
  24768. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  24769. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  24770. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  24771. push:'candidates',
  24772. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  24773. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  24774. format: function (o) {
  24775. var str = "candidate:%s %d %s %d %s %d typ %s";
  24776. // NB: candidate has two optional chunks, so %void middle one if it's missing
  24777. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  24778. if (o.generation != null) {
  24779. str += " generation %d";
  24780. }
  24781. return str;
  24782. }
  24783. },
  24784. { //a=end-of-candidates (keep after the candidates line for readability)
  24785. name: 'endOfCandidates',
  24786. reg: /^(end-of-candidates)/
  24787. },
  24788. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  24789. name: 'remoteCandidates',
  24790. reg: /^remote-candidates:(.*)/,
  24791. format: "remote-candidates:%s"
  24792. },
  24793. { //a=ice-options:google-ice
  24794. name: 'iceOptions',
  24795. reg: /^ice-options:(\S*)/,
  24796. format: "ice-options:%s"
  24797. },
  24798. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  24799. push: "ssrcs",
  24800. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  24801. names: ['id', 'attribute', 'value'],
  24802. format: "ssrc:%d %s:%s"
  24803. },
  24804. { //a=ssrc-group:FEC 1 2
  24805. push: "ssrcGroups",
  24806. reg: /^ssrc-group:(\w*) (.*)/,
  24807. names: ['semantics', 'ssrcs'],
  24808. format: "ssrc-group:%s %s"
  24809. },
  24810. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  24811. name: "msidSemantic",
  24812. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  24813. names: ['semantic', 'token'],
  24814. format: "msid-semantic: %s %s" // space after ":" is not accidental
  24815. },
  24816. { //a=group:BUNDLE audio video
  24817. push: 'groups',
  24818. reg: /^group:(\w*) (.*)/,
  24819. names: ['type', 'mids'],
  24820. format: "group:%s %s"
  24821. },
  24822. { //a=rtcp-mux
  24823. name: 'rtcpMux',
  24824. reg: /^(rtcp-mux)/
  24825. },
  24826. { //a=rtcp-rsize
  24827. name: 'rtcpRsize',
  24828. reg: /^(rtcp-rsize)/
  24829. },
  24830. { // any a= that we don't understand is kepts verbatim on media.invalid
  24831. push: 'invalid',
  24832. names: ["value"]
  24833. }
  24834. ]
  24835. };
  24836. // set sensible defaults to avoid polluting the grammar with boring details
  24837. Object.keys(grammar).forEach(function (key) {
  24838. var objs = grammar[key];
  24839. objs.forEach(function (obj) {
  24840. if (!obj.reg) {
  24841. obj.reg = /(.*)/;
  24842. }
  24843. if (!obj.format) {
  24844. obj.format = "%s";
  24845. }
  24846. });
  24847. });
  24848. },{}],95:[function(require,module,exports){
  24849. var parser = require('./parser');
  24850. var writer = require('./writer');
  24851. exports.write = writer;
  24852. exports.parse = parser.parse;
  24853. exports.parseFmtpConfig = parser.parseFmtpConfig;
  24854. exports.parsePayloads = parser.parsePayloads;
  24855. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  24856. },{"./parser":96,"./writer":97}],96:[function(require,module,exports){
  24857. var toIntIfInt = function (v) {
  24858. return String(Number(v)) === v ? Number(v) : v;
  24859. };
  24860. var attachProperties = function (match, location, names, rawName) {
  24861. if (rawName && !names) {
  24862. location[rawName] = toIntIfInt(match[1]);
  24863. }
  24864. else {
  24865. for (var i = 0; i < names.length; i += 1) {
  24866. if (match[i+1] != null) {
  24867. location[names[i]] = toIntIfInt(match[i+1]);
  24868. }
  24869. }
  24870. }
  24871. };
  24872. var parseReg = function (obj, location, content) {
  24873. var needsBlank = obj.name && obj.names;
  24874. if (obj.push && !location[obj.push]) {
  24875. location[obj.push] = [];
  24876. }
  24877. else if (needsBlank && !location[obj.name]) {
  24878. location[obj.name] = {};
  24879. }
  24880. var keyLocation = obj.push ?
  24881. {} : // blank object that will be pushed
  24882. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  24883. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  24884. if (obj.push) {
  24885. location[obj.push].push(keyLocation);
  24886. }
  24887. };
  24888. var grammar = require('./grammar');
  24889. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  24890. exports.parse = function (sdp) {
  24891. var session = {}
  24892. , media = []
  24893. , location = session; // points at where properties go under (one of the above)
  24894. // parse lines we understand
  24895. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  24896. var type = l[0];
  24897. var content = l.slice(2);
  24898. if (type === 'm') {
  24899. media.push({rtp: [], fmtp: []});
  24900. location = media[media.length-1]; // point at latest media line
  24901. }
  24902. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  24903. var obj = grammar[type][j];
  24904. if (obj.reg.test(content)) {
  24905. return parseReg(obj, location, content);
  24906. }
  24907. }
  24908. });
  24909. session.media = media; // link it up
  24910. return session;
  24911. };
  24912. var fmtpReducer = function (acc, expr) {
  24913. var s = expr.split('=');
  24914. if (s.length === 2) {
  24915. acc[s[0]] = toIntIfInt(s[1]);
  24916. }
  24917. return acc;
  24918. };
  24919. exports.parseFmtpConfig = function (str) {
  24920. return str.split(';').reduce(fmtpReducer, {});
  24921. };
  24922. exports.parsePayloads = function (str) {
  24923. return str.split(' ').map(Number);
  24924. };
  24925. exports.parseRemoteCandidates = function (str) {
  24926. var candidates = [];
  24927. var parts = str.split(' ').map(toIntIfInt);
  24928. for (var i = 0; i < parts.length; i += 3) {
  24929. candidates.push({
  24930. component: parts[i],
  24931. ip: parts[i + 1],
  24932. port: parts[i + 2]
  24933. });
  24934. }
  24935. return candidates;
  24936. };
  24937. },{"./grammar":94}],97:[function(require,module,exports){
  24938. var grammar = require('./grammar');
  24939. // customized util.format - discards excess arguments and can void middle ones
  24940. var formatRegExp = /%[sdv%]/g;
  24941. var format = function (formatStr) {
  24942. var i = 1;
  24943. var args = arguments;
  24944. var len = args.length;
  24945. return formatStr.replace(formatRegExp, function (x) {
  24946. if (i >= len) {
  24947. return x; // missing argument
  24948. }
  24949. var arg = args[i];
  24950. i += 1;
  24951. switch (x) {
  24952. case '%%':
  24953. return '%';
  24954. case '%s':
  24955. return String(arg);
  24956. case '%d':
  24957. return Number(arg);
  24958. case '%v':
  24959. return '';
  24960. }
  24961. });
  24962. // NB: we discard excess arguments - they are typically undefined from makeLine
  24963. };
  24964. var makeLine = function (type, obj, location) {
  24965. var str = obj.format instanceof Function ?
  24966. (obj.format(obj.push ? location : location[obj.name])) :
  24967. obj.format;
  24968. var args = [type + '=' + str];
  24969. if (obj.names) {
  24970. for (var i = 0; i < obj.names.length; i += 1) {
  24971. var n = obj.names[i];
  24972. if (obj.name) {
  24973. args.push(location[obj.name][n]);
  24974. }
  24975. else { // for mLine and push attributes
  24976. args.push(location[obj.names[i]]);
  24977. }
  24978. }
  24979. }
  24980. else {
  24981. args.push(location[obj.name]);
  24982. }
  24983. return format.apply(null, args);
  24984. };
  24985. // RFC specified order
  24986. // TODO: extend this with all the rest
  24987. var defaultOuterOrder = [
  24988. 'v', 'o', 's', 'i',
  24989. 'u', 'e', 'p', 'c',
  24990. 'b', 't', 'r', 'z', 'a'
  24991. ];
  24992. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  24993. module.exports = function (session, opts) {
  24994. opts = opts || {};
  24995. // ensure certain properties exist
  24996. if (session.version == null) {
  24997. session.version = 0; // "v=0" must be there (only defined version atm)
  24998. }
  24999. if (session.name == null) {
  25000. session.name = " "; // "s= " must be there if no meaningful name set
  25001. }
  25002. session.media.forEach(function (mLine) {
  25003. if (mLine.payloads == null) {
  25004. mLine.payloads = "";
  25005. }
  25006. });
  25007. var outerOrder = opts.outerOrder || defaultOuterOrder;
  25008. var innerOrder = opts.innerOrder || defaultInnerOrder;
  25009. var sdp = [];
  25010. // loop through outerOrder for matching properties on session
  25011. outerOrder.forEach(function (type) {
  25012. grammar[type].forEach(function (obj) {
  25013. if (obj.name in session && session[obj.name] != null) {
  25014. sdp.push(makeLine(type, obj, session));
  25015. }
  25016. else if (obj.push in session && session[obj.push] != null) {
  25017. session[obj.push].forEach(function (el) {
  25018. sdp.push(makeLine(type, obj, el));
  25019. });
  25020. }
  25021. });
  25022. });
  25023. // then for each media line, follow the innerOrder
  25024. session.media.forEach(function (mLine) {
  25025. sdp.push(makeLine('m', grammar.m[0], mLine));
  25026. innerOrder.forEach(function (type) {
  25027. grammar[type].forEach(function (obj) {
  25028. if (obj.name in mLine && mLine[obj.name] != null) {
  25029. sdp.push(makeLine(type, obj, mLine));
  25030. }
  25031. else if (obj.push in mLine && mLine[obj.push] != null) {
  25032. mLine[obj.push].forEach(function (el) {
  25033. sdp.push(makeLine(type, obj, el));
  25034. });
  25035. }
  25036. });
  25037. });
  25038. });
  25039. return sdp.join('\r\n') + '\r\n';
  25040. };
  25041. },{"./grammar":94}],98:[function(require,module,exports){
  25042. var MediaStreamType = {
  25043. VIDEO_TYPE: "Video",
  25044. AUDIO_TYPE: "Audio"
  25045. };
  25046. module.exports = MediaStreamType;
  25047. },{}],99:[function(require,module,exports){
  25048. var RTCBrowserType = {
  25049. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  25050. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  25051. };
  25052. module.exports = RTCBrowserType;
  25053. },{}],100:[function(require,module,exports){
  25054. var RTCEvents = {
  25055. LASTN_CHANGED: "rtc.lastn_changed",
  25056. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  25057. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  25058. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  25059. AUDIO_MUTE: "rtc.audio_mute",
  25060. VIDEO_MUTE: "rtc.video_mute"
  25061. };
  25062. module.exports = RTCEvents;
  25063. },{}],101:[function(require,module,exports){
  25064. var Resolutions = {
  25065. "1080": {
  25066. width: 1920,
  25067. height: 1080,
  25068. order: 7
  25069. },
  25070. "fullhd": {
  25071. width: 1920,
  25072. height: 1080,
  25073. order: 7
  25074. },
  25075. "720": {
  25076. width: 1280,
  25077. height: 720,
  25078. order: 6
  25079. },
  25080. "hd": {
  25081. width: 1280,
  25082. height: 720,
  25083. order: 6
  25084. },
  25085. "960": {
  25086. width: 960,
  25087. height: 720,
  25088. order: 5
  25089. },
  25090. "640": {
  25091. width: 640,
  25092. height: 480,
  25093. order: 4
  25094. },
  25095. "vga": {
  25096. width: 640,
  25097. height: 480,
  25098. order: 4
  25099. },
  25100. "360": {
  25101. width: 640,
  25102. height: 360,
  25103. order: 3
  25104. },
  25105. "320": {
  25106. width: 320,
  25107. height: 240,
  25108. order: 2
  25109. },
  25110. "180": {
  25111. width: 320,
  25112. height: 180,
  25113. order: 1
  25114. }
  25115. };
  25116. module.exports = Resolutions;
  25117. },{}],102:[function(require,module,exports){
  25118. var StreamEventTypes = {
  25119. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  25120. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  25121. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  25122. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  25123. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  25124. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  25125. };
  25126. module.exports = StreamEventTypes;
  25127. },{}],103:[function(require,module,exports){
  25128. var UIEvents = {
  25129. NICKNAME_CHANGED: "UI.nickname_changed",
  25130. SELECTED_ENDPOINT: "UI.selected_endpoint",
  25131. PINNED_ENDPOINT: "UI.pinned_endpoint"
  25132. };
  25133. module.exports = UIEvents;
  25134. },{}],104:[function(require,module,exports){
  25135. var AuthenticationEvents = {
  25136. /**
  25137. * Event callback arguments:
  25138. * function(authenticationEnabled, userIdentity)
  25139. * authenticationEnabled - indicates whether authentication has been enabled
  25140. * in this session
  25141. * userIdentity - if user has been logged in then it contains user name. If
  25142. * contains 'null' or 'undefined' then user is not logged in.
  25143. */
  25144. IDENTITY_UPDATED: "authentication.identity_updated"
  25145. };
  25146. module.exports = AuthenticationEvents;
  25147. },{}],105:[function(require,module,exports){
  25148. var CQEvents = {
  25149. LOCALSTATS_UPDATED: "cq.localstats_updated",
  25150. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  25151. STOP: "cq.stop"
  25152. };
  25153. module.exports = CQEvents;
  25154. },{}],106:[function(require,module,exports){
  25155. var DesktopSharingEventTypes = {
  25156. INIT: "ds.init",
  25157. SWITCHING_DONE: "ds.switching_done",
  25158. NEW_STREAM_CREATED: "ds.new_stream_created"
  25159. };
  25160. module.exports = DesktopSharingEventTypes;
  25161. },{}],107:[function(require,module,exports){
  25162. var Events = {
  25163. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  25164. };
  25165. module.exports = Events;
  25166. },{}],108:[function(require,module,exports){
  25167. module.exports = {
  25168. getLanguages : function () {
  25169. var languages = [];
  25170. for(var lang in this)
  25171. {
  25172. if(typeof this[lang] === "string")
  25173. languages.push(this[lang]);
  25174. }
  25175. return languages;
  25176. },
  25177. EN: "en",
  25178. BG: "bg",
  25179. DE: "de",
  25180. TR: "tr",
  25181. FR: "fr"
  25182. }
  25183. },{}],109:[function(require,module,exports){
  25184. var XMPPEvents = {
  25185. CONNECTION_FAILED: "xmpp.connection.failed",
  25186. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  25187. CALL_INCOMING: "xmpp.callincoming.jingle",
  25188. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  25189. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  25190. KICKED: "xmpp.kicked",
  25191. BRIDGE_DOWN: "xmpp.bridge_down",
  25192. USER_ID_CHANGED: "xmpp.user_id_changed",
  25193. STREAMS_CHANGED: "xmpp.streams_changed",
  25194. // We joined the MUC
  25195. MUC_JOINED: "xmpp.muc_joined",
  25196. // A member joined the MUC
  25197. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  25198. // A member left the MUC
  25199. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  25200. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  25201. MUC_DESTROYED: "xmpp.muc_destroyed",
  25202. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  25203. REMOTE_STATS: "xmpp.remote_stats",
  25204. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  25205. PRESENCE_STATUS: "xmpp.presence_status",
  25206. RESERVATION_ERROR: "xmpp.room_reservation_error",
  25207. SUBJECT_CHANGED: "xmpp.subject_changed",
  25208. MESSAGE_RECEIVED: "xmpp.message_received",
  25209. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  25210. PASSWORD_REQUIRED: "xmpp.password_required",
  25211. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  25212. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  25213. ETHERPAD: "xmpp.etherpad",
  25214. DEVICE_AVAILABLE: "xmpp.device_available",
  25215. START_MUTED: "xmpp.start_muted",
  25216. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  25217. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  25218. AUDIO_MUTED: "xmpp.audio_muted",
  25219. VIDEO_MUTED: "xmpp.video_muted"
  25220. };
  25221. module.exports = XMPPEvents;
  25222. },{}]},{},[3])(3)
  25223. });