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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826
  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. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  13. this.xmpp = require("./modules/xmpp/xmpp");
  14. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  15. this.translation = require("./modules/translation/translation");
  16. this.settings = require("./modules/settings/Settings");
  17. this.DTMF = require("./modules/DTMF/DTMF");
  18. this.members = require("./modules/members/MemberList");
  19. }
  20. };
  21. function init() {
  22. APP.RTC.start();
  23. APP.xmpp.start();
  24. APP.statistics.start();
  25. APP.connectionquality.init();
  26. // Set default desktop sharing method
  27. APP.desktopsharing.init();
  28. APP.keyboardshortcut.init();
  29. APP.members.start();
  30. }
  31. $(document).ready(function () {
  32. var URLPRocessor = require("./modules/URLProcessor/URLProcessor");
  33. URLPRocessor.setConfigParametersFromUrl();
  34. APP.init();
  35. APP.translation.init();
  36. if(APP.API.isEnabled())
  37. APP.API.init();
  38. APP.UI.start(init);
  39. });
  40. $(window).bind('beforeunload', function () {
  41. if(APP.API.isEnabled())
  42. APP.API.dispose();
  43. });
  44. module.exports = APP;
  45. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":9,"./modules/URLProcessor/URLProcessor":36,"./modules/connectionquality/connectionquality":37,"./modules/desktopsharing/desktopsharing":38,"./modules/keyboardshortcut/keyboardshortcut":39,"./modules/members/MemberList":40,"./modules/settings/Settings":41,"./modules/statistics/statistics":44,"./modules/translation/translation":45,"./modules/xmpp/xmpp":59}],2:[function(require,module,exports){
  46. /**
  47. * Implements API class that communicates with external api class
  48. * and provides interface to access Jitsi Meet features by external
  49. * applications that embed Jitsi Meet
  50. */
  51. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  52. /**
  53. * List of the available commands.
  54. * @type {{
  55. * displayName: inputDisplayNameHandler,
  56. * muteAudio: toggleAudio,
  57. * muteVideo: toggleVideo,
  58. * filmStrip: toggleFilmStrip
  59. * }}
  60. */
  61. var commands =
  62. {
  63. displayName: APP.UI.inputDisplayNameHandler,
  64. muteAudio: APP.UI.toggleAudio,
  65. muteVideo: APP.UI.toggleVideo,
  66. toggleFilmStrip: APP.UI.toggleFilmStrip,
  67. toggleChat: APP.UI.toggleChat,
  68. toggleContactList: APP.UI.toggleContactList
  69. };
  70. /**
  71. * Maps the supported events and their status
  72. * (true it the event is enabled and false if it is disabled)
  73. * @type {{
  74. * incomingMessage: boolean,
  75. * outgoingMessage: boolean,
  76. * displayNameChange: boolean,
  77. * participantJoined: boolean,
  78. * participantLeft: boolean
  79. * }}
  80. */
  81. var events =
  82. {
  83. incomingMessage: false,
  84. outgoingMessage:false,
  85. displayNameChange: false,
  86. participantJoined: false,
  87. participantLeft: false
  88. };
  89. var displayName = {};
  90. /**
  91. * Processes commands from external applicaiton.
  92. * @param message the object with the command
  93. */
  94. function processCommand(message)
  95. {
  96. if(message.action != "execute")
  97. {
  98. console.error("Unknown action of the message");
  99. return;
  100. }
  101. for(var key in message)
  102. {
  103. if(commands[key])
  104. commands[key].apply(null, message[key]);
  105. }
  106. }
  107. /**
  108. * Processes events objects from external applications
  109. * @param event the event
  110. */
  111. function processEvent(event) {
  112. if(!event.action)
  113. {
  114. console.error("Event with no action is received.");
  115. return;
  116. }
  117. var i = 0;
  118. switch(event.action)
  119. {
  120. case "add":
  121. for(; i < event.events.length; i++)
  122. {
  123. events[event.events[i]] = true;
  124. }
  125. break;
  126. case "remove":
  127. for(; i < event.events.length; i++)
  128. {
  129. events[event.events[i]] = false;
  130. }
  131. break;
  132. default:
  133. console.error("Unknown action for event.");
  134. }
  135. }
  136. /**
  137. * Sends message to the external application.
  138. * @param object
  139. */
  140. function sendMessage(object) {
  141. window.parent.postMessage(JSON.stringify(object), "*");
  142. }
  143. /**
  144. * Processes a message event from the external application
  145. * @param event the message event
  146. */
  147. function processMessage(event)
  148. {
  149. var message;
  150. try {
  151. message = JSON.parse(event.data);
  152. } catch (e) {}
  153. if(!message.type)
  154. return;
  155. switch (message.type)
  156. {
  157. case "command":
  158. processCommand(message);
  159. break;
  160. case "event":
  161. processEvent(message);
  162. break;
  163. default:
  164. console.error("Unknown type of the message");
  165. return;
  166. }
  167. }
  168. function setupListeners() {
  169. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  170. API.triggerEvent("participantJoined", {jid: from});
  171. });
  172. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  173. if (from != myjid)
  174. API.triggerEvent("incomingMessage",
  175. {"from": from, "nick": nick, "message": txt});
  176. });
  177. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  178. API.triggerEvent("participantLeft", {jid: jid});
  179. });
  180. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  181. name = displayName[jid];
  182. if(!name || name != newDisplayName) {
  183. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  184. displayName[jid] = newDisplayName;
  185. }
  186. });
  187. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  188. APP.API.triggerEvent("outgoingMessage", {"message": body});
  189. });
  190. }
  191. var API = {
  192. /**
  193. * Check whether the API should be enabled or not.
  194. * @returns {boolean}
  195. */
  196. isEnabled: function () {
  197. var hash = location.hash;
  198. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  199. return true;
  200. return false;
  201. },
  202. /**
  203. * Initializes the APIConnector. Setups message event listeners that will
  204. * receive information from external applications that embed Jitsi Meet.
  205. * It also sends a message to the external application that APIConnector
  206. * is initialized.
  207. */
  208. init: function () {
  209. if (window.addEventListener)
  210. {
  211. window.addEventListener('message',
  212. processMessage, false);
  213. }
  214. else
  215. {
  216. window.attachEvent('onmessage', processMessage);
  217. }
  218. sendMessage({type: "system", loaded: true});
  219. setupListeners();
  220. },
  221. /**
  222. * Checks whether the event is enabled ot not.
  223. * @param name the name of the event.
  224. * @returns {*}
  225. */
  226. isEventEnabled: function (name) {
  227. return events[name];
  228. },
  229. /**
  230. * Sends event object to the external application that has been subscribed
  231. * for that event.
  232. * @param name the name event
  233. * @param object data associated with the event
  234. */
  235. triggerEvent: function (name, object) {
  236. if(this.isEnabled() && this.isEventEnabled(name))
  237. sendMessage({
  238. type: "event", action: "result", event: name, result: object});
  239. },
  240. /**
  241. * Removes the listeners.
  242. */
  243. dispose: function () {
  244. if(window.removeEventListener)
  245. {
  246. window.removeEventListener("message",
  247. processMessage, false);
  248. }
  249. else
  250. {
  251. window.detachEvent('onmessage', processMessage);
  252. }
  253. }
  254. };
  255. module.exports = API;
  256. },{"../../service/xmpp/XMPPEvents":112}],3:[function(require,module,exports){
  257. /* global APP */
  258. /**
  259. * A module for sending DTMF tones.
  260. */
  261. var DTMFSender;
  262. var initDtmfSender = function() {
  263. // TODO: This needs to reset this if the peerconnection changes
  264. // (e.g. the call is re-made)
  265. if (DTMFSender)
  266. return;
  267. var localAudio = APP.RTC.localAudio;
  268. if (localAudio && localAudio.getTracks().length > 0)
  269. {
  270. var peerconnection
  271. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  272. if (peerconnection) {
  273. DTMFSender =
  274. peerconnection.peerconnection
  275. .createDTMFSender(localAudio.getTracks()[0]);
  276. console.log("Initialized DTMFSender");
  277. }
  278. else {
  279. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  280. }
  281. }
  282. else {
  283. console.log("Failed to initialize DTMFSender: no audio track.");
  284. }
  285. };
  286. var DTMF = {
  287. sendTones: function (tones, duration, pause) {
  288. if (!DTMFSender)
  289. initDtmfSender();
  290. if (DTMFSender){
  291. DTMFSender.insertDTMF(tones,
  292. (duration || 200),
  293. (pause || 200));
  294. }
  295. }
  296. };
  297. module.exports = DTMF;
  298. },{}],4:[function(require,module,exports){
  299. /* global Strophe, focusedVideoSrc*/
  300. // cache datachannels to avoid garbage collection
  301. // https://code.google.com/p/chromium/issues/detail?id=405545
  302. var RTCEvents = require("../../service/RTC/RTCEvents");
  303. var _dataChannels = [];
  304. var eventEmitter = null;
  305. var DataChannels =
  306. {
  307. /**
  308. * Callback triggered by PeerConnection when new data channel is opened
  309. * on the bridge.
  310. * @param event the event info object.
  311. */
  312. onDataChannel: function (event)
  313. {
  314. var dataChannel = event.channel;
  315. dataChannel.onopen = function () {
  316. console.info("Data channel opened by the Videobridge!", dataChannel);
  317. // Code sample for sending string and/or binary data
  318. // Sends String message to the bridge
  319. //dataChannel.send("Hello bridge!");
  320. // Sends 12 bytes binary message to the bridge
  321. //dataChannel.send(new ArrayBuffer(12));
  322. // when the data channel becomes available, tell the bridge about video
  323. // selections so that it can do adaptive simulcast,
  324. // we want the notification to trigger even if userJid is undefined,
  325. // or null.
  326. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  327. // we want the notification to trigger even if userJid is undefined,
  328. // or null.
  329. onSelectedEndpointChanged(userJid);
  330. };
  331. dataChannel.onerror = function (error) {
  332. console.error("Data Channel Error:", error, dataChannel);
  333. };
  334. dataChannel.onmessage = function (event) {
  335. var data = event.data;
  336. // JSON
  337. var obj;
  338. try {
  339. obj = JSON.parse(data);
  340. }
  341. catch (e) {
  342. console.error(
  343. "Failed to parse data channel message as JSON: ",
  344. data,
  345. dataChannel);
  346. }
  347. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  348. var colibriClass = obj.colibriClass;
  349. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  350. // Endpoint ID from the Videobridge.
  351. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  352. console.info(
  353. "Data channel new dominant speaker event: ",
  354. dominantSpeakerEndpoint);
  355. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  356. }
  357. else if ("InLastNChangeEvent" === colibriClass)
  358. {
  359. var oldValue = obj.oldValue;
  360. var newValue = obj.newValue;
  361. // Make sure that oldValue and newValue are of type boolean.
  362. var type;
  363. if ((type = typeof oldValue) !== 'boolean') {
  364. if (type === 'string') {
  365. oldValue = (oldValue == "true");
  366. } else {
  367. oldValue = new Boolean(oldValue).valueOf();
  368. }
  369. }
  370. if ((type = typeof newValue) !== 'boolean') {
  371. if (type === 'string') {
  372. newValue = (newValue == "true");
  373. } else {
  374. newValue = new Boolean(newValue).valueOf();
  375. }
  376. }
  377. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  378. }
  379. else if ("LastNEndpointsChangeEvent" === colibriClass)
  380. {
  381. // The new/latest list of last-n endpoint IDs.
  382. var lastNEndpoints = obj.lastNEndpoints;
  383. // The list of endpoint IDs which are entering the list of
  384. // last-n at this time i.e. were not in the old list of last-n
  385. // endpoint IDs.
  386. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  387. var stream = obj.stream;
  388. console.log(
  389. "Data channel new last-n event: ",
  390. lastNEndpoints, endpointsEnteringLastN, obj);
  391. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  392. lastNEndpoints, endpointsEnteringLastN, obj);
  393. }
  394. else
  395. {
  396. console.debug("Data channel JSON-formatted message: ", obj);
  397. }
  398. }
  399. };
  400. dataChannel.onclose = function ()
  401. {
  402. console.info("The Data Channel closed", dataChannel);
  403. var idx = _dataChannels.indexOf(dataChannel);
  404. if (idx > -1)
  405. _dataChannels = _dataChannels.splice(idx, 1);
  406. };
  407. _dataChannels.push(dataChannel);
  408. },
  409. /**
  410. * Binds "ondatachannel" event listener to given PeerConnection instance.
  411. * @param peerConnection WebRTC peer connection instance.
  412. */
  413. init: function (peerConnection, emitter) {
  414. if(!config.openSctp)
  415. return;
  416. peerConnection.ondatachannel = this.onDataChannel;
  417. eventEmitter = emitter;
  418. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  419. // Although it's not a requirement to open separate channels from both bridge
  420. // and peer as single channel can be used for sending and receiving data.
  421. // So either channel opened by the bridge or the one opened here is enough
  422. // for communication with the bridge.
  423. /*var dataChannelOptions =
  424. {
  425. reliable: true
  426. };
  427. var dataChannel
  428. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  429. // Can be used only when is in open state
  430. dataChannel.onopen = function ()
  431. {
  432. dataChannel.send("My channel !!!");
  433. };
  434. dataChannel.onmessage = function (event)
  435. {
  436. var msgData = event.data;
  437. console.info("Got My Data Channel Message:", msgData, dataChannel);
  438. };*/
  439. },
  440. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  441. handlePinnedEndpointEvent: onPinnedEndpointChanged
  442. };
  443. function onSelectedEndpointChanged(userResource)
  444. {
  445. console.log('selected endpoint changed: ', userResource);
  446. if (_dataChannels && _dataChannels.length != 0)
  447. {
  448. _dataChannels.some(function (dataChannel) {
  449. if (dataChannel.readyState == 'open')
  450. {
  451. console.log('sending selected endpoint changed '
  452. + 'notification to the bridge: ', userResource);
  453. dataChannel.send(JSON.stringify({
  454. 'colibriClass': 'SelectedEndpointChangedEvent',
  455. 'selectedEndpoint':
  456. (!userResource || userResource === null)?
  457. null : userResource
  458. }));
  459. return true;
  460. }
  461. });
  462. }
  463. }
  464. function onPinnedEndpointChanged(userResource)
  465. {
  466. console.log('pinned endpoint changed: ', userResource);
  467. if (_dataChannels && _dataChannels.length != 0)
  468. {
  469. _dataChannels.some(function (dataChannel) {
  470. if (dataChannel.readyState == 'open')
  471. {
  472. dataChannel.send(JSON.stringify({
  473. 'colibriClass': 'PinnedEndpointChangedEvent',
  474. 'pinnedEndpoint':
  475. (!userResource || userResource == null)?
  476. null : userResource
  477. }));
  478. return true;
  479. }
  480. });
  481. }
  482. }
  483. module.exports = DataChannels;
  484. },{"../../service/RTC/RTCEvents":103}],5:[function(require,module,exports){
  485. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  486. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  487. {
  488. this.stream = stream;
  489. this.eventEmitter = eventEmitter;
  490. this.type = type;
  491. this.videoType = videoType;
  492. this.isGUMStream = true;
  493. if(isGUMStream === false)
  494. this.isGUMStream = isGUMStream;
  495. var self = this;
  496. if(type == "audio")
  497. {
  498. this.getTracks = function () {
  499. return self.stream.getAudioTracks();
  500. };
  501. }
  502. else
  503. {
  504. this.getTracks = function () {
  505. return self.stream.getVideoTracks();
  506. };
  507. }
  508. this.stream.onended = function()
  509. {
  510. self.streamEnded();
  511. };
  512. }
  513. LocalStream.prototype.streamEnded = function () {
  514. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  515. }
  516. LocalStream.prototype.getOriginalStream = function()
  517. {
  518. return this.stream;
  519. }
  520. LocalStream.prototype.isAudioStream = function () {
  521. return this.type === "audio";
  522. };
  523. LocalStream.prototype.setMute = function(mute)
  524. {
  525. if((window.location.protocol != "https:" && this.isGUMStream) ||
  526. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  527. {
  528. var tracks = this.getTracks();
  529. for (var idx = 0; idx < tracks.length; idx++) {
  530. tracks[idx].enabled = mute;
  531. }
  532. }
  533. else
  534. {
  535. if(mute === false) {
  536. APP.xmpp.removeStream(this.stream);
  537. this.stream.stop();
  538. }
  539. else
  540. {
  541. var self = this;
  542. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  543. (this.isAudioStream() ? ["audio"] : ["video"]),
  544. function (stream) {
  545. if(self.isAudioStream())
  546. {
  547. APP.RTC.changeLocalAudio(stream, function () {});
  548. }
  549. else
  550. {
  551. APP.RTC.changeLocalVideo(stream, false, function () {});
  552. }
  553. });
  554. }
  555. }
  556. };
  557. LocalStream.prototype.isMuted = function () {
  558. var tracks = [];
  559. if(this.type == "audio")
  560. {
  561. tracks = this.stream.getAudioTracks();
  562. }
  563. else
  564. {
  565. if(this.stream.ended)
  566. return true;
  567. tracks = this.stream.getVideoTracks();
  568. }
  569. for (var idx = 0; idx < tracks.length; idx++) {
  570. if(tracks[idx].enabled)
  571. return false;
  572. }
  573. return true;
  574. }
  575. LocalStream.prototype.getId = function () {
  576. return this.stream.getTracks()[0].id;
  577. }
  578. module.exports = LocalStream;
  579. },{"../../service/RTC/StreamEventTypes.js":105}],6:[function(require,module,exports){
  580. ////These lines should be uncommented when require works in app.js
  581. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  582. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  583. /**
  584. * Creates a MediaStream object for the given data, session id and ssrc.
  585. * It is a wrapper class for the MediaStream.
  586. *
  587. * @param data the data object from which we obtain the stream,
  588. * the peerjid, etc.
  589. * @param sid the session id
  590. * @param ssrc the ssrc corresponding to this MediaStream
  591. *
  592. * @constructor
  593. */
  594. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  595. // XXX(gp) to minimize headaches in the future, we should build our
  596. // abstractions around tracks and not streams. ORTC is track based API.
  597. // Mozilla expects m-lines to represent media tracks.
  598. //
  599. // Practically, what I'm saying is that we should have a MediaTrack class
  600. // and not a MediaStream class.
  601. //
  602. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  603. // a track might have an associated RTX and FEC sources.
  604. this.sid = sid;
  605. this.stream = data.stream;
  606. this.peerjid = data.peerjid;
  607. this.ssrc = ssrc;
  608. this.type = (this.stream.getVideoTracks().length > 0)?
  609. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  610. this.videoType = null;
  611. this.muted = false;
  612. this.eventEmitter = eventEmitter;
  613. }
  614. MediaStream.prototype.getOriginalStream = function()
  615. {
  616. return this.stream;
  617. };
  618. MediaStream.prototype.setMute = function (value)
  619. {
  620. this.stream.muted = value;
  621. this.muted = value;
  622. };
  623. MediaStream.prototype.setVideoType = function (value) {
  624. if(this.videoType === value)
  625. return;
  626. this.videoType = value;
  627. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  628. this.peerjid);
  629. };
  630. module.exports = MediaStream;
  631. },{"../../service/RTC/MediaStreamTypes":101,"../../service/RTC/StreamEventTypes":105}],7:[function(require,module,exports){
  632. var EventEmitter = require("events");
  633. var RTCUtils = require("./RTCUtils.js");
  634. var LocalStream = require("./LocalStream.js");
  635. var DataChannels = require("./DataChannels");
  636. var MediaStream = require("./MediaStream.js");
  637. var DesktopSharingEventTypes
  638. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  639. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  640. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  641. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  642. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  643. var UIEvents = require("../../service/UI/UIEvents");
  644. var eventEmitter = new EventEmitter();
  645. function getMediaStreamUsage()
  646. {
  647. var result = {
  648. audio: true,
  649. video: true
  650. };
  651. /** There are some issues with the desktop sharing
  652. * when this property is enabled.
  653. * WARNING: We must change the implementation to start video/audio if we
  654. * receive from the focus that the peer is not muted.
  655. var isSecureConnection = window.location.protocol == "https:";
  656. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  657. {
  658. result = {
  659. audio: false,
  660. video: false
  661. };
  662. }
  663. **/
  664. return result;
  665. }
  666. var RTC = {
  667. rtcUtils: null,
  668. devices: {
  669. audio: true,
  670. video: true
  671. },
  672. localStreams: [],
  673. remoteStreams: {},
  674. localAudio: null,
  675. localVideo: null,
  676. addStreamListener: function (listener, eventType) {
  677. eventEmitter.on(eventType, listener);
  678. },
  679. addListener: function (type, listener) {
  680. eventEmitter.on(type, listener);
  681. },
  682. removeStreamListener: function (listener, eventType) {
  683. if(!(eventType instanceof StreamEventTypes))
  684. throw "Illegal argument";
  685. eventEmitter.removeListener(eventType, listener);
  686. },
  687. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  688. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  689. //in firefox we have only one stream object
  690. if(this.localStreams.length == 0 ||
  691. this.localStreams[0].getOriginalStream() != stream)
  692. this.localStreams.push(localStream);
  693. if(isMuted === true)
  694. localStream.setMute(false);
  695. if(type == "audio")
  696. {
  697. this.localAudio = localStream;
  698. }
  699. else
  700. {
  701. this.localVideo = localStream;
  702. }
  703. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  704. if(change)
  705. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  706. eventEmitter.emit(eventType, localStream, isMuted);
  707. return localStream;
  708. },
  709. removeLocalStream: function (stream) {
  710. for(var i = 0; i < this.localStreams.length; i++)
  711. {
  712. if(this.localStreams[i].getOriginalStream() === stream) {
  713. delete this.localStreams[i];
  714. return;
  715. }
  716. }
  717. },
  718. createRemoteStream: function (data, sid, thessrc) {
  719. var remoteStream = new MediaStream(data, sid, thessrc,
  720. this.getBrowserType(), eventEmitter);
  721. var jid = data.peerjid || APP.xmpp.myJid();
  722. if(!this.remoteStreams[jid]) {
  723. this.remoteStreams[jid] = {};
  724. }
  725. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  726. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  727. return remoteStream;
  728. },
  729. getBrowserType: function () {
  730. return this.rtcUtils.browser;
  731. },
  732. getPCConstraints: function () {
  733. return this.rtcUtils.pc_constraints;
  734. },
  735. getUserMediaWithConstraints:function(um, success_callback,
  736. failure_callback, resolution,
  737. bandwidth, fps, desktopStream)
  738. {
  739. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  740. failure_callback, resolution, bandwidth, fps, desktopStream);
  741. },
  742. attachMediaStream: function (element, stream) {
  743. this.rtcUtils.attachMediaStream(element, stream);
  744. },
  745. getStreamID: function (stream) {
  746. return this.rtcUtils.getStreamID(stream);
  747. },
  748. getVideoSrc: function (element) {
  749. return this.rtcUtils.getVideoSrc(element);
  750. },
  751. setVideoSrc: function (element, src) {
  752. this.rtcUtils.setVideoSrc(element, src);
  753. },
  754. dispose: function() {
  755. if (this.rtcUtils) {
  756. this.rtcUtils = null;
  757. }
  758. },
  759. stop: function () {
  760. this.dispose();
  761. },
  762. start: function () {
  763. var self = this;
  764. APP.desktopsharing.addListener(
  765. function (stream, isUsingScreenStream, callback) {
  766. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  767. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  768. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  769. for(var i = 0; i < changedStreams.length; i++) {
  770. var type = changedStreams[i].type;
  771. if (type != "audio") {
  772. var peerStreams = self.remoteStreams[jid];
  773. if(!peerStreams)
  774. continue;
  775. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  776. if(!videoStream)
  777. continue;
  778. videoStream.setVideoType(changedStreams[i].type);
  779. }
  780. }
  781. });
  782. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  783. DataChannels.init(event.peerconnection, eventEmitter);
  784. });
  785. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  786. DataChannels.handleSelectedEndpointEvent);
  787. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  788. DataChannels.handlePinnedEndpointEvent);
  789. this.rtcUtils = new RTCUtils(this);
  790. this.rtcUtils.obtainAudioAndVideoPermissions(
  791. null, null, getMediaStreamUsage());
  792. },
  793. muteRemoteVideoStream: function (jid, value) {
  794. var stream;
  795. if(this.remoteStreams[jid] &&
  796. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  797. {
  798. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  799. }
  800. if(!stream)
  801. return true;
  802. if (value != stream.muted) {
  803. stream.setMute(value);
  804. return true;
  805. }
  806. return false;
  807. },
  808. switchVideoStreams: function (new_stream) {
  809. this.localVideo.stream = new_stream;
  810. this.localStreams = [];
  811. //in firefox we have only one stream object
  812. if (this.localAudio.getOriginalStream() != new_stream)
  813. this.localStreams.push(this.localAudio);
  814. this.localStreams.push(this.localVideo);
  815. },
  816. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  817. var oldStream = this.localVideo.getOriginalStream();
  818. var type = (isUsingScreenStream? "screen" : "video");
  819. var localCallback = callback;
  820. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  821. {
  822. localCallback = function() {
  823. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  824. callback();
  825. };
  826. }
  827. var videoStream = this.rtcUtils.createStream(stream, true);
  828. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  829. // Stop the stream to trigger onended event for old stream
  830. oldStream.stop();
  831. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  832. },
  833. changeLocalAudio: function (stream, callback) {
  834. var oldStream = this.localAudio.getOriginalStream();
  835. var newStream = this.rtcUtils.createStream(stream);
  836. this.localAudio = this.createLocalStream(newStream, "audio", true);
  837. // Stop the stream to trigger onended event for old stream
  838. oldStream.stop();
  839. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  840. },
  841. /**
  842. * Checks if video identified by given src is desktop stream.
  843. * @param videoSrc eg.
  844. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  845. * @returns {boolean}
  846. */
  847. isVideoSrcDesktop: function (jid) {
  848. if(!jid)
  849. return false;
  850. var isDesktop = false;
  851. var stream = null;
  852. if (APP.xmpp.myJid() === jid) {
  853. // local video
  854. stream = this.localVideo;
  855. } else {
  856. var peerStreams = this.remoteStreams[jid];
  857. if(!peerStreams)
  858. return false;
  859. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  860. }
  861. if(stream)
  862. isDesktop = (stream.videoType === "screen");
  863. return isDesktop;
  864. },
  865. setVideoMute: function(mute, callback, options) {
  866. if(!this.localVideo)
  867. return;
  868. if (mute == APP.RTC.localVideo.isMuted())
  869. {
  870. APP.xmpp.sendVideoInfoPresence(mute);
  871. if(callback)
  872. callback(mute);
  873. }
  874. else
  875. {
  876. APP.RTC.localVideo.setMute(!mute);
  877. APP.xmpp.setVideoMute(
  878. mute,
  879. callback,
  880. options);
  881. }
  882. },
  883. setDeviceAvailability: function (devices) {
  884. if(!devices)
  885. return;
  886. if(devices.audio === true || devices.audio === false)
  887. this.devices.audio = devices.audio;
  888. if(devices.video === true || devices.video === false)
  889. this.devices.video = devices.video;
  890. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  891. }
  892. };
  893. module.exports = RTC;
  894. },{"../../service/RTC/MediaStreamTypes":101,"../../service/RTC/RTCEvents.js":103,"../../service/RTC/StreamEventTypes.js":105,"../../service/UI/UIEvents":106,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../../service/xmpp/XMPPEvents":112,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCUtils.js":8,"events":62}],8:[function(require,module,exports){
  895. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  896. var Resolutions = require("../../service/RTC/Resolutions");
  897. var currentResolution = null;
  898. function getPreviousResolution(resolution) {
  899. if(!Resolutions[resolution])
  900. return null;
  901. var order = Resolutions[resolution].order;
  902. var res = null;
  903. var resName = null;
  904. for(var i in Resolutions)
  905. {
  906. var tmp = Resolutions[i];
  907. if(res == null || (res.order < tmp.order && tmp.order < order))
  908. {
  909. resName = i;
  910. res = tmp;
  911. }
  912. }
  913. return resName;
  914. }
  915. function setResolutionConstraints(constraints, resolution, isAndroid)
  916. {
  917. if (resolution && !constraints.video || isAndroid) {
  918. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  919. }
  920. if(Resolutions[resolution])
  921. {
  922. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  923. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  924. }
  925. else
  926. {
  927. if (isAndroid) {
  928. constraints.video.mandatory.minWidth = 320;
  929. constraints.video.mandatory.minHeight = 240;
  930. constraints.video.mandatory.maxFrameRate = 15;
  931. }
  932. }
  933. if (constraints.video.mandatory.minWidth)
  934. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  935. if (constraints.video.mandatory.minHeight)
  936. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  937. }
  938. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  939. {
  940. var constraints = {audio: false, video: false};
  941. if (um.indexOf('video') >= 0) {
  942. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  943. }
  944. if (um.indexOf('audio') >= 0) {
  945. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  946. }
  947. if (um.indexOf('screen') >= 0) {
  948. constraints.video = {
  949. mandatory: {
  950. chromeMediaSource: "screen",
  951. googLeakyBucket: true,
  952. maxWidth: window.screen.width,
  953. maxHeight: window.screen.height,
  954. maxFrameRate: 3
  955. },
  956. optional: []
  957. };
  958. }
  959. if (um.indexOf('desktop') >= 0) {
  960. constraints.video = {
  961. mandatory: {
  962. chromeMediaSource: "desktop",
  963. chromeMediaSourceId: desktopStream,
  964. googLeakyBucket: true,
  965. maxWidth: window.screen.width,
  966. maxHeight: window.screen.height,
  967. maxFrameRate: 3
  968. },
  969. optional: []
  970. };
  971. }
  972. if (constraints.audio) {
  973. // if it is good enough for hangouts...
  974. constraints.audio.optional.push(
  975. {googEchoCancellation: true},
  976. {googAutoGainControl: true},
  977. {googNoiseSupression: true},
  978. {googHighpassFilter: true},
  979. {googNoisesuppression2: true},
  980. {googEchoCancellation2: true},
  981. {googAutoGainControl2: true}
  982. );
  983. }
  984. if (constraints.video) {
  985. constraints.video.optional.push(
  986. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  987. );
  988. if (um.indexOf('video') >= 0) {
  989. constraints.video.optional.push(
  990. {googLeakyBucket: true}
  991. );
  992. }
  993. }
  994. if (um.indexOf('video') >= 0) {
  995. setResolutionConstraints(constraints, resolution, isAndroid);
  996. }
  997. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  998. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  999. constraints.video.optional.push({bandwidth: bandwidth});
  1000. }
  1001. if (fps) { // for some cameras it might be necessary to request 30fps
  1002. // so they choose 30fps mjpg over 10fps yuy2
  1003. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1004. constraints.video.mandatory.minFrameRate = fps;
  1005. }
  1006. return constraints;
  1007. }
  1008. function RTCUtils(RTCService)
  1009. {
  1010. this.service = RTCService;
  1011. if (navigator.mozGetUserMedia) {
  1012. console.log('This appears to be Firefox');
  1013. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1014. if (version >= 40
  1015. && config.useBundle && config.useRtcpMux) {
  1016. this.peerconnection = mozRTCPeerConnection;
  1017. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1018. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1019. this.pc_constraints = {};
  1020. this.attachMediaStream = function (element, stream) {
  1021. // srcObject is being standardized and FF will eventually
  1022. // support that unprefixed. FF also supports the
  1023. // "element.src = URL.createObjectURL(...)" combo, but that
  1024. // will be deprecated in favour of srcObject.
  1025. //
  1026. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1027. // https://github.com/webrtc/samples/issues/302
  1028. if(!element[0])
  1029. return;
  1030. element[0].mozSrcObject = stream;
  1031. element[0].play();
  1032. };
  1033. this.getStreamID = function (stream) {
  1034. var tracks = stream.getVideoTracks();
  1035. if(!tracks || tracks.length == 0)
  1036. {
  1037. tracks = stream.getAudioTracks();
  1038. }
  1039. return tracks[0].id.replace(/[\{,\}]/g,"");
  1040. };
  1041. this.getVideoSrc = function (element) {
  1042. if(!element)
  1043. return null;
  1044. return element.mozSrcObject;
  1045. };
  1046. this.setVideoSrc = function (element, src) {
  1047. if(element)
  1048. element.mozSrcObject = src;
  1049. };
  1050. RTCSessionDescription = mozRTCSessionDescription;
  1051. RTCIceCandidate = mozRTCIceCandidate;
  1052. } else {
  1053. window.location.href = 'unsupported_browser.html';
  1054. return;
  1055. }
  1056. } else if (navigator.webkitGetUserMedia) {
  1057. console.log('This appears to be Chrome');
  1058. this.peerconnection = webkitRTCPeerConnection;
  1059. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1060. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1061. this.attachMediaStream = function (element, stream) {
  1062. element.attr('src', webkitURL.createObjectURL(stream));
  1063. };
  1064. this.getStreamID = function (stream) {
  1065. // streams from FF endpoints have the characters '{' and '}'
  1066. // that make jQuery choke.
  1067. return stream.id.replace(/[\{,\}]/g,"");
  1068. };
  1069. this.getVideoSrc = function (element) {
  1070. if(!element)
  1071. return null;
  1072. return element.getAttribute("src");
  1073. };
  1074. this.setVideoSrc = function (element, src) {
  1075. if(element)
  1076. element.setAttribute("src", src);
  1077. };
  1078. // DTLS should now be enabled by default but..
  1079. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1080. if (navigator.userAgent.indexOf('Android') != -1) {
  1081. this.pc_constraints = {}; // disable DTLS on Android
  1082. }
  1083. if (!webkitMediaStream.prototype.getVideoTracks) {
  1084. webkitMediaStream.prototype.getVideoTracks = function () {
  1085. return this.videoTracks;
  1086. };
  1087. }
  1088. if (!webkitMediaStream.prototype.getAudioTracks) {
  1089. webkitMediaStream.prototype.getAudioTracks = function () {
  1090. return this.audioTracks;
  1091. };
  1092. }
  1093. }
  1094. else
  1095. {
  1096. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1097. window.location.href = 'unsupported_browser.html';
  1098. return;
  1099. }
  1100. }
  1101. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1102. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1103. desktopStream)
  1104. {
  1105. currentResolution = resolution;
  1106. // Check if we are running on Android device
  1107. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1108. var constraints = getConstraints(
  1109. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1110. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1111. var self = this;
  1112. try {
  1113. this.getUserMedia(constraints,
  1114. function (stream) {
  1115. console.log('onUserMediaSuccess');
  1116. self.setAvailableDevices(um, true);
  1117. success_callback(stream);
  1118. },
  1119. function (error) {
  1120. self.setAvailableDevices(um, false);
  1121. console.warn('Failed to get access to local media. Error ',
  1122. error, constraints);
  1123. if (failure_callback) {
  1124. failure_callback(error);
  1125. }
  1126. });
  1127. } catch (e) {
  1128. console.error('GUM failed: ', e);
  1129. if(failure_callback) {
  1130. failure_callback(e);
  1131. }
  1132. }
  1133. };
  1134. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1135. var devices = {};
  1136. if(um.indexOf("video") != -1)
  1137. {
  1138. devices.video = available;
  1139. }
  1140. if(um.indexOf("audio") != -1)
  1141. {
  1142. devices.audio = available;
  1143. }
  1144. this.service.setDeviceAvailability(devices);
  1145. }
  1146. /**
  1147. * We ask for audio and video combined stream in order to get permissions and
  1148. * not to ask twice.
  1149. */
  1150. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1151. function(devices, callback, usageOptions)
  1152. {
  1153. var self = this;
  1154. // Get AV
  1155. var successCallback = function (stream) {
  1156. if(callback)
  1157. callback(stream, usageOptions);
  1158. else
  1159. self.successCallback(stream, usageOptions);
  1160. };
  1161. if(!devices)
  1162. devices = ['audio', 'video'];
  1163. var newDevices = [];
  1164. if(usageOptions)
  1165. for(var i = 0; i < devices.length; i++)
  1166. {
  1167. var device = devices[i];
  1168. if(usageOptions[device] === true)
  1169. newDevices.push(device);
  1170. }
  1171. else
  1172. newDevices = devices;
  1173. if(newDevices.length === 0)
  1174. {
  1175. successCallback();
  1176. return;
  1177. }
  1178. if (navigator.mozGetUserMedia) {
  1179. // With FF we can't split the stream into audio and video because FF
  1180. // doesn't support media stream constructors. So, we need to get the
  1181. // audio stream separately from the video stream using two distinct GUM
  1182. // calls. Not very user friendly :-( but we don't have many other
  1183. // options neither.
  1184. //
  1185. // Note that we pack those 2 streams in a single object and pass it to
  1186. // the successCallback method.
  1187. self.getUserMediaWithConstraints(
  1188. ['audio'],
  1189. function (audioStream) {
  1190. self.getUserMediaWithConstraints(
  1191. ['video'],
  1192. function (videoStream) {
  1193. return self.successCallback({
  1194. audioStream: audioStream,
  1195. videoStream: videoStream
  1196. });
  1197. },
  1198. function (error) {
  1199. console.error('failed to obtain video stream - stop',
  1200. error);
  1201. return self.successCallback(null);
  1202. },
  1203. config.resolution || '360');
  1204. },
  1205. function (error) {
  1206. console.error('failed to obtain audio stream - stop',
  1207. error);
  1208. return self.successCallback(null);
  1209. }
  1210. );
  1211. } else {
  1212. this.getUserMediaWithConstraints(
  1213. newDevices,
  1214. function (stream) {
  1215. successCallback(stream);
  1216. },
  1217. function (error) {
  1218. self.errorCallback(error);
  1219. },
  1220. config.resolution || '360');
  1221. }
  1222. }
  1223. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1224. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1225. // an object with two properties: audioStream, videoStream.
  1226. if(stream && !navigator.mozGetUserMedia)
  1227. console.log('got', stream, stream.getAudioTracks().length,
  1228. stream.getVideoTracks().length);
  1229. this.handleLocalStream(stream, usageOptions);
  1230. };
  1231. RTCUtils.prototype.errorCallback = function (error) {
  1232. var self = this;
  1233. console.error('failed to obtain audio/video stream - trying audio only', error);
  1234. var resolution = getPreviousResolution(currentResolution);
  1235. if(typeof error == "object" && error.constraintName && error.name
  1236. && (error.name == "ConstraintNotSatisfiedError" ||
  1237. error.name == "OverconstrainedError") &&
  1238. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1239. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1240. && resolution != null)
  1241. {
  1242. self.getUserMediaWithConstraints(['audio', 'video'],
  1243. function (stream) {
  1244. return self.successCallback(stream);
  1245. }, function (error) {
  1246. return self.errorCallback(error);
  1247. }, resolution);
  1248. }
  1249. else
  1250. {
  1251. self.getUserMediaWithConstraints(
  1252. ['audio'],
  1253. function (stream) {
  1254. return self.successCallback(stream);
  1255. },
  1256. function (error) {
  1257. console.error('failed to obtain audio/video stream - stop',
  1258. error);
  1259. return self.successCallback(null);
  1260. }
  1261. );
  1262. }
  1263. }
  1264. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1265. {
  1266. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1267. // an object with two properties: audioStream, videoStream.
  1268. var audioStream, videoStream;
  1269. if(window.webkitMediaStream)
  1270. {
  1271. audioStream = new webkitMediaStream();
  1272. videoStream = new webkitMediaStream();
  1273. if(stream) {
  1274. var audioTracks = stream.getAudioTracks();
  1275. for (var i = 0; i < audioTracks.length; i++) {
  1276. audioStream.addTrack(audioTracks[i]);
  1277. }
  1278. var videoTracks = stream.getVideoTracks();
  1279. for (i = 0; i < videoTracks.length; i++) {
  1280. videoStream.addTrack(videoTracks[i]);
  1281. }
  1282. }
  1283. }
  1284. else
  1285. {//firefox
  1286. audioStream = stream.audioStream;
  1287. videoStream = stream.videoStream;
  1288. }
  1289. var audioMuted = (usageOptions && usageOptions.audio === false),
  1290. videoMuted = (usageOptions && usageOptions.video === false);
  1291. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1292. videoGUM = (!usageOptions || usageOptions.video !== false);
  1293. this.service.createLocalStream(audioStream, "audio", null, null,
  1294. audioMuted, audioGUM);
  1295. this.service.createLocalStream(videoStream, "video", null, null,
  1296. videoMuted, videoGUM);
  1297. };
  1298. RTCUtils.prototype.createStream = function(stream, isVideo)
  1299. {
  1300. var newStream = null;
  1301. if(window.webkitMediaStream)
  1302. {
  1303. newStream = new webkitMediaStream();
  1304. if(newStream)
  1305. {
  1306. var tracks = (isVideo? stream.getVideoTracks() : stream.getAudioTracks());
  1307. for (i = 0; i < tracks.length; i++) {
  1308. newStream.addTrack(tracks[i]);
  1309. }
  1310. }
  1311. }
  1312. else
  1313. newStream = stream;
  1314. return newStream;
  1315. };
  1316. module.exports = RTCUtils;
  1317. },{"../../service/RTC/RTCBrowserType.js":102,"../../service/RTC/Resolutions":104}],9:[function(require,module,exports){
  1318. var UI = {};
  1319. var VideoLayout = require("./videolayout/VideoLayout.js");
  1320. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1321. var Prezi = require("./prezi/Prezi.js");
  1322. var Etherpad = require("./etherpad/Etherpad.js");
  1323. var Chat = require("./side_pannels/chat/Chat.js");
  1324. var Toolbar = require("./toolbars/Toolbar");
  1325. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1326. var BottomToolbar = require("./toolbars/BottomToolbar");
  1327. var ContactList = require("./side_pannels/contactlist/ContactList");
  1328. var Avatar = require("./avatar/Avatar");
  1329. var EventEmitter = require("events");
  1330. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1331. var Settings = require("./../settings/Settings");
  1332. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1333. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1334. UI.messageHandler = require("./util/MessageHandler");
  1335. var messageHandler = UI.messageHandler;
  1336. var Authentication = require("./authentication/Authentication");
  1337. var UIUtil = require("./util/UIUtil");
  1338. var NicknameHandler = require("./util/NicknameHandler");
  1339. var CQEvents = require("../../service/connectionquality/CQEvents");
  1340. var DesktopSharingEventTypes
  1341. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1342. var RTCEvents = require("../../service/RTC/RTCEvents");
  1343. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1344. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1345. var MemberEvents = require("../../service/members/Events");
  1346. var eventEmitter = new EventEmitter();
  1347. var roomName = null;
  1348. function notifyForInitialMute()
  1349. {
  1350. messageHandler.notify(null, "notify.mutedTitle", "connected",
  1351. "notify.muted", null, {timeOut: 120000});
  1352. }
  1353. function setupPrezi()
  1354. {
  1355. $("#reloadPresentationLink").click(function()
  1356. {
  1357. Prezi.reloadPresentation();
  1358. });
  1359. }
  1360. function setupChat()
  1361. {
  1362. Chat.init();
  1363. $("#toggle_smileys").click(function() {
  1364. Chat.toggleSmileys();
  1365. });
  1366. }
  1367. function setupToolbars() {
  1368. Toolbar.init(UI);
  1369. Toolbar.setupButtonsFromConfig();
  1370. BottomToolbar.init();
  1371. }
  1372. function streamHandler(stream, isMuted) {
  1373. switch (stream.type)
  1374. {
  1375. case "audio":
  1376. VideoLayout.changeLocalAudio(stream, isMuted);
  1377. break;
  1378. case "video":
  1379. VideoLayout.changeLocalVideo(stream, isMuted);
  1380. break;
  1381. case "stream":
  1382. VideoLayout.changeLocalStream(stream, isMuted);
  1383. break;
  1384. }
  1385. }
  1386. function onXmppConnectionFailed(stropheErrorMsg) {
  1387. var title = APP.translation.generateTranslatonHTML(
  1388. "dialog.error");
  1389. var message;
  1390. if (stropheErrorMsg) {
  1391. message = APP.translation.generateTranslatonHTML(
  1392. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  1393. } else {
  1394. message = APP.translation.generateTranslatonHTML(
  1395. "dialog.connectError");
  1396. }
  1397. messageHandler.openDialog(
  1398. title, message, true, {}, function (e, v, m, f) { return false; });
  1399. }
  1400. function onDisposeConference(unload) {
  1401. Toolbar.showAuthenticateButton(false);
  1402. }
  1403. function onDisplayNameChanged(jid, displayName) {
  1404. ContactList.onDisplayNameChange(jid, displayName);
  1405. SettingsMenu.onDisplayNameChange(jid, displayName);
  1406. VideoLayout.onDisplayNameChanged(jid, displayName);
  1407. }
  1408. function registerListeners() {
  1409. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1410. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1411. APP.RTC.addStreamListener(function (stream) {
  1412. VideoLayout.onRemoteStreamAdded(stream);
  1413. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1414. APP.RTC.addStreamListener(function (jid) {
  1415. VideoLayout.onVideoTypeChanged(jid);
  1416. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1417. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1418. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1419. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1420. });
  1421. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1422. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1423. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1424. endpointsEnteringLastN, stream);
  1425. });
  1426. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1427. function (devices) {
  1428. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1429. })
  1430. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1431. {
  1432. var resourceJid;
  1433. if(jid === APP.statistics.LOCAL_JID)
  1434. {
  1435. resourceJid = AudioLevels.LOCAL_LEVEL;
  1436. if(APP.RTC.localAudio.isMuted())
  1437. {
  1438. audioLevel = 0;
  1439. }
  1440. }
  1441. else
  1442. {
  1443. resourceJid = Strophe.getResourceFromJid(jid);
  1444. }
  1445. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1446. UI.getLargeVideoState().userResourceJid);
  1447. });
  1448. APP.desktopsharing.addListener(function () {
  1449. ToolbarToggler.showDesktopSharingButton();
  1450. }, DesktopSharingEventTypes.INIT);
  1451. APP.desktopsharing.addListener(
  1452. Toolbar.changeDesktopSharingButtonState,
  1453. DesktopSharingEventTypes.SWITCHING_DONE);
  1454. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1455. VideoLayout.updateLocalConnectionStats);
  1456. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1457. VideoLayout.updateConnectionStats);
  1458. APP.connectionquality.addListener(CQEvents.STOP,
  1459. VideoLayout.onStatsStop);
  1460. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  1461. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1462. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1463. messageHandler.openMessageDialog(
  1464. 'dialog.serviceUnavailable',
  1465. 'dialog.gracefulShutdown'
  1466. );
  1467. });
  1468. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1469. var title = APP.translation.generateTranslatonHTML(
  1470. "dialog.reservationError");
  1471. var message = APP.translation.generateTranslatonHTML(
  1472. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1473. messageHandler.openDialog(
  1474. title,
  1475. message,
  1476. true, {},
  1477. function (event, value, message, formVals)
  1478. {
  1479. return false;
  1480. }
  1481. );
  1482. });
  1483. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1484. messageHandler.openMessageDialog("dialog.sessTerminated",
  1485. "dialog.kickMessage");
  1486. });
  1487. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1488. //FIXME: use Session Terminated from translation, but
  1489. // 'reason' text comes from XMPP packet and is not translated
  1490. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1491. messageHandler.openDialog(
  1492. title, reason, true, {},
  1493. function (event, value, message, formVals)
  1494. {
  1495. return false;
  1496. }
  1497. );
  1498. });
  1499. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1500. messageHandler.showError("dialog.error",
  1501. "dialog.bridgeUnavailable");
  1502. });
  1503. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1504. Avatar.setUserAvatar(from, id);
  1505. });
  1506. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  1507. for(stream in changedStreams)
  1508. {
  1509. // might need to update the direction if participant just went from sendrecv to recvonly
  1510. if (stream.type === 'video' || stream.type === 'screen') {
  1511. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1512. switch (stream.direction) {
  1513. case 'sendrecv':
  1514. el.show();
  1515. break;
  1516. case 'recvonly':
  1517. el.hide();
  1518. // FIXME: Check if we have to change large video
  1519. //VideoLayout.updateLargeVideo(el);
  1520. break;
  1521. }
  1522. }
  1523. }
  1524. });
  1525. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1526. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1527. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  1528. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  1529. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1530. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1531. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1532. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1533. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  1534. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  1535. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1536. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1537. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1538. onAuthenticationRequired);
  1539. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1540. function (resource, devices) {
  1541. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1542. });
  1543. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  1544. onDtmfSupportChanged);
  1545. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  1546. SettingsMenu.setStartMuted(audio, video);
  1547. });
  1548. }
  1549. /**
  1550. * Mutes/unmutes the local video.
  1551. *
  1552. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1553. * @param options an object which specifies optional arguments such as the
  1554. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1555. * specifies whether the method was initiated in response to a user command (in
  1556. * contrast to an automatic decision taken by the application logic)
  1557. */
  1558. function setVideoMute(mute, options) {
  1559. APP.RTC.setVideoMute(mute,
  1560. UI.setVideoMuteButtonsState,
  1561. options);
  1562. }
  1563. function bindEvents()
  1564. {
  1565. /**
  1566. * Resizes and repositions videos in full screen mode.
  1567. */
  1568. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1569. function () {
  1570. VideoLayout.resizeLargeVideoContainer();
  1571. VideoLayout.positionLarge();
  1572. }
  1573. );
  1574. $(window).resize(function () {
  1575. VideoLayout.resizeLargeVideoContainer();
  1576. VideoLayout.positionLarge();
  1577. });
  1578. }
  1579. UI.start = function (init) {
  1580. document.title = interfaceConfig.APP_NAME;
  1581. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1582. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1583. {
  1584. $("#videoconference_page").hide();
  1585. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1586. setupWelcomePage();
  1587. return;
  1588. }
  1589. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1590. var leftWatermarkDiv
  1591. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1592. leftWatermarkDiv.css({display: 'block'});
  1593. leftWatermarkDiv.parent().get(0).href
  1594. = interfaceConfig.JITSI_WATERMARK_LINK;
  1595. }
  1596. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1597. var rightWatermarkDiv
  1598. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1599. rightWatermarkDiv.css({display: 'block'});
  1600. rightWatermarkDiv.parent().get(0).href
  1601. = interfaceConfig.BRAND_WATERMARK_LINK;
  1602. rightWatermarkDiv.get(0).style.backgroundImage
  1603. = "url(images/rightwatermark.png)";
  1604. }
  1605. if (interfaceConfig.SHOW_POWERED_BY) {
  1606. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1607. }
  1608. $("#welcome_page").hide();
  1609. VideoLayout.resizeLargeVideoContainer();
  1610. $("#videospace").mousemove(function () {
  1611. return ToolbarToggler.showToolbar();
  1612. });
  1613. // Set the defaults for prompt dialogs.
  1614. jQuery.prompt.setDefaults({persistent: false});
  1615. VideoLayout.init(eventEmitter);
  1616. AudioLevels.init();
  1617. NicknameHandler.init(eventEmitter);
  1618. registerListeners();
  1619. bindEvents();
  1620. setupPrezi();
  1621. setupToolbars();
  1622. setupChat();
  1623. document.title = interfaceConfig.APP_NAME;
  1624. $("#downloadlog").click(function (event) {
  1625. dump(event.target);
  1626. });
  1627. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1628. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1629. {
  1630. $("#videoconference_page").hide();
  1631. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1632. setupWelcomePage();
  1633. return;
  1634. }
  1635. $("#welcome_page").hide();
  1636. // Display notice message at the top of the toolbar
  1637. if (config.noticeMessage) {
  1638. $('#noticeText').text(config.noticeMessage);
  1639. $('#notice').css({display: 'block'});
  1640. }
  1641. document.getElementById('largeVideo').volume = 0;
  1642. if (!$('#settings').is(':visible')) {
  1643. console.log('init');
  1644. init();
  1645. } else {
  1646. loginInfo.onsubmit = function (e) {
  1647. if (e.preventDefault) e.preventDefault();
  1648. $('#settings').hide();
  1649. init();
  1650. };
  1651. }
  1652. toastr.options = {
  1653. "closeButton": true,
  1654. "debug": false,
  1655. "positionClass": "notification-bottom-right",
  1656. "onclick": null,
  1657. "showDuration": "300",
  1658. "hideDuration": "1000",
  1659. "timeOut": "2000",
  1660. "extendedTimeOut": "1000",
  1661. "showEasing": "swing",
  1662. "hideEasing": "linear",
  1663. "showMethod": "fadeIn",
  1664. "hideMethod": "fadeOut",
  1665. "reposition": function() {
  1666. if(PanelToggler.isVisible()) {
  1667. $("#toast-container").addClass("notification-bottom-right-center");
  1668. } else {
  1669. $("#toast-container").removeClass("notification-bottom-right-center");
  1670. }
  1671. },
  1672. "newestOnTop": false
  1673. };
  1674. SettingsMenu.init();
  1675. };
  1676. function chatAddError(errorMessage, originalText)
  1677. {
  1678. return Chat.chatAddError(errorMessage, originalText);
  1679. };
  1680. function chatSetSubject(text)
  1681. {
  1682. return Chat.chatSetSubject(text);
  1683. };
  1684. function updateChatConversation(from, displayName, message) {
  1685. return Chat.updateChatConversation(from, displayName, message);
  1686. };
  1687. function onMucJoined(jid, info) {
  1688. Toolbar.updateRoomUrl(window.location.href);
  1689. var meHTML = APP.translation.generateTranslatonHTML("me");
  1690. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1691. var settings = Settings.getSettings();
  1692. // Add myself to the contact list.
  1693. ContactList.addContact(jid, settings.email || settings.uid);
  1694. // Once we've joined the muc show the toolbar
  1695. ToolbarToggler.showToolbar();
  1696. var displayName = !config.displayJids
  1697. ? info.displayName : Strophe.getResourceFromJid(jid);
  1698. if (displayName)
  1699. onDisplayNameChanged('localVideoContainer', displayName);
  1700. VideoLayout.mucJoined();
  1701. }
  1702. function initEtherpad(name) {
  1703. Etherpad.init(name);
  1704. };
  1705. function onMucMemberLeft(jid) {
  1706. console.log('left.muc', jid);
  1707. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1708. '>.displayname').html();
  1709. messageHandler.notify(displayName,'notify.somebody',
  1710. 'disconnected',
  1711. 'notify.disconnected');
  1712. if(!config.startAudioMuted ||
  1713. config.startAudioMuted > APP.members.size())
  1714. UIUtil.playSoundNotification('userLeft');
  1715. // Need to call this with a slight delay, otherwise the element couldn't be
  1716. // found for some reason.
  1717. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1718. window.setTimeout(function () {
  1719. var container = document.getElementById(
  1720. 'participant_' + Strophe.getResourceFromJid(jid));
  1721. if (container) {
  1722. ContactList.removeContact(jid);
  1723. VideoLayout.removeConnectionIndicator(jid);
  1724. // hide here, wait for video to close before removing
  1725. $(container).hide();
  1726. VideoLayout.resizeThumbnails();
  1727. }
  1728. }, 10);
  1729. VideoLayout.participantLeft(jid);
  1730. };
  1731. function onLocalRoleChanged(jid, info, pres, isModerator)
  1732. {
  1733. console.info("My role changed, new role: " + info.role);
  1734. onModeratorStatusChanged(isModerator);
  1735. VideoLayout.showModeratorIndicator();
  1736. SettingsMenu.onRoleChanged();
  1737. if (isModerator) {
  1738. Authentication.closeAuthenticationWindow();
  1739. messageHandler.notify(null, "notify.me",
  1740. 'connected', "notify.moderator");
  1741. }
  1742. }
  1743. function onModeratorStatusChanged(isModerator) {
  1744. Toolbar.showSipCallButton(isModerator);
  1745. Toolbar.showRecordingButton(
  1746. isModerator); //&&
  1747. // FIXME:
  1748. // Recording visible if
  1749. // there are at least 2(+ 1 focus) participants
  1750. //Object.keys(connection.emuc.members).length >= 3);
  1751. if (isModerator && config.etherpad_base) {
  1752. Etherpad.init();
  1753. }
  1754. };
  1755. function onPasswordRequired(callback) {
  1756. // password is required
  1757. Toolbar.lockLockButton();
  1758. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1759. message += APP.translation.translateString(
  1760. "dialog.passwordRequired");
  1761. message += '</h2>' +
  1762. '<input name="lockKey" type="text" data-i18n=' +
  1763. '"[placeholder]dialog.password" placeholder="' +
  1764. APP.translation.translateString("dialog.password") +
  1765. '" autofocus>';
  1766. messageHandler.openTwoButtonDialog(null, null, null, message,
  1767. true,
  1768. "dialog.Ok",
  1769. function (e, v, m, f) {},
  1770. null,
  1771. function (e, v, m, f) {
  1772. if (v) {
  1773. var lockKey = f.lockKey;
  1774. if (lockKey) {
  1775. Toolbar.setSharedKey(lockKey);
  1776. callback(lockKey);
  1777. }
  1778. }
  1779. },
  1780. ':input:first'
  1781. );
  1782. }
  1783. /**
  1784. * The dialpad button is shown iff there is at least one member that supports
  1785. * DTMF (e.g. jigasi).
  1786. */
  1787. function onDtmfSupportChanged(dtmfSupport) {
  1788. //TODO: enable when the UI is ready
  1789. //Toolbar.showDialPadButton(dtmfSupport);
  1790. }
  1791. function onMucMemberJoined(jid, id, displayName) {
  1792. messageHandler.notify(displayName,'notify.somebody',
  1793. 'connected',
  1794. 'notify.connected');
  1795. if(!config.startAudioMuted ||
  1796. config.startAudioMuted > APP.members.size())
  1797. UIUtil.playSoundNotification('userJoined');
  1798. // Add Peer's container
  1799. VideoLayout.ensurePeerContainerExists(jid,id);
  1800. }
  1801. function onMucPresenceStatus( jid, info) {
  1802. VideoLayout.setPresenceStatus(
  1803. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1804. }
  1805. function onMucRoleChanged(role, displayName) {
  1806. VideoLayout.showModeratorIndicator();
  1807. if (role === 'moderator') {
  1808. var messageKey, messageOptions = {};
  1809. if (!displayName) {
  1810. messageKey = "notify.grantedToUnknown";
  1811. }
  1812. else
  1813. {
  1814. messageKey = "notify.grantedTo";
  1815. messageOptions = {to: displayName};
  1816. }
  1817. messageHandler.notify(
  1818. displayName,'notify.somebody',
  1819. 'connected', messageKey,
  1820. messageOptions);
  1821. }
  1822. }
  1823. function onAuthenticationRequired(intervalCallback) {
  1824. Authentication.openAuthenticationDialog(
  1825. roomName, intervalCallback, function () {
  1826. Toolbar.authenticateClicked();
  1827. });
  1828. };
  1829. function onLastNChanged(oldValue, newValue) {
  1830. if (config.muteLocalVideoIfNotInLastN) {
  1831. setVideoMute(!newValue, { 'byUser': false });
  1832. }
  1833. }
  1834. UI.toggleSmileys = function () {
  1835. Chat.toggleSmileys();
  1836. };
  1837. UI.getSettings = function () {
  1838. return Settings.getSettings();
  1839. };
  1840. UI.toggleFilmStrip = function () {
  1841. return BottomToolbar.toggleFilmStrip();
  1842. };
  1843. UI.toggleChat = function () {
  1844. return BottomToolbar.toggleChat();
  1845. };
  1846. UI.toggleContactList = function () {
  1847. return BottomToolbar.toggleContactList();
  1848. };
  1849. UI.inputDisplayNameHandler = function (value) {
  1850. VideoLayout.inputDisplayNameHandler(value);
  1851. };
  1852. UI.getLargeVideoState = function()
  1853. {
  1854. return VideoLayout.getLargeVideoState();
  1855. };
  1856. UI.generateRoomName = function() {
  1857. if(roomName)
  1858. return roomName;
  1859. var roomnode = null;
  1860. var path = window.location.pathname;
  1861. // determinde the room node from the url
  1862. // TODO: just the roomnode or the whole bare jid?
  1863. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1864. // custom function might be responsible for doing the pushstate
  1865. roomnode = config.getroomnode(path);
  1866. } else {
  1867. /* fall back to default strategy
  1868. * this is making assumptions about how the URL->room mapping happens.
  1869. * It currently assumes deployment at root, with a rewrite like the
  1870. * following one (for nginx):
  1871. location ~ ^/([a-zA-Z0-9]+)$ {
  1872. rewrite ^/(.*)$ / break;
  1873. }
  1874. */
  1875. if (path.length > 1) {
  1876. roomnode = path.substr(1).toLowerCase();
  1877. } else {
  1878. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1879. roomnode = word.toLowerCase();
  1880. window.history.pushState('VideoChat',
  1881. 'Room: ' + word, window.location.pathname + word);
  1882. }
  1883. }
  1884. roomName = roomnode + '@' + config.hosts.muc;
  1885. return roomName;
  1886. };
  1887. UI.connectionIndicatorShowMore = function(id)
  1888. {
  1889. return VideoLayout.connectionIndicators[id].showMore();
  1890. };
  1891. UI.showLoginPopup = function(callback)
  1892. {
  1893. console.log('password is required');
  1894. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1895. message += APP.translation.translateString(
  1896. "dialog.passwordRequired");
  1897. message += '</h2>' +
  1898. '<input name="username" type="text" ' +
  1899. 'placeholder="user@domain.net" autofocus>' +
  1900. '<input name="password" ' +
  1901. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1902. ' placeholder="user password">';
  1903. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1904. true,
  1905. "dialog.Ok",
  1906. function (e, v, m, f) {
  1907. if (v) {
  1908. if (f.username !== null && f.password != null) {
  1909. callback(f.username, f.password);
  1910. }
  1911. }
  1912. },
  1913. null, null, ':input:first'
  1914. );
  1915. }
  1916. UI.checkForNicknameAndJoin = function () {
  1917. Authentication.closeAuthenticationDialog();
  1918. Authentication.stopInterval();
  1919. var nick = null;
  1920. if (config.useNicks) {
  1921. nick = window.prompt('Your nickname (optional)');
  1922. }
  1923. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1924. };
  1925. function dump(elem, filename) {
  1926. elem = elem.parentNode;
  1927. elem.download = filename || 'meetlog.json';
  1928. elem.href = 'data:application/json;charset=utf-8,\n';
  1929. var data = APP.xmpp.populateData();
  1930. var metadata = {};
  1931. metadata.time = new Date();
  1932. metadata.url = window.location.href;
  1933. metadata.ua = navigator.userAgent;
  1934. var log = APP.xmpp.getLogger();
  1935. if (log) {
  1936. metadata.xmpp = log;
  1937. }
  1938. data.metadata = metadata;
  1939. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1940. return false;
  1941. }
  1942. UI.getRoomName = function () {
  1943. return roomName;
  1944. };
  1945. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  1946. if(muteAudio || muteVideo) notifyForInitialMute();
  1947. if(muteAudio) UI.setAudioMuted(true);
  1948. if(muteVideo) UI.setVideoMute(true);
  1949. }
  1950. /**
  1951. * Mutes/unmutes the local video.
  1952. */
  1953. UI.toggleVideo = function () {
  1954. setVideoMute(!APP.RTC.localVideo.isMuted());
  1955. };
  1956. /**
  1957. * Mutes / unmutes audio for the local participant.
  1958. */
  1959. UI.toggleAudio = function() {
  1960. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1961. };
  1962. /**
  1963. * Sets muted audio state for the local participant.
  1964. */
  1965. UI.setAudioMuted = function (mute, earlyMute) {
  1966. var audioMute = null;
  1967. if(earlyMute)
  1968. audioMute = function (mute, cb) {
  1969. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  1970. };
  1971. else
  1972. audioMute = function (mute, cb) {
  1973. return APP.xmpp.setAudioMute(mute, cb);
  1974. }
  1975. if(!audioMute(mute, function () {
  1976. VideoLayout.showLocalAudioIndicator(mute);
  1977. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1978. }))
  1979. {
  1980. // We still click the button.
  1981. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1982. return;
  1983. }
  1984. }
  1985. UI.addListener = function (type, listener) {
  1986. eventEmitter.on(type, listener);
  1987. }
  1988. UI.clickOnVideo = function (videoNumber) {
  1989. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1990. if (remoteVideos.length > videoNumber) {
  1991. remoteVideos[videoNumber].click();
  1992. }
  1993. }
  1994. //Used by torture
  1995. UI.showToolbar = function () {
  1996. return ToolbarToggler.showToolbar();
  1997. }
  1998. //Used by torture
  1999. UI.dockToolbar = function (isDock) {
  2000. return ToolbarToggler.dockToolbar(isDock);
  2001. }
  2002. UI.setVideoMuteButtonsState = function (mute) {
  2003. var video = $('#video');
  2004. var communicativeClass = "icon-camera";
  2005. var muteClass = "icon-camera icon-camera-disabled";
  2006. if (mute) {
  2007. video.removeClass(communicativeClass);
  2008. video.addClass(muteClass);
  2009. } else {
  2010. video.removeClass(muteClass);
  2011. video.addClass(communicativeClass);
  2012. }
  2013. }
  2014. UI.setVideoMute = setVideoMute;
  2015. module.exports = UI;
  2016. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes":105,"../../service/connectionquality/CQEvents":108,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../../service/members/Events":110,"../../service/xmpp/XMPPEvents":112,"./../settings/Settings":41,"./audio_levels/AudioLevels.js":10,"./authentication/Authentication":12,"./avatar/Avatar":14,"./etherpad/Etherpad.js":15,"./prezi/Prezi.js":16,"./side_pannels/SidePanelToggler":18,"./side_pannels/chat/Chat.js":19,"./side_pannels/contactlist/ContactList":23,"./side_pannels/settings/SettingsMenu":24,"./toolbars/BottomToolbar":25,"./toolbars/Toolbar":26,"./toolbars/ToolbarToggler":27,"./util/MessageHandler":29,"./util/NicknameHandler":30,"./util/UIUtil":31,"./videolayout/VideoLayout.js":33,"./welcome_page/RoomnameGenerator":34,"./welcome_page/WelcomePage":35,"events":62}],10:[function(require,module,exports){
  2017. var CanvasUtil = require("./CanvasUtils");
  2018. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  2019. function initActiveSpeakerAudioLevels() {
  2020. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  2021. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  2022. // Draw a circle.
  2023. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  2024. // Add a shadow around the circle
  2025. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  2026. ASDrawContext.shadowOffsetX = 0;
  2027. ASDrawContext.shadowOffsetY = 0;
  2028. }
  2029. /**
  2030. * The audio Levels plugin.
  2031. */
  2032. var AudioLevels = (function(my) {
  2033. var audioLevelCanvasCache = {};
  2034. my.LOCAL_LEVEL = 'local';
  2035. my.init = function () {
  2036. initActiveSpeakerAudioLevels();
  2037. }
  2038. /**
  2039. * Updates the audio level canvas for the given peerJid. If the canvas
  2040. * didn't exist we create it.
  2041. */
  2042. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  2043. var resourceJid = null;
  2044. var videoSpanId = null;
  2045. if (!peerJid)
  2046. videoSpanId = 'localVideoContainer';
  2047. else {
  2048. resourceJid = Strophe.getResourceFromJid(peerJid);
  2049. videoSpanId = 'participant_' + resourceJid;
  2050. }
  2051. var videoSpan = document.getElementById(videoSpanId);
  2052. if (!videoSpan) {
  2053. if (resourceJid)
  2054. console.error("No video element for jid", resourceJid);
  2055. else
  2056. console.error("No video element for local video.");
  2057. return;
  2058. }
  2059. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  2060. var videoSpaceWidth = $('#remoteVideos').width();
  2061. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  2062. var thumbnailWidth = thumbnailSize[0];
  2063. var thumbnailHeight = thumbnailSize[1];
  2064. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  2065. audioLevelCanvas = document.createElement('canvas');
  2066. audioLevelCanvas.className = "audiolevel";
  2067. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2068. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2069. resizeAudioLevelCanvas( audioLevelCanvas,
  2070. thumbnailWidth,
  2071. thumbnailHeight);
  2072. videoSpan.appendChild(audioLevelCanvas);
  2073. } else {
  2074. audioLevelCanvas = audioLevelCanvas.get(0);
  2075. resizeAudioLevelCanvas( audioLevelCanvas,
  2076. thumbnailWidth,
  2077. thumbnailHeight);
  2078. }
  2079. };
  2080. /**
  2081. * Updates the audio level UI for the given resourceJid.
  2082. *
  2083. * @param resourceJid the resource jid indicating the video element for
  2084. * which we draw the audio level
  2085. * @param audioLevel the newAudio level to render
  2086. */
  2087. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  2088. drawAudioLevelCanvas(resourceJid, audioLevel);
  2089. var videoSpanId = getVideoSpanId(resourceJid);
  2090. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  2091. if (!audioLevelCanvas)
  2092. return;
  2093. var drawContext = audioLevelCanvas.getContext('2d');
  2094. var canvasCache = audioLevelCanvasCache[resourceJid];
  2095. drawContext.clearRect (0, 0,
  2096. audioLevelCanvas.width, audioLevelCanvas.height);
  2097. drawContext.drawImage(canvasCache, 0, 0);
  2098. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  2099. if(!APP.xmpp.myJid()) {
  2100. return;
  2101. }
  2102. resourceJid = APP.xmpp.myResource();
  2103. }
  2104. if(resourceJid === largeVideoResourceJid) {
  2105. window.requestAnimationFrame(function () {
  2106. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  2107. });
  2108. }
  2109. };
  2110. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2111. if($("#activeSpeaker").css("visibility") == "hidden")
  2112. return;
  2113. ASDrawContext.clearRect(0, 0, 300, 300);
  2114. if(audioLevel == 0)
  2115. return;
  2116. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2117. // Fill the shape.
  2118. ASDrawContext.fill();
  2119. };
  2120. /**
  2121. * Resizes the given audio level canvas to match the given thumbnail size.
  2122. */
  2123. function resizeAudioLevelCanvas(audioLevelCanvas,
  2124. thumbnailWidth,
  2125. thumbnailHeight) {
  2126. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2127. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2128. }
  2129. /**
  2130. * Draws the audio level canvas into the cached canvas object.
  2131. *
  2132. * @param resourceJid the resource jid indicating the video element for
  2133. * which we draw the audio level
  2134. * @param audioLevel the newAudio level to render
  2135. */
  2136. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2137. if (!audioLevelCanvasCache[resourceJid]) {
  2138. var videoSpanId = getVideoSpanId(resourceJid);
  2139. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2140. /*
  2141. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2142. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2143. * error. Since audio levels are frequently updated, the errors have
  2144. * been observed to pile into the console, strain the CPU.
  2145. */
  2146. if (audioLevelCanvasOrig)
  2147. {
  2148. audioLevelCanvasCache[resourceJid]
  2149. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2150. }
  2151. }
  2152. var canvas = audioLevelCanvasCache[resourceJid];
  2153. if (!canvas)
  2154. return;
  2155. var drawContext = canvas.getContext('2d');
  2156. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2157. var shadowLevel = getShadowLevel(audioLevel);
  2158. if (shadowLevel > 0)
  2159. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2160. CanvasUtil.drawRoundRectGlow( drawContext,
  2161. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2162. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2163. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2164. interfaceConfig.CANVAS_RADIUS,
  2165. interfaceConfig.SHADOW_COLOR,
  2166. shadowLevel);
  2167. }
  2168. /**
  2169. * Returns the shadow/glow level for the given audio level.
  2170. *
  2171. * @param audioLevel the audio level from which we determine the shadow
  2172. * level
  2173. */
  2174. function getShadowLevel (audioLevel) {
  2175. var shadowLevel = 0;
  2176. if (audioLevel <= 0.3) {
  2177. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2178. }
  2179. else if (audioLevel <= 0.6) {
  2180. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2181. }
  2182. else {
  2183. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2184. }
  2185. return shadowLevel;
  2186. }
  2187. /**
  2188. * Returns the video span id corresponding to the given resourceJid or local
  2189. * user.
  2190. */
  2191. function getVideoSpanId(resourceJid) {
  2192. var videoSpanId = null;
  2193. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2194. || (APP.xmpp.myResource() && resourceJid
  2195. === APP.xmpp.myResource()))
  2196. videoSpanId = 'localVideoContainer';
  2197. else
  2198. videoSpanId = 'participant_' + resourceJid;
  2199. return videoSpanId;
  2200. }
  2201. /**
  2202. * Indicates that the remote video has been resized.
  2203. */
  2204. $(document).bind('remotevideo.resized', function (event, width, height) {
  2205. var resized = false;
  2206. $('#remoteVideos>span>canvas').each(function() {
  2207. var canvas = $(this).get(0);
  2208. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2209. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2210. resized = true;
  2211. }
  2212. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2213. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2214. resized = true;
  2215. }
  2216. });
  2217. if (resized)
  2218. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2219. audioLevelCanvasCache[resourceJid].width
  2220. = width + interfaceConfig.CANVAS_EXTRA;
  2221. audioLevelCanvasCache[resourceJid].height
  2222. = height + interfaceConfig.CANVAS_EXTRA;
  2223. });
  2224. });
  2225. return my;
  2226. })(AudioLevels || {});
  2227. module.exports = AudioLevels;
  2228. },{"./CanvasUtils":11}],11:[function(require,module,exports){
  2229. /**
  2230. * Utility class for drawing canvas shapes.
  2231. */
  2232. var CanvasUtil = (function(my) {
  2233. /**
  2234. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2235. * of the glow.
  2236. *
  2237. * @param drawContext the context of the canvas to draw to
  2238. * @param x the x coordinate of the round rectangle
  2239. * @param y the y coordinate of the round rectangle
  2240. * @param w the width of the round rectangle
  2241. * @param h the height of the round rectangle
  2242. * @param glowColor the color of the glow
  2243. * @param glowWidth the width of the glow
  2244. */
  2245. my.drawRoundRectGlow
  2246. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2247. // Save the previous state of the context.
  2248. drawContext.save();
  2249. if (w < 2 * r) r = w / 2;
  2250. if (h < 2 * r) r = h / 2;
  2251. // Draw a round rectangle.
  2252. drawContext.beginPath();
  2253. drawContext.moveTo(x+r, y);
  2254. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2255. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2256. drawContext.arcTo(x, y+h, x, y, r);
  2257. drawContext.arcTo(x, y, x+w, y, r);
  2258. drawContext.closePath();
  2259. // Add a shadow around the rectangle
  2260. drawContext.shadowColor = glowColor;
  2261. drawContext.shadowBlur = glowWidth;
  2262. drawContext.shadowOffsetX = 0;
  2263. drawContext.shadowOffsetY = 0;
  2264. // Fill the shape.
  2265. drawContext.fill();
  2266. drawContext.save();
  2267. drawContext.restore();
  2268. // 1) Uncomment this line to use Composite Operation, which is doing the
  2269. // same as the clip function below and is also antialiasing the round
  2270. // border, but is said to be less fast performance wise.
  2271. // drawContext.globalCompositeOperation='destination-out';
  2272. drawContext.beginPath();
  2273. drawContext.moveTo(x+r, y);
  2274. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2275. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2276. drawContext.arcTo(x, y+h, x, y, r);
  2277. drawContext.arcTo(x, y, x+w, y, r);
  2278. drawContext.closePath();
  2279. // 2) Uncomment this line to use Composite Operation, which is doing the
  2280. // same as the clip function below and is also antialiasing the round
  2281. // border, but is said to be less fast performance wise.
  2282. // drawContext.fill();
  2283. // Comment these two lines if choosing to do the same with composite
  2284. // operation above 1 and 2.
  2285. drawContext.clip();
  2286. drawContext.clearRect(0, 0, 277, 200);
  2287. // Restore the previous context state.
  2288. drawContext.restore();
  2289. };
  2290. /**
  2291. * Clones the given canvas.
  2292. *
  2293. * @return the new cloned canvas.
  2294. */
  2295. my.cloneCanvas = function (oldCanvas) {
  2296. /*
  2297. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2298. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2299. * levels are frequently updated, the errors have been observed to pile
  2300. * into the console, strain the CPU.
  2301. */
  2302. if (!oldCanvas)
  2303. return oldCanvas;
  2304. //create a new canvas
  2305. var newCanvas = document.createElement('canvas');
  2306. var context = newCanvas.getContext('2d');
  2307. //set dimensions
  2308. newCanvas.width = oldCanvas.width;
  2309. newCanvas.height = oldCanvas.height;
  2310. //apply the old canvas to the new one
  2311. context.drawImage(oldCanvas, 0, 0);
  2312. //return the new canvas
  2313. return newCanvas;
  2314. };
  2315. return my;
  2316. })(CanvasUtil || {});
  2317. module.exports = CanvasUtil;
  2318. },{}],12:[function(require,module,exports){
  2319. /* global $, APP*/
  2320. var LoginDialog = require('./LoginDialog');
  2321. var Moderator = require('../../xmpp/moderator');
  2322. /* Initial "authentication required" dialog */
  2323. var authDialog = null;
  2324. /* Loop retry ID that wits for other user to create the room */
  2325. var authRetryId = null;
  2326. var authenticationWindow = null;
  2327. var Authentication = {
  2328. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2329. // This is the loop that will wait for the room to be created by
  2330. // someone else. 'auth_required.moderator' will bring us back here.
  2331. authRetryId = window.setTimeout(intervalCallback, 5000);
  2332. // Show prompt only if it's not open
  2333. if (authDialog !== null) {
  2334. return;
  2335. }
  2336. // extract room name from 'room@muc.server.net'
  2337. var room = roomName.substr(0, roomName.indexOf('@'));
  2338. var title
  2339. = APP.translation.generateTranslatonHTML("dialog.WaitingForHost");
  2340. var msg
  2341. = APP.translation.generateTranslatonHTML(
  2342. "dialog.WaitForHostMsg", {room: room});
  2343. var buttonTxt
  2344. = APP.translation.generateTranslatonHTML("dialog.IamHost");
  2345. var buttons = [];
  2346. buttons.push({title: buttonTxt, value: "authNow"});
  2347. authDialog = APP.UI.messageHandler.openDialog(
  2348. title,
  2349. msg,
  2350. true,
  2351. buttons,
  2352. function (onSubmitEvent, submitValue) {
  2353. // Do not close the dialog yet
  2354. onSubmitEvent.preventDefault();
  2355. // Open login popup
  2356. if (submitValue === 'authNow') {
  2357. callback();
  2358. }
  2359. }
  2360. );
  2361. },
  2362. closeAuthenticationWindow: function () {
  2363. if (authenticationWindow) {
  2364. authenticationWindow.close();
  2365. authenticationWindow = null;
  2366. }
  2367. },
  2368. xmppAuthenticate: function () {
  2369. var loginDialog = LoginDialog.show(
  2370. function (connection, state) {
  2371. if (!state) {
  2372. // User cancelled
  2373. loginDialog.close();
  2374. return;
  2375. } else if (state == APP.xmpp.Status.CONNECTED) {
  2376. loginDialog.close();
  2377. Authentication.stopInterval();
  2378. Authentication.closeAuthenticationDialog();
  2379. // Close the connection as anonymous one will be used
  2380. // to create the conference. Session-id will authorize
  2381. // the request.
  2382. connection.disconnect();
  2383. var roomName = APP.UI.generateRoomName();
  2384. Moderator.allocateConferenceFocus(roomName, function () {
  2385. // If it's not "on the fly" authentication now join
  2386. // the conference room
  2387. if (!APP.xmpp.getMUCJoined()) {
  2388. APP.UI.checkForNicknameAndJoin();
  2389. }
  2390. });
  2391. }
  2392. }, true);
  2393. },
  2394. focusAuthenticationWindow: function () {
  2395. // If auth window exists just bring it to the front
  2396. if (authenticationWindow) {
  2397. authenticationWindow.focus();
  2398. return;
  2399. }
  2400. },
  2401. closeAuthenticationDialog: function () {
  2402. // Close authentication dialog if opened
  2403. if (authDialog) {
  2404. authDialog.close();
  2405. authDialog = null;
  2406. }
  2407. },
  2408. createAuthenticationWindow: function (callback, url) {
  2409. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2410. url, 910, 660,
  2411. // On closed
  2412. function () {
  2413. // Close authentication dialog if opened
  2414. Authentication.closeAuthenticationDialog();
  2415. callback();
  2416. authenticationWindow = null;
  2417. });
  2418. return authenticationWindow;
  2419. },
  2420. stopInterval: function () {
  2421. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2422. if (authRetryId) {
  2423. window.clearTimeout(authRetryId);
  2424. authRetryId = null;
  2425. }
  2426. }
  2427. };
  2428. module.exports = Authentication;
  2429. },{"../../xmpp/moderator":51,"./LoginDialog":13}],13:[function(require,module,exports){
  2430. /* global $, APP, config*/
  2431. var XMPP = require('../../xmpp/xmpp');
  2432. var Moderator = require('../../xmpp/moderator');
  2433. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2434. // anonymous domain is not enabled
  2435. /**
  2436. * Creates new <tt>Dialog</tt> instance.
  2437. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2438. * when we either fail to connect or succeed(check Strophe.Status).
  2439. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2440. * in order to create session-id after the connection is established.
  2441. * @constructor
  2442. */
  2443. function Dialog(callback, obtainSession) {
  2444. var self = this;
  2445. var stop = false;
  2446. var connection = APP.xmpp.createConnection();
  2447. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2448. message += APP.translation.translateString("dialog.passwordRequired");
  2449. message += '</h2>' +
  2450. '<input name="username" type="text" ' +
  2451. 'placeholder="user@domain.net" autofocus>' +
  2452. '<input name="password" ' +
  2453. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2454. ' placeholder="user password">';
  2455. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2456. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2457. var states = {
  2458. login: {
  2459. html: message,
  2460. buttons: [
  2461. { title: okButton, value: true},
  2462. { title: cancelButton, value: false}
  2463. ],
  2464. focus: ':input:first',
  2465. submit: function (e, v, m, f) {
  2466. e.preventDefault();
  2467. if (v) {
  2468. var jid = f.username;
  2469. var password = f.password;
  2470. if (jid && password) {
  2471. stop = false;
  2472. connection.reset();
  2473. connDialog.goToState('connecting');
  2474. connection.connect(jid, password, stateHandler);
  2475. }
  2476. } else {
  2477. // User cancelled
  2478. stop = true;
  2479. callback();
  2480. }
  2481. }
  2482. },
  2483. connecting: {
  2484. title: APP.translation.translateString('dialog.connecting'),
  2485. html: '<div id="connectionStatus"></div>',
  2486. buttons: [],
  2487. defaultButton: 0
  2488. },
  2489. finished: {
  2490. title: APP.translation.translateString('dialog.error'),
  2491. html: '<div id="errorMessage"></div>',
  2492. buttons: [
  2493. {
  2494. title: APP.translation.translateString('dialog.retry'),
  2495. value: 'retry'
  2496. },
  2497. {
  2498. title: APP.translation.translateString('dialog.Cancel'),
  2499. value: 'cancel'
  2500. },
  2501. ],
  2502. defaultButton: 0,
  2503. submit: function (e, v, m, f) {
  2504. e.preventDefault();
  2505. if (v === 'retry')
  2506. connDialog.goToState('login');
  2507. else
  2508. callback();
  2509. }
  2510. }
  2511. };
  2512. var connDialog
  2513. = APP.UI.messageHandler.openDialogWithStates(states,
  2514. { persistent: true, closeText: '' }, null);
  2515. var stateHandler = function (status, message) {
  2516. if (stop) {
  2517. return;
  2518. }
  2519. var translateKey = "connection." + XMPP.getStatusString(status);
  2520. var statusStr = APP.translation.translateString(translateKey);
  2521. // Display current state
  2522. var connectionStatus =
  2523. connDialog.getState('connecting').find('#connectionStatus');
  2524. connectionStatus.text(statusStr);
  2525. switch (status) {
  2526. case XMPP.Status.CONNECTED:
  2527. stop = true;
  2528. if (!obtainSession) {
  2529. callback(connection, status);
  2530. return;
  2531. }
  2532. // Obtaining session-id status
  2533. connectionStatus.text(
  2534. APP.translation.translateString(
  2535. 'connection.FETCH_SESSION_ID'));
  2536. // Authenticate with Jicofo and obtain session-id
  2537. var roomName = APP.UI.generateRoomName();
  2538. // Jicofo will return new session-id when connected
  2539. // from authenticated domain
  2540. connection.sendIQ(
  2541. Moderator.createConferenceIq(roomName),
  2542. function (result) {
  2543. connectionStatus.text(
  2544. APP.translation.translateString(
  2545. 'connection.GOT_SESSION_ID'));
  2546. stop = true;
  2547. // Parse session-id
  2548. Moderator.parseSessionId(result);
  2549. callback(connection, status);
  2550. },
  2551. function (error) {
  2552. console.error("Auth on the fly failed", error);
  2553. stop = true;
  2554. var errorMsg =
  2555. APP.translation.translateString(
  2556. 'connection.GET_SESSION_ID_ERROR') +
  2557. $(error).find('>error').attr('code');
  2558. self.displayError(errorMsg);
  2559. connection.disconnect();
  2560. });
  2561. break;
  2562. case XMPP.Status.AUTHFAIL:
  2563. case XMPP.Status.CONNFAIL:
  2564. case XMPP.Status.DISCONNECTED:
  2565. stop = true;
  2566. callback(connection, status);
  2567. var errorMessage = statusStr;
  2568. if (message)
  2569. {
  2570. errorMessage += ': ' + message;
  2571. }
  2572. self.displayError(errorMessage);
  2573. break;
  2574. default:
  2575. break;
  2576. }
  2577. };
  2578. /**
  2579. * Displays error message in 'finished' state which allows either to cancel
  2580. * or retry.
  2581. * @param message the final message to be displayed.
  2582. */
  2583. this.displayError = function (message) {
  2584. var finishedState = connDialog.getState('finished');
  2585. var errorMessageElem = finishedState.find('#errorMessage');
  2586. errorMessageElem.text(message);
  2587. connDialog.goToState('finished');
  2588. };
  2589. /**
  2590. * Closes LoginDialog.
  2591. */
  2592. this.close = function () {
  2593. stop = true;
  2594. connDialog.close();
  2595. };
  2596. }
  2597. var LoginDialog = {
  2598. /**
  2599. * Displays login prompt used to establish new XMPP connection. Given
  2600. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2601. * called when we connect successfully(status === CONNECTED) or when we fail
  2602. * to do so. On connection failure program can call Dialog.close() method in
  2603. * order to cancel or do nothing to let the user retry.
  2604. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2605. * called when we either fail to connect or succeed(check
  2606. * Strophe.Status).
  2607. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2608. * Jicofo in order to create session-id after the connection is
  2609. * established.
  2610. * @returns {Dialog}
  2611. */
  2612. show: function (callback, obtainSession) {
  2613. return new Dialog(callback, obtainSession);
  2614. }
  2615. };
  2616. module.exports = LoginDialog;
  2617. },{"../../xmpp/moderator":51,"../../xmpp/xmpp":59}],14:[function(require,module,exports){
  2618. var Settings = require("../../settings/Settings");
  2619. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2620. var users = {};
  2621. var activeSpeakerJid;
  2622. function setVisibility(selector, show) {
  2623. if (selector && selector.length > 0) {
  2624. selector.css("visibility", show ? "visible" : "hidden");
  2625. }
  2626. }
  2627. function isUserMuted(jid) {
  2628. // XXX(gp) we may want to rename this method to something like
  2629. // isUserStreaming, for example.
  2630. if (jid && jid != APP.xmpp.myJid()) {
  2631. var resource = Strophe.getResourceFromJid(jid);
  2632. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2633. return true;
  2634. }
  2635. }
  2636. if(jid && jid == APP.xmpp.myJid())
  2637. {
  2638. var localVideo = APP.RTC.localVideo;
  2639. return (!localVideo || localVideo.isMuted());
  2640. }
  2641. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2642. return null;
  2643. }
  2644. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2645. }
  2646. function getGravatarUrl(id, size) {
  2647. if(id === APP.xmpp.myJid() || !id) {
  2648. id = Settings.getSettings().uid;
  2649. }
  2650. return 'https://www.gravatar.com/avatar/' +
  2651. MD5.hexdigest(id.trim().toLowerCase()) +
  2652. "?d=wavatar&size=" + (size || "30");
  2653. }
  2654. var Avatar = {
  2655. /**
  2656. * Sets the user's avatar in the settings menu(if local user), contact list
  2657. * and thumbnail
  2658. * @param jid jid of the user
  2659. * @param id email or userID to be used as a hash
  2660. */
  2661. setUserAvatar: function (jid, id) {
  2662. if (id) {
  2663. if (users[jid] === id) {
  2664. return;
  2665. }
  2666. users[jid] = id;
  2667. }
  2668. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2669. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2670. var resourceJid = Strophe.getResourceFromJid(jid);
  2671. var thumbnail = $('#participant_' + resourceJid);
  2672. var avatar = $('#avatar_' + resourceJid);
  2673. // set the avatar in the settings menu if it is local user and get the
  2674. // local video container
  2675. if (jid === APP.xmpp.myJid()) {
  2676. $('#avatar').get(0).src = thumbUrl;
  2677. thumbnail = $('#localVideoContainer');
  2678. }
  2679. // set the avatar in the contact list
  2680. var contact = $('#' + resourceJid + '>img');
  2681. if (contact && contact.length > 0) {
  2682. contact.get(0).src = contactListUrl;
  2683. }
  2684. // set the avatar in the thumbnail
  2685. if (avatar && avatar.length > 0) {
  2686. avatar[0].src = thumbUrl;
  2687. } else {
  2688. if (thumbnail && thumbnail.length > 0) {
  2689. avatar = document.createElement('img');
  2690. avatar.id = 'avatar_' + resourceJid;
  2691. avatar.className = 'userAvatar';
  2692. avatar.src = thumbUrl;
  2693. thumbnail.append(avatar);
  2694. }
  2695. }
  2696. //if the user is the current active speaker - update the active speaker
  2697. // avatar
  2698. if (jid === activeSpeakerJid) {
  2699. this.updateActiveSpeakerAvatarSrc(jid);
  2700. }
  2701. },
  2702. /**
  2703. * Hides or shows the user's avatar
  2704. * @param jid jid of the user
  2705. * @param show whether we should show the avatar or not
  2706. * video because there is no dominant speaker and no focused speaker
  2707. */
  2708. showUserAvatar: function (jid, show) {
  2709. if (users[jid]) {
  2710. var resourceJid = Strophe.getResourceFromJid(jid);
  2711. var video = $('#participant_' + resourceJid + '>video');
  2712. var avatar = $('#avatar_' + resourceJid);
  2713. if (jid === APP.xmpp.myJid()) {
  2714. video = $('#localVideoWrapper>video');
  2715. }
  2716. if (show === undefined || show === null) {
  2717. show = isUserMuted(jid);
  2718. }
  2719. //if the user is the currently focused, the dominant speaker or if
  2720. //there is no focused and no dominant speaker and the large video is
  2721. //currently shown
  2722. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2723. setVisibility($("#largeVideo"), !show);
  2724. setVisibility($('#activeSpeaker'), show);
  2725. setVisibility(avatar, false);
  2726. setVisibility(video, false);
  2727. } else {
  2728. if (video && video.length > 0) {
  2729. setVisibility(video, !show);
  2730. }
  2731. setVisibility(avatar, show);
  2732. }
  2733. }
  2734. },
  2735. /**
  2736. * Updates the src of the active speaker avatar
  2737. * @param jid of the current active speaker
  2738. */
  2739. updateActiveSpeakerAvatarSrc: function (jid) {
  2740. if (!jid) {
  2741. jid = APP.xmpp.findJidFromResource(
  2742. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2743. }
  2744. var avatar = $("#activeSpeakerAvatar")[0];
  2745. var url = getGravatarUrl(users[jid],
  2746. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2747. if (jid === activeSpeakerJid && avatar.src === url) {
  2748. return;
  2749. }
  2750. activeSpeakerJid = jid;
  2751. var isMuted = isUserMuted(jid);
  2752. if (jid && isMuted !== null) {
  2753. avatar.src = url;
  2754. setVisibility($("#largeVideo"), !isMuted);
  2755. Avatar.showUserAvatar(jid, isMuted);
  2756. }
  2757. }
  2758. };
  2759. module.exports = Avatar;
  2760. },{"../../../service/RTC/MediaStreamTypes":101,"../../settings/Settings":41,"../videolayout/VideoLayout":33}],15:[function(require,module,exports){
  2761. /* global $, config,
  2762. setLargeVideoVisible, Util */
  2763. var VideoLayout = require("../videolayout/VideoLayout");
  2764. var Prezi = require("../prezi/Prezi");
  2765. var UIUtil = require("../util/UIUtil");
  2766. var etherpadName = null;
  2767. var etherpadIFrame = null;
  2768. var domain = null;
  2769. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2770. /**
  2771. * Resizes the etherpad.
  2772. */
  2773. function resize() {
  2774. if ($('#etherpad>iframe').length) {
  2775. var remoteVideos = $('#remoteVideos');
  2776. var availableHeight
  2777. = window.innerHeight - remoteVideos.outerHeight();
  2778. var availableWidth = UIUtil.getAvailableVideoWidth();
  2779. $('#etherpad>iframe').width(availableWidth);
  2780. $('#etherpad>iframe').height(availableHeight);
  2781. }
  2782. }
  2783. /**
  2784. * Shares the Etherpad name with other participants.
  2785. */
  2786. function shareEtherpad() {
  2787. APP.xmpp.addToPresence("etherpad", etherpadName);
  2788. }
  2789. /**
  2790. * Creates the Etherpad button and adds it to the toolbar.
  2791. */
  2792. function enableEtherpadButton() {
  2793. if (!$('#etherpadButton').is(":visible"))
  2794. $('#etherpadButton').css({display: 'inline-block'});
  2795. }
  2796. /**
  2797. * Creates the IFrame for the etherpad.
  2798. */
  2799. function createIFrame() {
  2800. etherpadIFrame = document.createElement('iframe');
  2801. etherpadIFrame.src = domain + etherpadName + options;
  2802. etherpadIFrame.frameBorder = 0;
  2803. etherpadIFrame.scrolling = "no";
  2804. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2805. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2806. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2807. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2808. etherpadIFrame.onload = function() {
  2809. document.domain = document.domain;
  2810. bubbleIframeMouseMove(etherpadIFrame);
  2811. setTimeout(function() {
  2812. // the iframes inside of the etherpad are
  2813. // not yet loaded when the etherpad iframe is loaded
  2814. var outer = etherpadIFrame.
  2815. contentDocument.getElementsByName("ace_outer")[0];
  2816. bubbleIframeMouseMove(outer);
  2817. var inner = outer.
  2818. contentDocument.getElementsByName("ace_inner")[0];
  2819. bubbleIframeMouseMove(inner);
  2820. }, 2000);
  2821. };
  2822. }
  2823. function bubbleIframeMouseMove(iframe){
  2824. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2825. iframe.contentWindow.onmousemove = function(e){
  2826. if(existingOnMouseMove) existingOnMouseMove(e);
  2827. var evt = document.createEvent("MouseEvents");
  2828. var boundingClientRect = iframe.getBoundingClientRect();
  2829. evt.initMouseEvent(
  2830. "mousemove",
  2831. true, // bubbles
  2832. false, // not cancelable
  2833. window,
  2834. e.detail,
  2835. e.screenX,
  2836. e.screenY,
  2837. e.clientX + boundingClientRect.left,
  2838. e.clientY + boundingClientRect.top,
  2839. e.ctrlKey,
  2840. e.altKey,
  2841. e.shiftKey,
  2842. e.metaKey,
  2843. e.button,
  2844. null // no related element
  2845. );
  2846. iframe.dispatchEvent(evt);
  2847. };
  2848. }
  2849. /**
  2850. * On video selected event.
  2851. */
  2852. $(document).bind('video.selected', function (event, isPresentation) {
  2853. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2854. Etherpad.toggleEtherpad(isPresentation);
  2855. });
  2856. var Etherpad = {
  2857. /**
  2858. * Initializes the etherpad.
  2859. */
  2860. init: function (name) {
  2861. if (config.etherpad_base && !etherpadName) {
  2862. domain = config.etherpad_base;
  2863. if (!name) {
  2864. // In case we're the focus we generate the name.
  2865. etherpadName = Math.random().toString(36).substring(7) +
  2866. '_' + (new Date().getTime()).toString();
  2867. shareEtherpad();
  2868. }
  2869. else
  2870. etherpadName = name;
  2871. enableEtherpadButton();
  2872. /**
  2873. * Resizes the etherpad, when the window is resized.
  2874. */
  2875. $(window).resize(function () {
  2876. resize();
  2877. });
  2878. }
  2879. },
  2880. /**
  2881. * Opens/hides the Etherpad.
  2882. */
  2883. toggleEtherpad: function (isPresentation) {
  2884. if (!etherpadIFrame)
  2885. createIFrame();
  2886. var largeVideo = null;
  2887. if (Prezi.isPresentationVisible())
  2888. largeVideo = $('#presentation>iframe');
  2889. else
  2890. largeVideo = $('#largeVideo');
  2891. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2892. $('#activeSpeaker').css('visibility', 'hidden');
  2893. largeVideo.fadeOut(300, function () {
  2894. if (Prezi.isPresentationVisible()) {
  2895. largeVideo.css({opacity: '0'});
  2896. } else {
  2897. VideoLayout.setLargeVideoVisible(false);
  2898. }
  2899. });
  2900. $('#etherpad>iframe').fadeIn(300, function () {
  2901. document.body.style.background = '#eeeeee';
  2902. $('#etherpad>iframe').css({visibility: 'visible'});
  2903. $('#etherpad').css({zIndex: 2});
  2904. });
  2905. }
  2906. else if ($('#etherpad>iframe')) {
  2907. $('#etherpad>iframe').fadeOut(300, function () {
  2908. $('#etherpad>iframe').css({visibility: 'hidden'});
  2909. $('#etherpad').css({zIndex: 0});
  2910. document.body.style.background = 'black';
  2911. });
  2912. if (!isPresentation) {
  2913. $('#largeVideo').fadeIn(300, function () {
  2914. VideoLayout.setLargeVideoVisible(true);
  2915. });
  2916. }
  2917. }
  2918. resize();
  2919. },
  2920. isVisible: function() {
  2921. var etherpadIframe = $('#etherpad>iframe');
  2922. return etherpadIframe && etherpadIframe.is(':visible');
  2923. }
  2924. };
  2925. module.exports = Etherpad;
  2926. },{"../prezi/Prezi":16,"../util/UIUtil":31,"../videolayout/VideoLayout":33}],16:[function(require,module,exports){
  2927. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2928. var UIUtil = require("../util/UIUtil");
  2929. var VideoLayout = require("../videolayout/VideoLayout");
  2930. var messageHandler = require("../util/MessageHandler");
  2931. var PreziPlayer = require("./PreziPlayer");
  2932. var preziPlayer = null;
  2933. var Prezi = {
  2934. /**
  2935. * Reloads the current presentation.
  2936. */
  2937. reloadPresentation: function() {
  2938. var iframe = document.getElementById(preziPlayer.options.preziId);
  2939. iframe.src = iframe.src;
  2940. },
  2941. /**
  2942. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2943. * otherwise.
  2944. */
  2945. isPresentationVisible: function () {
  2946. return ($('#presentation>iframe') != null
  2947. && $('#presentation>iframe').css('opacity') == 1);
  2948. },
  2949. /**
  2950. * Opens the Prezi dialog, from which the user could choose a presentation
  2951. * to load.
  2952. */
  2953. openPreziDialog: function() {
  2954. var myprezi = APP.xmpp.getPrezi();
  2955. if (myprezi) {
  2956. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2957. null,
  2958. "dialog.removePreziMsg",
  2959. null,
  2960. false,
  2961. "dialog.Remove",
  2962. function(e,v,m,f) {
  2963. if(v) {
  2964. APP.xmpp.removePreziFromPresence();
  2965. }
  2966. }
  2967. );
  2968. }
  2969. else if (preziPlayer != null) {
  2970. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2971. null, "dialog.sharePreziMsg",
  2972. null,
  2973. false,
  2974. "dialog.Ok",
  2975. function(e,v,m,f) {
  2976. $.prompt.close();
  2977. }
  2978. );
  2979. }
  2980. else {
  2981. var html = APP.translation.generateTranslatonHTML(
  2982. "dialog.sharePreziTitle");
  2983. var cancelButton = APP.translation.generateTranslatonHTML(
  2984. "dialog.Cancel");
  2985. var shareButton = APP.translation.generateTranslatonHTML(
  2986. "dialog.Share");
  2987. var backButton = APP.translation.generateTranslatonHTML(
  2988. "dialog.Back");
  2989. var buttons = [];
  2990. var buttons1 = [];
  2991. // Cancel button to both states
  2992. buttons.push({title: cancelButton, value: false});
  2993. buttons1.push({title: cancelButton, value: false});
  2994. // Share button
  2995. buttons.push({title: shareButton, value: true});
  2996. // Back button
  2997. buttons1.push({title: backButton, value: true});
  2998. var linkError = APP.translation.generateTranslatonHTML(
  2999. "dialog.preziLinkError");
  3000. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  3001. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  3002. var openPreziState = {
  3003. state0: {
  3004. html: '<h2>' + html + '</h2>' +
  3005. '<input name="preziUrl" type="text" ' +
  3006. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  3007. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  3008. '\' placeholder="' + defaultUrl + '" autofocus>',
  3009. persistent: false,
  3010. buttons: buttons,
  3011. focus: ':input:first',
  3012. defaultButton: 0,
  3013. submit: function (e, v, m, f) {
  3014. e.preventDefault();
  3015. if(v)
  3016. {
  3017. var preziUrl = f.preziUrl;
  3018. if (preziUrl)
  3019. {
  3020. var urlValue
  3021. = encodeURI(UIUtil.escapeHtml(preziUrl));
  3022. if (urlValue.indexOf('http://prezi.com/') != 0
  3023. && urlValue.indexOf('https://prezi.com/') != 0)
  3024. {
  3025. $.prompt.goToState('state1');
  3026. return false;
  3027. }
  3028. else {
  3029. var presIdTmp = urlValue.substring(
  3030. urlValue.indexOf("prezi.com/") + 10);
  3031. if (!isAlphanumeric(presIdTmp)
  3032. || presIdTmp.indexOf('/') < 2) {
  3033. $.prompt.goToState('state1');
  3034. return false;
  3035. }
  3036. else {
  3037. APP.xmpp.addToPresence("prezi", urlValue);
  3038. $.prompt.close();
  3039. }
  3040. }
  3041. }
  3042. }
  3043. else
  3044. $.prompt.close();
  3045. }
  3046. },
  3047. state1: {
  3048. html: '<h2>' + html + '</h2>' +
  3049. linkError,
  3050. persistent: false,
  3051. buttons: buttons1,
  3052. focus: ':input:first',
  3053. defaultButton: 1,
  3054. submit: function (e, v, m, f) {
  3055. e.preventDefault();
  3056. if (v === 0)
  3057. $.prompt.close();
  3058. else
  3059. $.prompt.goToState('state0');
  3060. }
  3061. }
  3062. };
  3063. messageHandler.openDialogWithStates(openPreziState);
  3064. }
  3065. }
  3066. };
  3067. /**
  3068. * A new presentation has been added.
  3069. *
  3070. * @param event the event indicating the add of a presentation
  3071. * @param jid the jid from which the presentation was added
  3072. * @param presUrl url of the presentation
  3073. * @param currentSlide the current slide to which we should move
  3074. */
  3075. function presentationAdded(event, jid, presUrl, currentSlide) {
  3076. console.log("presentation added", presUrl);
  3077. var presId = getPresentationId(presUrl);
  3078. var elementId = 'participant_'
  3079. + Strophe.getResourceFromJid(jid)
  3080. + '_' + presId;
  3081. // We explicitly don't specify the peer jid here, because we don't want
  3082. // this video to be dealt with as a peer related one (for example we
  3083. // don't want to show a mute/kick menu for this one, etc.).
  3084. VideoLayout.addRemoteVideoContainer(null, elementId);
  3085. VideoLayout.resizeThumbnails();
  3086. var controlsEnabled = false;
  3087. if (jid === APP.xmpp.myJid())
  3088. controlsEnabled = true;
  3089. setPresentationVisible(true);
  3090. $('#largeVideoContainer').hover(
  3091. function (event) {
  3092. if (Prezi.isPresentationVisible()) {
  3093. var reloadButtonRight = window.innerWidth
  3094. - $('#presentation>iframe').offset().left
  3095. - $('#presentation>iframe').width();
  3096. $('#reloadPresentation').css({ right: reloadButtonRight,
  3097. display:'inline-block'});
  3098. }
  3099. },
  3100. function (event) {
  3101. if (!Prezi.isPresentationVisible())
  3102. $('#reloadPresentation').css({display:'none'});
  3103. else {
  3104. var e = event.toElement || event.relatedTarget;
  3105. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  3106. $('#reloadPresentation').css({display:'none'});
  3107. }
  3108. });
  3109. preziPlayer = new PreziPlayer(
  3110. 'presentation',
  3111. {preziId: presId,
  3112. width: getPresentationWidth(),
  3113. height: getPresentationHeihgt(),
  3114. controls: controlsEnabled,
  3115. debug: true
  3116. });
  3117. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  3118. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  3119. console.log("prezi status", event.value);
  3120. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  3121. if (jid != APP.xmpp.myJid())
  3122. preziPlayer.flyToStep(currentSlide);
  3123. }
  3124. });
  3125. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  3126. console.log("event value", event.value);
  3127. APP.xmpp.addToPresence("preziSlide", event.value);
  3128. });
  3129. $("#" + elementId).css( 'background-image',
  3130. 'url(../images/avatarprezi.png)');
  3131. $("#" + elementId).click(
  3132. function () {
  3133. setPresentationVisible(true);
  3134. }
  3135. );
  3136. };
  3137. /**
  3138. * A presentation has been removed.
  3139. *
  3140. * @param event the event indicating the remove of a presentation
  3141. * @param jid the jid for which the presentation was removed
  3142. * @param the url of the presentation
  3143. */
  3144. function presentationRemoved(event, jid, presUrl) {
  3145. console.log('presentation removed', presUrl);
  3146. var presId = getPresentationId(presUrl);
  3147. setPresentationVisible(false);
  3148. $('#participant_'
  3149. + Strophe.getResourceFromJid(jid)
  3150. + '_' + presId).remove();
  3151. $('#presentation>iframe').remove();
  3152. if (preziPlayer != null) {
  3153. preziPlayer.destroy();
  3154. preziPlayer = null;
  3155. }
  3156. };
  3157. /**
  3158. * Indicates if the given string is an alphanumeric string.
  3159. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  3160. * purpose of checking URIs.
  3161. */
  3162. function isAlphanumeric(unsafeText) {
  3163. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  3164. return regex.test(unsafeText);
  3165. }
  3166. /**
  3167. * Returns the presentation id from the given url.
  3168. */
  3169. function getPresentationId (presUrl) {
  3170. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  3171. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  3172. }
  3173. /**
  3174. * Returns the presentation width.
  3175. */
  3176. function getPresentationWidth() {
  3177. var availableWidth = UIUtil.getAvailableVideoWidth();
  3178. var availableHeight = getPresentationHeihgt();
  3179. var aspectRatio = 16.0 / 9.0;
  3180. if (availableHeight < availableWidth / aspectRatio) {
  3181. availableWidth = Math.floor(availableHeight * aspectRatio);
  3182. }
  3183. return availableWidth;
  3184. }
  3185. /**
  3186. * Returns the presentation height.
  3187. */
  3188. function getPresentationHeihgt() {
  3189. var remoteVideos = $('#remoteVideos');
  3190. return window.innerHeight - remoteVideos.outerHeight();
  3191. }
  3192. /**
  3193. * Resizes the presentation iframe.
  3194. */
  3195. function resize() {
  3196. if ($('#presentation>iframe')) {
  3197. $('#presentation>iframe').width(getPresentationWidth());
  3198. $('#presentation>iframe').height(getPresentationHeihgt());
  3199. }
  3200. }
  3201. /**
  3202. * Shows/hides a presentation.
  3203. */
  3204. function setPresentationVisible(visible) {
  3205. var prezi = $('#presentation>iframe');
  3206. if (visible) {
  3207. // Trigger the video.selected event to indicate a change in the
  3208. // large video.
  3209. $(document).trigger("video.selected", [true]);
  3210. $('#largeVideo').fadeOut(300);
  3211. prezi.fadeIn(300, function() {
  3212. prezi.css({opacity:'1'});
  3213. ToolbarToggler.dockToolbar(true);
  3214. VideoLayout.setLargeVideoVisible(false);
  3215. });
  3216. $('#activeSpeaker').css('visibility', 'hidden');
  3217. }
  3218. else {
  3219. if (prezi.css('opacity') == '1') {
  3220. prezi.fadeOut(300, function () {
  3221. prezi.css({opacity:'0'});
  3222. $('#reloadPresentation').css({display:'none'});
  3223. $('#largeVideo').fadeIn(300, function() {
  3224. VideoLayout.setLargeVideoVisible(true);
  3225. ToolbarToggler.dockToolbar(false);
  3226. });
  3227. });
  3228. }
  3229. }
  3230. }
  3231. /**
  3232. * Presentation has been removed.
  3233. */
  3234. $(document).bind('presentationremoved.muc', presentationRemoved);
  3235. /**
  3236. * Presentation has been added.
  3237. */
  3238. $(document).bind('presentationadded.muc', presentationAdded);
  3239. /*
  3240. * Indicates presentation slide change.
  3241. */
  3242. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3243. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3244. preziPlayer.flyToStep(current);
  3245. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3246. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3247. preziPlayer.flyToStep(current, i);
  3248. }
  3249. }
  3250. });
  3251. /**
  3252. * On video selected event.
  3253. */
  3254. $(document).bind('video.selected', function (event, isPresentation) {
  3255. if (!isPresentation && $('#presentation>iframe')) {
  3256. setPresentationVisible(false);
  3257. }
  3258. });
  3259. $(window).resize(function () {
  3260. resize();
  3261. });
  3262. module.exports = Prezi;
  3263. },{"../toolbars/ToolbarToggler":27,"../util/MessageHandler":29,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./PreziPlayer":17}],17:[function(require,module,exports){
  3264. (function() {
  3265. "use strict";
  3266. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3267. window.PreziPlayer = (function() {
  3268. PreziPlayer.API_VERSION = 1;
  3269. PreziPlayer.CURRENT_STEP = 'currentStep';
  3270. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3271. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3272. PreziPlayer.STATUS_LOADING = 'loading';
  3273. PreziPlayer.STATUS_READY = 'ready';
  3274. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3275. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3276. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3277. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3278. PreziPlayer.EVENT_STATUS = "statusChange";
  3279. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3280. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3281. PreziPlayer.domain = "https://prezi.com";
  3282. PreziPlayer.path = "/player/";
  3283. PreziPlayer.players = {};
  3284. PreziPlayer.binded_methods = ['changesHandler'];
  3285. PreziPlayer.createMultiplePlayers = function(optionArray){
  3286. for(var i=0; i<optionArray.length; i++) {
  3287. var optionSet = optionArray[i];
  3288. new PreziPlayer(optionSet.id, optionSet);
  3289. };
  3290. };
  3291. PreziPlayer.messageReceived = function(event){
  3292. var message, item, player;
  3293. try {
  3294. message = JSON.parse(event.data);
  3295. if (message.id && (player = PreziPlayer.players[message.id])) {
  3296. if (player.options.debug === true) {
  3297. if (console && console.log)
  3298. console.log('received', message);
  3299. }
  3300. if (message.type === "changes") {
  3301. player.changesHandler(message);
  3302. }
  3303. for (var i = 0; i < player.callbacks.length; i++) {
  3304. item = player.callbacks[i];
  3305. if (item && message.type === item.event) {
  3306. item.callback(message);
  3307. }
  3308. }
  3309. }
  3310. } catch (e) { }
  3311. };
  3312. function PreziPlayer(id, options) {
  3313. var params, paramString = "", _this = this;
  3314. if (PreziPlayer.players[id]){
  3315. PreziPlayer.players[id].destroy();
  3316. }
  3317. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3318. var method_name = PreziPlayer.binded_methods[i];
  3319. _this[method_name] = __bind(_this[method_name], _this);
  3320. };
  3321. options = options || {};
  3322. this.options = options;
  3323. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3324. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3325. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3326. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3327. this.callbacks = [];
  3328. this.id = id;
  3329. this.embedTo = document.getElementById(id);
  3330. if (!this.embedTo) {
  3331. throw "The element id is not available.";
  3332. }
  3333. this.iframe = document.createElement('iframe');
  3334. params = [
  3335. { name: 'oid', value: options.preziId },
  3336. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3337. { name: 'controls', value: options.controls ? 1 : 0 }
  3338. ];
  3339. for(var i=0; i<params.length; i++) {
  3340. var param = params[i];
  3341. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3342. };
  3343. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3344. this.iframe.frameBorder = 0;
  3345. this.iframe.scrolling = "no";
  3346. this.iframe.width = options.width || 640;
  3347. this.iframe.height = options.height || 480;
  3348. this.embedTo.innerHTML = '';
  3349. // JITSI: IN CASE SOMETHING GOES WRONG.
  3350. try {
  3351. this.embedTo.appendChild(this.iframe);
  3352. }
  3353. catch (err) {
  3354. console.log("CATCH ERROR");
  3355. }
  3356. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3357. // crashes for us.
  3358. this.initPollInterval = setInterval(function(){
  3359. _this.sendMessage({'action': 'init'});
  3360. }, 500);
  3361. PreziPlayer.players[id] = this;
  3362. }
  3363. PreziPlayer.prototype.changesHandler = function(message) {
  3364. var key, value, j, item;
  3365. if (this.initPollInterval) {
  3366. clearInterval(this.initPollInterval);
  3367. this.initPollInterval = false;
  3368. }
  3369. for (key in message.data) {
  3370. if (message.data.hasOwnProperty(key)){
  3371. value = message.data[key];
  3372. this.values[key] = value;
  3373. for (j=0; j<this.callbacks.length; j++) {
  3374. item = this.callbacks[j];
  3375. if (item && item.event === key + "Change"){
  3376. item.callback({type: item.event, value: value});
  3377. }
  3378. }
  3379. }
  3380. }
  3381. };
  3382. PreziPlayer.prototype.destroy = function() {
  3383. if (this.initPollInterval) {
  3384. clearInterval(this.initPollInterval);
  3385. this.initPollInterval = false;
  3386. }
  3387. this.embedTo.innerHTML = '';
  3388. };
  3389. PreziPlayer.prototype.sendMessage = function(message) {
  3390. if (this.options.debug === true) {
  3391. if (console && console.log) console.log('sent', message);
  3392. }
  3393. message.version = PreziPlayer.API_VERSION;
  3394. message.id = this.id;
  3395. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3396. };
  3397. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3398. PreziPlayer.prototype.flyToNextStep = function() {
  3399. return this.sendMessage({
  3400. 'action': 'present',
  3401. 'data': ['moveToNextStep']
  3402. });
  3403. };
  3404. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3405. PreziPlayer.prototype.flyToPreviousStep = function() {
  3406. return this.sendMessage({
  3407. 'action': 'present',
  3408. 'data': ['moveToPrevStep']
  3409. });
  3410. };
  3411. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3412. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3413. var obj = this;
  3414. // check animation_step
  3415. if (animation_step > 0 &&
  3416. obj.values.animationCountOnSteps &&
  3417. obj.values.animationCountOnSteps[step] <= animation_step) {
  3418. animation_step = obj.values.animationCountOnSteps[step];
  3419. }
  3420. // jump to animation steps by calling flyToNextStep()
  3421. function doAnimationSteps() {
  3422. if (obj.values.isMoving == true) {
  3423. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3424. return;
  3425. }
  3426. while (animation_step-- > 0) {
  3427. obj.flyToNextStep(); // do the animation steps
  3428. }
  3429. }
  3430. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3431. // jump to the step
  3432. return this.sendMessage({
  3433. 'action': 'present',
  3434. 'data': ['moveToStep', step]
  3435. });
  3436. };
  3437. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3438. PreziPlayer.prototype.flyToObject = function(objectId) {
  3439. return this.sendMessage({
  3440. 'action': 'present',
  3441. 'data': ['moveToObject', objectId]
  3442. });
  3443. };
  3444. PreziPlayer.prototype.play = function(defaultDelay) {
  3445. return this.sendMessage({
  3446. 'action': 'present',
  3447. 'data': ['startAutoPlay', defaultDelay]
  3448. });
  3449. };
  3450. PreziPlayer.prototype.stop = function() {
  3451. return this.sendMessage({
  3452. 'action': 'present',
  3453. 'data': ['stopAutoPlay']
  3454. });
  3455. };
  3456. PreziPlayer.prototype.pause = function(defaultDelay) {
  3457. return this.sendMessage({
  3458. 'action': 'present',
  3459. 'data': ['pauseAutoPlay', defaultDelay]
  3460. });
  3461. };
  3462. PreziPlayer.prototype.getCurrentStep = function() {
  3463. return this.values.currentStep;
  3464. };
  3465. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3466. return this.values.currentAnimationStep;
  3467. };
  3468. PreziPlayer.prototype.getCurrentObject = function() {
  3469. return this.values.currentObject;
  3470. };
  3471. PreziPlayer.prototype.getStatus = function() {
  3472. return this.values.status;
  3473. };
  3474. PreziPlayer.prototype.isPlaying = function() {
  3475. return this.values.isAutoPlaying;
  3476. };
  3477. PreziPlayer.prototype.getStepCount = function() {
  3478. return this.values.stepCount;
  3479. };
  3480. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3481. return this.values.animationCountOnSteps;
  3482. };
  3483. PreziPlayer.prototype.getTitle = function() {
  3484. return this.values.title;
  3485. };
  3486. PreziPlayer.prototype.setDimensions = function(dims) {
  3487. for (var parameter in dims) {
  3488. this.iframe[parameter] = dims[parameter];
  3489. }
  3490. }
  3491. PreziPlayer.prototype.getDimensions = function() {
  3492. return {
  3493. width: parseInt(this.iframe.width, 10),
  3494. height: parseInt(this.iframe.height, 10)
  3495. }
  3496. }
  3497. PreziPlayer.prototype.on = function(event, callback) {
  3498. this.callbacks.push({
  3499. event: event,
  3500. callback: callback
  3501. });
  3502. };
  3503. PreziPlayer.prototype.off = function(event, callback) {
  3504. var j, item;
  3505. if (event === undefined) {
  3506. this.callbacks = [];
  3507. }
  3508. j = this.callbacks.length;
  3509. while (j--) {
  3510. item = this.callbacks[j];
  3511. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3512. this.callbacks.splice(j, 1);
  3513. }
  3514. }
  3515. };
  3516. if (window.addEventListener) {
  3517. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3518. } else {
  3519. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3520. }
  3521. return PreziPlayer;
  3522. })();
  3523. })();
  3524. module.exports = PreziPlayer;
  3525. },{}],18:[function(require,module,exports){
  3526. var Chat = require("./chat/Chat");
  3527. var ContactList = require("./contactlist/ContactList");
  3528. var Settings = require("./../../settings/Settings");
  3529. var SettingsMenu = require("./settings/SettingsMenu");
  3530. var VideoLayout = require("../videolayout/VideoLayout");
  3531. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3532. var UIUtil = require("../util/UIUtil");
  3533. /**
  3534. * Toggler for the chat, contact list, settings menu, etc..
  3535. */
  3536. var PanelToggler = (function(my) {
  3537. var currentlyOpen = null;
  3538. var buttons = {
  3539. '#chatspace': '#chatBottomButton',
  3540. '#contactlist': '#contactListButton',
  3541. '#settingsmenu': '#settingsButton'
  3542. };
  3543. /**
  3544. * Resizes the video area
  3545. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3546. * @param completeFunction a function to be called when the video space is resized
  3547. */
  3548. var resizeVideoArea = function(isClosing, completeFunction) {
  3549. var videospace = $('#videospace');
  3550. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3551. var videospaceWidth = window.innerWidth - panelSize[0];
  3552. var videospaceHeight = window.innerHeight;
  3553. var videoSize
  3554. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3555. var videoWidth = videoSize[0];
  3556. var videoHeight = videoSize[1];
  3557. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3558. videoHeight,
  3559. videospaceWidth,
  3560. videospaceHeight);
  3561. var horizontalIndent = videoPosition[0];
  3562. var verticalIndent = videoPosition[1];
  3563. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3564. var thumbnailsWidth = thumbnailSize[0];
  3565. var thumbnailsHeight = thumbnailSize[1];
  3566. //for chat
  3567. videospace.animate({
  3568. right: panelSize[0],
  3569. width: videospaceWidth,
  3570. height: videospaceHeight
  3571. },
  3572. {
  3573. queue: false,
  3574. duration: 500,
  3575. complete: completeFunction
  3576. });
  3577. $('#remoteVideos').animate({
  3578. height: thumbnailsHeight
  3579. },
  3580. {
  3581. queue: false,
  3582. duration: 500
  3583. });
  3584. $('#remoteVideos>span').animate({
  3585. height: thumbnailsHeight,
  3586. width: thumbnailsWidth
  3587. },
  3588. {
  3589. queue: false,
  3590. duration: 500,
  3591. complete: function () {
  3592. $(document).trigger(
  3593. "remotevideo.resized",
  3594. [thumbnailsWidth,
  3595. thumbnailsHeight]);
  3596. }
  3597. });
  3598. $('#largeVideoContainer').animate({
  3599. width: videospaceWidth,
  3600. height: videospaceHeight
  3601. },
  3602. {
  3603. queue: false,
  3604. duration: 500
  3605. });
  3606. $('#largeVideo').animate({
  3607. width: videoWidth,
  3608. height: videoHeight,
  3609. top: verticalIndent,
  3610. bottom: verticalIndent,
  3611. left: horizontalIndent,
  3612. right: horizontalIndent
  3613. },
  3614. {
  3615. queue: false,
  3616. duration: 500
  3617. });
  3618. };
  3619. /**
  3620. * Toggles the windows in the side panel
  3621. * @param object the window that should be shown
  3622. * @param selector the selector for the element containing the panel
  3623. * @param onOpenComplete function to be called when the panel is opened
  3624. * @param onOpen function to be called if the window is going to be opened
  3625. * @param onClose function to be called if the window is going to be closed
  3626. */
  3627. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3628. UIUtil.buttonClick(buttons[selector], "active");
  3629. if (object.isVisible()) {
  3630. $("#toast-container").animate({
  3631. right: '5px'
  3632. },
  3633. {
  3634. queue: false,
  3635. duration: 500
  3636. });
  3637. $(selector).hide("slide", {
  3638. direction: "right",
  3639. queue: false,
  3640. duration: 500
  3641. });
  3642. if(typeof onClose === "function") {
  3643. onClose();
  3644. }
  3645. currentlyOpen = null;
  3646. }
  3647. else {
  3648. // Undock the toolbar when the chat is shown and if we're in a
  3649. // video mode.
  3650. if (VideoLayout.isLargeVideoVisible()) {
  3651. ToolbarToggler.dockToolbar(false);
  3652. }
  3653. if(currentlyOpen) {
  3654. var current = $(currentlyOpen);
  3655. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3656. current.css('z-index', 4);
  3657. setTimeout(function () {
  3658. current.css('display', 'none');
  3659. current.css('z-index', 5);
  3660. }, 500);
  3661. }
  3662. $("#toast-container").animate({
  3663. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3664. },
  3665. {
  3666. queue: false,
  3667. duration: 500
  3668. });
  3669. $(selector).show("slide", {
  3670. direction: "right",
  3671. queue: false,
  3672. duration: 500,
  3673. complete: onOpenComplete
  3674. });
  3675. if(typeof onOpen === "function") {
  3676. onOpen();
  3677. }
  3678. currentlyOpen = selector;
  3679. }
  3680. };
  3681. /**
  3682. * Opens / closes the chat area.
  3683. */
  3684. my.toggleChat = function() {
  3685. var chatCompleteFunction = Chat.isVisible() ?
  3686. function() {} : function () {
  3687. Chat.scrollChatToBottom();
  3688. $('#chatspace').trigger('shown');
  3689. };
  3690. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3691. toggle(Chat,
  3692. '#chatspace',
  3693. function () {
  3694. // Request the focus in the nickname field or the chat input field.
  3695. if ($('#nickname').css('visibility') === 'visible') {
  3696. $('#nickinput').focus();
  3697. } else {
  3698. $('#usermsg').focus();
  3699. }
  3700. },
  3701. null,
  3702. Chat.resizeChat,
  3703. null);
  3704. };
  3705. /**
  3706. * Opens / closes the contact list area.
  3707. */
  3708. my.toggleContactList = function () {
  3709. var completeFunction = ContactList.isVisible() ?
  3710. function() {} : function () { $('#contactlist').trigger('shown');};
  3711. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3712. toggle(ContactList,
  3713. '#contactlist',
  3714. null,
  3715. function() {
  3716. ContactList.setVisualNotification(false);
  3717. },
  3718. null);
  3719. };
  3720. /**
  3721. * Opens / closes the settings menu
  3722. */
  3723. my.toggleSettingsMenu = function() {
  3724. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3725. toggle(SettingsMenu,
  3726. '#settingsmenu',
  3727. null,
  3728. function() {
  3729. var settings = Settings.getSettings();
  3730. $('#setDisplayName').get(0).value = settings.displayName;
  3731. $('#setEmail').get(0).value = settings.email;
  3732. },
  3733. null);
  3734. };
  3735. /**
  3736. * Returns the size of the side panel.
  3737. */
  3738. my.getPanelSize = function () {
  3739. var availableHeight = window.innerHeight;
  3740. var availableWidth = window.innerWidth;
  3741. var panelWidth = 200;
  3742. if (availableWidth * 0.2 < 200) {
  3743. panelWidth = availableWidth * 0.2;
  3744. }
  3745. return [panelWidth, availableHeight];
  3746. };
  3747. my.isVisible = function() {
  3748. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3749. };
  3750. return my;
  3751. }(PanelToggler || {}));
  3752. module.exports = PanelToggler;
  3753. },{"../toolbars/ToolbarToggler":27,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./../../settings/Settings":41,"./chat/Chat":19,"./contactlist/ContactList":23,"./settings/SettingsMenu":24}],19:[function(require,module,exports){
  3754. /* global $, Util, nickname:true */
  3755. var Replacement = require("./Replacement");
  3756. var CommandsProcessor = require("./Commands");
  3757. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3758. var smileys = require("./smileys.json").smileys;
  3759. var NicknameHandler = require("../../util/NicknameHandler");
  3760. var UIUtil = require("../../util/UIUtil");
  3761. var UIEvents = require("../../../../service/UI/UIEvents");
  3762. var notificationInterval = false;
  3763. var unreadMessages = 0;
  3764. /**
  3765. * Shows/hides a visual notification, indicating that a message has arrived.
  3766. */
  3767. function setVisualNotification(show) {
  3768. var unreadMsgElement = document.getElementById('unreadMessages');
  3769. var unreadMsgBottomElement
  3770. = document.getElementById('bottomUnreadMessages');
  3771. var glower = $('#chatButton');
  3772. var bottomGlower = $('#chatBottomButton');
  3773. if (unreadMessages) {
  3774. unreadMsgElement.innerHTML = unreadMessages.toString();
  3775. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3776. ToolbarToggler.dockToolbar(true);
  3777. var chatButtonElement
  3778. = document.getElementById('chatButton').parentNode;
  3779. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3780. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3781. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3782. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3783. unreadMsgElement.setAttribute(
  3784. 'style',
  3785. 'top:' + topIndent +
  3786. '; left:' + leftIndent + ';');
  3787. var chatBottomButtonElement
  3788. = document.getElementById('chatBottomButton').parentNode;
  3789. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3790. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3791. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3792. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3793. unreadMsgBottomElement.setAttribute(
  3794. 'style',
  3795. 'top:' + bottomTopIndent +
  3796. '; left:' + bottomLeftIndent + ';');
  3797. if (!glower.hasClass('icon-chat-simple')) {
  3798. glower.removeClass('icon-chat');
  3799. glower.addClass('icon-chat-simple');
  3800. }
  3801. }
  3802. else {
  3803. unreadMsgElement.innerHTML = '';
  3804. unreadMsgBottomElement.innerHTML = '';
  3805. glower.removeClass('icon-chat-simple');
  3806. glower.addClass('icon-chat');
  3807. }
  3808. if (show && !notificationInterval) {
  3809. notificationInterval = window.setInterval(function () {
  3810. glower.toggleClass('active');
  3811. bottomGlower.toggleClass('active glowing');
  3812. }, 800);
  3813. }
  3814. else if (!show && notificationInterval) {
  3815. window.clearInterval(notificationInterval);
  3816. notificationInterval = false;
  3817. glower.removeClass('active');
  3818. bottomGlower.removeClass('glowing');
  3819. bottomGlower.addClass('active');
  3820. }
  3821. }
  3822. /**
  3823. * Returns the current time in the format it is shown to the user
  3824. * @returns {string}
  3825. */
  3826. function getCurrentTime() {
  3827. var now = new Date();
  3828. var hour = now.getHours();
  3829. var minute = now.getMinutes();
  3830. var second = now.getSeconds();
  3831. if(hour.toString().length === 1) {
  3832. hour = '0'+hour;
  3833. }
  3834. if(minute.toString().length === 1) {
  3835. minute = '0'+minute;
  3836. }
  3837. if(second.toString().length === 1) {
  3838. second = '0'+second;
  3839. }
  3840. return hour+':'+minute+':'+second;
  3841. }
  3842. function toggleSmileys()
  3843. {
  3844. var smileys = $('#smileysContainer');
  3845. if(!smileys.is(':visible')) {
  3846. smileys.show("slide", { direction: "down", duration: 300});
  3847. } else {
  3848. smileys.hide("slide", { direction: "down", duration: 300});
  3849. }
  3850. $('#usermsg').focus();
  3851. }
  3852. function addClickFunction(smiley, number) {
  3853. smiley.onclick = function addSmileyToMessage() {
  3854. var usermsg = $('#usermsg');
  3855. var message = usermsg.val();
  3856. message += smileys['smiley' + number];
  3857. usermsg.val(message);
  3858. usermsg.get(0).setSelectionRange(message.length, message.length);
  3859. toggleSmileys();
  3860. usermsg.focus();
  3861. };
  3862. }
  3863. /**
  3864. * Adds the smileys container to the chat
  3865. */
  3866. function addSmileys() {
  3867. var smileysContainer = document.createElement('div');
  3868. smileysContainer.id = 'smileysContainer';
  3869. for(var i = 1; i <= 21; i++) {
  3870. var smileyContainer = document.createElement('div');
  3871. smileyContainer.id = 'smiley' + i;
  3872. smileyContainer.className = 'smileyContainer';
  3873. var smiley = document.createElement('img');
  3874. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3875. smiley.className = 'smiley';
  3876. addClickFunction(smiley, i);
  3877. smileyContainer.appendChild(smiley);
  3878. smileysContainer.appendChild(smileyContainer);
  3879. }
  3880. $("#chatspace").append(smileysContainer);
  3881. }
  3882. /**
  3883. * Resizes the chat conversation.
  3884. */
  3885. function resizeChatConversation() {
  3886. var msgareaHeight = $('#usermsg').outerHeight();
  3887. var chatspace = $('#chatspace');
  3888. var width = chatspace.width();
  3889. var chat = $('#chatconversation');
  3890. var smileys = $('#smileysarea');
  3891. smileys.height(msgareaHeight);
  3892. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3893. $('#smileysContainer').css('bottom', msgareaHeight);
  3894. chat.width(width - 10);
  3895. chat.height(window.innerHeight - 15 - msgareaHeight);
  3896. }
  3897. /**
  3898. * Chat related user interface.
  3899. */
  3900. var Chat = (function (my) {
  3901. /**
  3902. * Initializes chat related interface.
  3903. */
  3904. my.init = function () {
  3905. if(NicknameHandler.getNickname())
  3906. Chat.setChatConversationMode(true);
  3907. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3908. function (nickname) {
  3909. Chat.setChatConversationMode(true);
  3910. });
  3911. $('#nickinput').keydown(function (event) {
  3912. if (event.keyCode === 13) {
  3913. event.preventDefault();
  3914. var val = UIUtil.escapeHtml(this.value);
  3915. this.value = '';
  3916. if (!NicknameHandler.getNickname()) {
  3917. NicknameHandler.setNickname(val);
  3918. return;
  3919. }
  3920. }
  3921. });
  3922. $('#usermsg').keydown(function (event) {
  3923. if (event.keyCode === 13) {
  3924. event.preventDefault();
  3925. var value = this.value;
  3926. $('#usermsg').val('').trigger('autosize.resize');
  3927. this.focus();
  3928. var command = new CommandsProcessor(value);
  3929. if(command.isCommand())
  3930. {
  3931. command.processCommand();
  3932. }
  3933. else
  3934. {
  3935. var message = UIUtil.escapeHtml(value);
  3936. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3937. }
  3938. }
  3939. });
  3940. var onTextAreaResize = function () {
  3941. resizeChatConversation();
  3942. Chat.scrollChatToBottom();
  3943. };
  3944. $('#usermsg').autosize({callback: onTextAreaResize});
  3945. $("#chatspace").bind("shown",
  3946. function () {
  3947. unreadMessages = 0;
  3948. setVisualNotification(false);
  3949. });
  3950. addSmileys();
  3951. };
  3952. /**
  3953. * Appends the given message to the chat conversation.
  3954. */
  3955. my.updateChatConversation = function (from, displayName, message) {
  3956. var divClassName = '';
  3957. if (APP.xmpp.myJid() === from) {
  3958. divClassName = "localuser";
  3959. }
  3960. else {
  3961. divClassName = "remoteuser";
  3962. if (!Chat.isVisible()) {
  3963. unreadMessages++;
  3964. UIUtil.playSoundNotification('chatNotification');
  3965. setVisualNotification(true);
  3966. }
  3967. }
  3968. // replace links and smileys
  3969. // Strophe already escapes special symbols on sending,
  3970. // so we escape here only tags to avoid double &amp;
  3971. var escMessage = message.replace(/</g, '&lt;').
  3972. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3973. var escDisplayName = UIUtil.escapeHtml(displayName);
  3974. message = Replacement.processReplacements(escMessage);
  3975. var messageContainer =
  3976. '<div class="chatmessage">'+
  3977. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3978. '<div class="username ' + divClassName +'">' + escDisplayName +
  3979. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3980. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3981. '</div>';
  3982. $('#chatconversation').append(messageContainer);
  3983. $('#chatconversation').animate(
  3984. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3985. };
  3986. /**
  3987. * Appends error message to the conversation
  3988. * @param errorMessage the received error message.
  3989. * @param originalText the original message.
  3990. */
  3991. my.chatAddError = function(errorMessage, originalText)
  3992. {
  3993. errorMessage = UIUtil.escapeHtml(errorMessage);
  3994. originalText = UIUtil.escapeHtml(originalText);
  3995. $('#chatconversation').append(
  3996. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3997. (originalText? (' \"'+ originalText + '\"') : "") +
  3998. ' was not sent.' +
  3999. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  4000. $('#chatconversation').animate(
  4001. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  4002. };
  4003. /**
  4004. * Sets the subject to the UI
  4005. * @param subject the subject
  4006. */
  4007. my.chatSetSubject = function(subject)
  4008. {
  4009. if(subject)
  4010. subject = subject.trim();
  4011. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  4012. if(subject === "")
  4013. {
  4014. $("#subject").css({display: "none"});
  4015. }
  4016. else
  4017. {
  4018. $("#subject").css({display: "block"});
  4019. }
  4020. };
  4021. /**
  4022. * Sets the chat conversation mode.
  4023. */
  4024. my.setChatConversationMode = function (isConversationMode) {
  4025. if (isConversationMode) {
  4026. $('#nickname').css({visibility: 'hidden'});
  4027. $('#chatconversation').css({visibility: 'visible'});
  4028. $('#usermsg').css({visibility: 'visible'});
  4029. $('#smileysarea').css({visibility: 'visible'});
  4030. $('#usermsg').focus();
  4031. }
  4032. };
  4033. /**
  4034. * Resizes the chat area.
  4035. */
  4036. my.resizeChat = function () {
  4037. var chatSize = require("../SidePanelToggler").getPanelSize();
  4038. $('#chatspace').width(chatSize[0]);
  4039. $('#chatspace').height(chatSize[1]);
  4040. resizeChatConversation();
  4041. };
  4042. /**
  4043. * Indicates if the chat is currently visible.
  4044. */
  4045. my.isVisible = function () {
  4046. return $('#chatspace').is(":visible");
  4047. };
  4048. /**
  4049. * Shows and hides the window with the smileys
  4050. */
  4051. my.toggleSmileys = toggleSmileys;
  4052. /**
  4053. * Scrolls chat to the bottom.
  4054. */
  4055. my.scrollChatToBottom = function() {
  4056. setTimeout(function () {
  4057. $('#chatconversation').scrollTop(
  4058. $('#chatconversation')[0].scrollHeight);
  4059. }, 5);
  4060. };
  4061. return my;
  4062. }(Chat || {}));
  4063. module.exports = Chat;
  4064. },{"../../../../service/UI/UIEvents":106,"../../toolbars/ToolbarToggler":27,"../../util/NicknameHandler":30,"../../util/UIUtil":31,"../SidePanelToggler":18,"./Commands":20,"./Replacement":21,"./smileys.json":22}],20:[function(require,module,exports){
  4065. var UIUtil = require("../../util/UIUtil");
  4066. /**
  4067. * List with supported commands. The keys are the names of the commands and
  4068. * the value is the function that processes the message.
  4069. * @type {{String: function}}
  4070. */
  4071. var commands = {
  4072. "topic" : processTopic
  4073. };
  4074. /**
  4075. * Extracts the command from the message.
  4076. * @param message the received message
  4077. * @returns {string} the command
  4078. */
  4079. function getCommand(message)
  4080. {
  4081. if(message)
  4082. {
  4083. for(var command in commands)
  4084. {
  4085. if(message.indexOf("/" + command) == 0)
  4086. return command;
  4087. }
  4088. }
  4089. return "";
  4090. };
  4091. /**
  4092. * Processes the data for topic command.
  4093. * @param commandArguments the arguments of the topic command.
  4094. */
  4095. function processTopic(commandArguments)
  4096. {
  4097. var topic = UIUtil.escapeHtml(commandArguments);
  4098. APP.xmpp.setSubject(topic);
  4099. }
  4100. /**
  4101. * Constructs new CommandProccessor instance from a message that
  4102. * handles commands received via chat messages.
  4103. * @param message the message
  4104. * @constructor
  4105. */
  4106. function CommandsProcessor(message)
  4107. {
  4108. var command = getCommand(message);
  4109. /**
  4110. * Returns the name of the command.
  4111. * @returns {String} the command
  4112. */
  4113. this.getCommand = function()
  4114. {
  4115. return command;
  4116. };
  4117. var messageArgument = message.substr(command.length + 2);
  4118. /**
  4119. * Returns the arguments of the command.
  4120. * @returns {string}
  4121. */
  4122. this.getArgument = function()
  4123. {
  4124. return messageArgument;
  4125. };
  4126. }
  4127. /**
  4128. * Checks whether this instance is valid command or not.
  4129. * @returns {boolean}
  4130. */
  4131. CommandsProcessor.prototype.isCommand = function()
  4132. {
  4133. if(this.getCommand())
  4134. return true;
  4135. return false;
  4136. };
  4137. /**
  4138. * Processes the command.
  4139. */
  4140. CommandsProcessor.prototype.processCommand = function()
  4141. {
  4142. if(!this.isCommand())
  4143. return;
  4144. commands[this.getCommand()](this.getArgument());
  4145. };
  4146. module.exports = CommandsProcessor;
  4147. },{"../../util/UIUtil":31}],21:[function(require,module,exports){
  4148. var Smileys = require("./smileys.json");
  4149. /**
  4150. * Processes links and smileys in "body"
  4151. */
  4152. function processReplacements(body)
  4153. {
  4154. //make links clickable
  4155. body = linkify(body);
  4156. //add smileys
  4157. body = smilify(body);
  4158. return body;
  4159. }
  4160. /**
  4161. * Finds and replaces all links in the links in "body"
  4162. * with their <a href=""></a>
  4163. */
  4164. function linkify(inputText)
  4165. {
  4166. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  4167. //URLs starting with http://, https://, or ftp://
  4168. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  4169. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  4170. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  4171. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  4172. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  4173. //Change email addresses to mailto:: links.
  4174. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  4175. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  4176. return replacedText;
  4177. }
  4178. /**
  4179. * Replaces common smiley strings with images
  4180. */
  4181. function smilify(body)
  4182. {
  4183. if(!body) {
  4184. return body;
  4185. }
  4186. var regexs = Smileys["regexs"];
  4187. for(var smiley in regexs) {
  4188. if(regexs.hasOwnProperty(smiley)) {
  4189. body = body.replace(regexs[smiley],
  4190. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4191. }
  4192. }
  4193. return body;
  4194. }
  4195. module.exports = {
  4196. processReplacements: processReplacements,
  4197. linkify: linkify
  4198. };
  4199. },{"./smileys.json":22}],22:[function(require,module,exports){
  4200. module.exports={
  4201. "smileys": {
  4202. "smiley1": ":)",
  4203. "smiley2": ":(",
  4204. "smiley3": ":D",
  4205. "smiley4": "(y)",
  4206. "smiley5": " :P",
  4207. "smiley6": "(wave)",
  4208. "smiley7": "(blush)",
  4209. "smiley8": "(chuckle)",
  4210. "smiley9": "(shocked)",
  4211. "smiley10": ":*",
  4212. "smiley11": "(n)",
  4213. "smiley12": "(search)",
  4214. "smiley13": " <3",
  4215. "smiley14": "(oops)",
  4216. "smiley15": "(angry)",
  4217. "smiley16": "(angel)",
  4218. "smiley17": "(sick)",
  4219. "smiley18": ";(",
  4220. "smiley19": "(bomb)",
  4221. "smiley20": "(clap)",
  4222. "smiley21": " ;)"
  4223. },
  4224. "regexs": {
  4225. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4226. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4227. "smiley1": /(:-\)|:\))/gi,
  4228. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4229. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4230. "smiley6": /(\(wave\))/gi,
  4231. "smiley7": /(\(blush\))/gi,
  4232. "smiley8": /(\(chuckle\))/gi,
  4233. "smiley9": /(:-0|\(shocked\))/gi,
  4234. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4235. "smiley11": /(\(n\))/gi,
  4236. "smiley12": /(\(search\))/g,
  4237. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4238. "smiley14": /(\(oops\))/gi,
  4239. "smiley15": /(\(angry\))/gi,
  4240. "smiley16": /(\(angel\))/gi,
  4241. "smiley17": /(\(sick\))/gi,
  4242. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4243. "smiley19": /(\(bomb\))/gi,
  4244. "smiley20": /(\(clap\))/gi,
  4245. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4246. }
  4247. }
  4248. },{}],23:[function(require,module,exports){
  4249. var numberOfContacts = 0;
  4250. var notificationInterval;
  4251. /**
  4252. * Updates the number of participants in the contact list button and sets
  4253. * the glow
  4254. * @param delta indicates whether a new user has joined (1) or someone has
  4255. * left(-1)
  4256. */
  4257. function updateNumberOfParticipants(delta) {
  4258. //when the user is alone we don't show the number of participants
  4259. if(numberOfContacts === 0) {
  4260. $("#numberOfParticipants").text('');
  4261. numberOfContacts += delta;
  4262. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4263. ContactList.setVisualNotification(true);
  4264. numberOfContacts += delta;
  4265. $("#numberOfParticipants").text(numberOfContacts);
  4266. }
  4267. }
  4268. /**
  4269. * Creates the avatar element.
  4270. *
  4271. * @return the newly created avatar element
  4272. */
  4273. function createAvatar(id) {
  4274. var avatar = document.createElement('img');
  4275. avatar.className = "icon-avatar avatar";
  4276. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4277. return avatar;
  4278. }
  4279. /**
  4280. * Creates the display name paragraph.
  4281. *
  4282. * @param displayName the display name to set
  4283. */
  4284. function createDisplayNameParagraph(key, displayName) {
  4285. var p = document.createElement('p');
  4286. if(displayName)
  4287. p.innerText = displayName;
  4288. else if(key)
  4289. {
  4290. p.setAttribute("data-i18n",key);
  4291. p.innerText = APP.translation.translateString(key);
  4292. }
  4293. return p;
  4294. }
  4295. function stopGlowing(glower) {
  4296. window.clearInterval(notificationInterval);
  4297. notificationInterval = false;
  4298. glower.removeClass('glowing');
  4299. if (!ContactList.isVisible()) {
  4300. glower.removeClass('active');
  4301. }
  4302. }
  4303. /**
  4304. * Contact list.
  4305. */
  4306. var ContactList = {
  4307. /**
  4308. * Indicates if the chat is currently visible.
  4309. *
  4310. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4311. * otherwise
  4312. */
  4313. isVisible: function () {
  4314. return $('#contactlist').is(":visible");
  4315. },
  4316. /**
  4317. * Adds a contact for the given peerJid if such doesn't yet exist.
  4318. *
  4319. * @param peerJid the peerJid corresponding to the contact
  4320. * @param id the user's email or userId used to get the user's avatar
  4321. */
  4322. ensureAddContact: function (peerJid, id) {
  4323. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4324. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4325. if (!contact || contact.length <= 0)
  4326. ContactList.addContact(peerJid, id);
  4327. },
  4328. /**
  4329. * Adds a contact for the given peer jid.
  4330. *
  4331. * @param peerJid the jid of the contact to add
  4332. * @param id the email or userId of the user
  4333. */
  4334. addContact: function (peerJid, id) {
  4335. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4336. var contactlist = $('#contactlist>ul');
  4337. var newContact = document.createElement('li');
  4338. newContact.id = resourceJid;
  4339. newContact.className = "clickable";
  4340. newContact.onclick = function (event) {
  4341. if (event.currentTarget.className === "clickable") {
  4342. $(ContactList).trigger('contactclicked', [peerJid]);
  4343. }
  4344. };
  4345. newContact.appendChild(createAvatar(id));
  4346. newContact.appendChild(createDisplayNameParagraph("participant"));
  4347. var clElement = contactlist.get(0);
  4348. if (resourceJid === APP.xmpp.myResource()
  4349. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4350. clElement.insertBefore(newContact,
  4351. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4352. }
  4353. else {
  4354. clElement.appendChild(newContact);
  4355. }
  4356. updateNumberOfParticipants(1);
  4357. },
  4358. /**
  4359. * Removes a contact for the given peer jid.
  4360. *
  4361. * @param peerJid the peerJid corresponding to the contact to remove
  4362. */
  4363. removeContact: function (peerJid) {
  4364. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4365. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4366. if (contact && contact.length > 0) {
  4367. var contactlist = $('#contactlist>ul');
  4368. contactlist.get(0).removeChild(contact.get(0));
  4369. updateNumberOfParticipants(-1);
  4370. }
  4371. },
  4372. setVisualNotification: function (show, stopGlowingIn) {
  4373. var glower = $('#contactListButton');
  4374. if (show && !notificationInterval) {
  4375. notificationInterval = window.setInterval(function () {
  4376. glower.toggleClass('active glowing');
  4377. }, 800);
  4378. }
  4379. else if (!show && notificationInterval) {
  4380. stopGlowing(glower);
  4381. }
  4382. if (stopGlowingIn) {
  4383. setTimeout(function () {
  4384. stopGlowing(glower);
  4385. }, stopGlowingIn);
  4386. }
  4387. },
  4388. setClickable: function (resourceJid, isClickable) {
  4389. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4390. if (isClickable) {
  4391. contact.addClass('clickable');
  4392. } else {
  4393. contact.removeClass('clickable');
  4394. }
  4395. },
  4396. onDisplayNameChange: function (peerJid, displayName) {
  4397. if (peerJid === 'localVideoContainer')
  4398. peerJid = APP.xmpp.myJid();
  4399. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4400. var contactName = $('#contactlist #' + resourceJid + '>p');
  4401. if (contactName && displayName && displayName.length > 0)
  4402. contactName.html(displayName);
  4403. }
  4404. };
  4405. module.exports = ContactList;
  4406. },{}],24:[function(require,module,exports){
  4407. var Avatar = require("../../avatar/Avatar");
  4408. var Settings = require("./../../../settings/Settings");
  4409. var UIUtil = require("../../util/UIUtil");
  4410. var languages = require("../../../../service/translation/languages");
  4411. function generateLanguagesSelectBox()
  4412. {
  4413. var currentLang = APP.translation.getCurrentLanguage();
  4414. var html = "<select id=\"languages_selectbox\">";
  4415. var langArray = languages.getLanguages();
  4416. for(var i = 0; i < langArray.length; i++)
  4417. {
  4418. var lang = langArray[i];
  4419. html += "<option ";
  4420. if(lang === currentLang)
  4421. html += "selected ";
  4422. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4423. html += "</option>";
  4424. }
  4425. return html + "</select>";
  4426. }
  4427. var SettingsMenu = {
  4428. init: function () {
  4429. $("#startMutedOptions").before(generateLanguagesSelectBox());
  4430. APP.translation.translateElement($("#languages_selectbox"));
  4431. $('#settingsmenu>input').keyup(function(event){
  4432. if(event.keyCode === 13) {//enter
  4433. SettingsMenu.update();
  4434. }
  4435. });
  4436. if(APP.xmpp.isModerator())
  4437. {
  4438. $("#startMutedOptions").css("display", "block");
  4439. }
  4440. else
  4441. {
  4442. $("#startMutedOptions").css("display", "none");
  4443. }
  4444. $("#updateSettings").click(function () {
  4445. SettingsMenu.update();
  4446. });
  4447. },
  4448. onRoleChanged: function () {
  4449. if(APP.xmpp.isModerator())
  4450. {
  4451. $("#startMutedOptions").css("display", "block");
  4452. }
  4453. else
  4454. {
  4455. $("#startMutedOptions").css("display", "none");
  4456. }
  4457. },
  4458. setStartMuted: function (audio, video) {
  4459. $("#startAudioMuted").attr("checked", audio);
  4460. $("#startVideoMuted").attr("checked", video);
  4461. },
  4462. update: function() {
  4463. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4464. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4465. if(newDisplayName) {
  4466. var displayName = Settings.setDisplayName(newDisplayName);
  4467. APP.xmpp.addToPresence("displayName", displayName, true);
  4468. }
  4469. var language = $("#languages_selectbox").val();
  4470. APP.translation.setLanguage(language);
  4471. Settings.setLanguage(language);
  4472. APP.xmpp.addToPresence("email", newEmail);
  4473. var email = Settings.setEmail(newEmail);
  4474. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  4475. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  4476. APP.xmpp.addToPresence("startMuted",
  4477. [startAudioMuted, startVideoMuted]);
  4478. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4479. },
  4480. isVisible: function() {
  4481. return $('#settingsmenu').is(':visible');
  4482. },
  4483. setDisplayName: function(newDisplayName) {
  4484. var displayName = Settings.setDisplayName(newDisplayName);
  4485. $('#setDisplayName').get(0).value = displayName;
  4486. },
  4487. onDisplayNameChange: function(peerJid, newDisplayName) {
  4488. if(peerJid === 'localVideoContainer' ||
  4489. peerJid === APP.xmpp.myJid()) {
  4490. this.setDisplayName(newDisplayName);
  4491. }
  4492. }
  4493. };
  4494. module.exports = SettingsMenu;
  4495. },{"../../../../service/translation/languages":111,"../../avatar/Avatar":14,"../../util/UIUtil":31,"./../../../settings/Settings":41}],25:[function(require,module,exports){
  4496. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4497. var buttonHandlers = {
  4498. "bottom_toolbar_contact_list": function () {
  4499. BottomToolbar.toggleContactList();
  4500. },
  4501. "bottom_toolbar_film_strip": function () {
  4502. BottomToolbar.toggleFilmStrip();
  4503. },
  4504. "bottom_toolbar_chat": function () {
  4505. BottomToolbar.toggleChat();
  4506. }
  4507. };
  4508. var BottomToolbar = (function (my) {
  4509. my.init = function () {
  4510. for(var k in buttonHandlers)
  4511. $("#" + k).click(buttonHandlers[k]);
  4512. };
  4513. my.toggleChat = function() {
  4514. PanelToggler.toggleChat();
  4515. };
  4516. my.toggleContactList = function() {
  4517. PanelToggler.toggleContactList();
  4518. };
  4519. my.toggleFilmStrip = function() {
  4520. var filmstrip = $("#remoteVideos");
  4521. filmstrip.toggleClass("hidden");
  4522. };
  4523. $(document).bind("remotevideo.resized", function (event, width, height) {
  4524. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4525. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4526. });
  4527. return my;
  4528. }(BottomToolbar || {}));
  4529. module.exports = BottomToolbar;
  4530. },{"../side_pannels/SidePanelToggler":18}],26:[function(require,module,exports){
  4531. /* global APP,$, buttonClick, config, lockRoom,
  4532. setSharedKey, Util */
  4533. var messageHandler = require("../util/MessageHandler");
  4534. var BottomToolbar = require("./BottomToolbar");
  4535. var Prezi = require("../prezi/Prezi");
  4536. var Etherpad = require("../etherpad/Etherpad");
  4537. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4538. var Authentication = require("../authentication/Authentication");
  4539. var UIUtil = require("../util/UIUtil");
  4540. var AuthenticationEvents
  4541. = require("../../../service/authentication/AuthenticationEvents");
  4542. var roomUrl = null;
  4543. var sharedKey = '';
  4544. var UI = null;
  4545. var buttonHandlers =
  4546. {
  4547. "toolbar_button_mute": function () {
  4548. return APP.UI.toggleAudio();
  4549. },
  4550. "toolbar_button_camera": function () {
  4551. return APP.UI.toggleVideo();
  4552. },
  4553. /*"toolbar_button_authentication": function () {
  4554. return Toolbar.authenticateClicked();
  4555. },*/
  4556. "toolbar_button_record": function () {
  4557. return toggleRecording();
  4558. },
  4559. "toolbar_button_security": function () {
  4560. return Toolbar.openLockDialog();
  4561. },
  4562. "toolbar_button_link": function () {
  4563. return Toolbar.openLinkDialog();
  4564. },
  4565. "toolbar_button_chat": function () {
  4566. return BottomToolbar.toggleChat();
  4567. },
  4568. "toolbar_button_prezi": function () {
  4569. return Prezi.openPreziDialog();
  4570. },
  4571. "toolbar_button_etherpad": function () {
  4572. return Etherpad.toggleEtherpad(0);
  4573. },
  4574. "toolbar_button_desktopsharing": function () {
  4575. return APP.desktopsharing.toggleScreenSharing();
  4576. },
  4577. "toolbar_button_fullScreen": function()
  4578. {
  4579. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4580. return Toolbar.toggleFullScreen();
  4581. },
  4582. "toolbar_button_sip": function () {
  4583. return callSipButtonClicked();
  4584. },
  4585. "toolbar_button_dialpad": function () {
  4586. return dialpadButtonClicked();
  4587. },
  4588. "toolbar_button_settings": function () {
  4589. PanelToggler.toggleSettingsMenu();
  4590. },
  4591. "toolbar_button_hangup": function () {
  4592. return hangup();
  4593. },
  4594. "toolbar_button_login": function () {
  4595. Toolbar.authenticateClicked();
  4596. },
  4597. "toolbar_button_logout": function () {
  4598. // Ask for confirmation
  4599. messageHandler.openTwoButtonDialog(
  4600. "dialog.logoutTitle",
  4601. null,
  4602. "dialog.logoutQuestion",
  4603. null,
  4604. false,
  4605. "dialog.Yes",
  4606. function (evt, yes) {
  4607. if (yes) {
  4608. APP.xmpp.logout(function (url) {
  4609. if (url) {
  4610. window.location.href = url;
  4611. } else {
  4612. hangup();
  4613. }
  4614. });
  4615. }
  4616. });
  4617. }
  4618. };
  4619. function hangup() {
  4620. APP.xmpp.disposeConference();
  4621. if(config.enableWelcomePage)
  4622. {
  4623. setTimeout(function()
  4624. {
  4625. window.localStorage.welcomePageDisabled = false;
  4626. window.location.pathname = "/";
  4627. }, 10000);
  4628. }
  4629. var title = APP.translation.generateTranslatonHTML(
  4630. "dialog.sessTerminated");
  4631. var msg = APP.translation.generateTranslatonHTML(
  4632. "dialog.hungUp");
  4633. var button = APP.translation.generateTranslatonHTML(
  4634. "dialog.joinAgain");
  4635. var buttons = [];
  4636. buttons.push({title: button, value: true});
  4637. UI.messageHandler.openDialog(
  4638. title,
  4639. msg,
  4640. true,
  4641. buttons,
  4642. function(event, value, message, formVals)
  4643. {
  4644. window.location.reload();
  4645. return false;
  4646. }
  4647. );
  4648. }
  4649. /**
  4650. * Starts or stops the recording for the conference.
  4651. */
  4652. function toggleRecording() {
  4653. APP.xmpp.toggleRecording(function (callback) {
  4654. var msg = APP.translation.generateTranslatonHTML(
  4655. "dialog.recordingToken");
  4656. var token = APP.translation.translateString("dialog.token");
  4657. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4658. '<h2>' + msg + '</h2>' +
  4659. '<input name="recordingToken" type="text" ' +
  4660. ' data-i18n="[placeholder]dialog.token" ' +
  4661. 'placeholder="' + token + '" autofocus>',
  4662. false,
  4663. "dialog.Save",
  4664. function (e, v, m, f) {
  4665. if (v) {
  4666. var token = f.recordingToken;
  4667. if (token) {
  4668. callback(UIUtil.escapeHtml(token));
  4669. }
  4670. }
  4671. },
  4672. null,
  4673. function () { },
  4674. ':input:first'
  4675. );
  4676. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4677. }
  4678. /**
  4679. * Locks / unlocks the room.
  4680. */
  4681. function lockRoom(lock) {
  4682. var currentSharedKey = '';
  4683. if (lock)
  4684. currentSharedKey = sharedKey;
  4685. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4686. // password is required
  4687. if (sharedKey)
  4688. {
  4689. console.log('set room password');
  4690. Toolbar.lockLockButton();
  4691. }
  4692. else
  4693. {
  4694. console.log('removed room password');
  4695. Toolbar.unlockLockButton();
  4696. }
  4697. }, function (err) {
  4698. console.warn('setting password failed', err);
  4699. messageHandler.showError("dialog.lockTitle",
  4700. "dialog.lockMessage");
  4701. Toolbar.setSharedKey('');
  4702. }, function () {
  4703. console.warn('room passwords not supported');
  4704. messageHandler.showError("dialog.warning",
  4705. "dialog.passwordNotSupported");
  4706. Toolbar.setSharedKey('');
  4707. });
  4708. };
  4709. /**
  4710. * Invite participants to conference.
  4711. */
  4712. function inviteParticipants() {
  4713. if (roomUrl === null)
  4714. return;
  4715. var sharedKeyText = "";
  4716. if (sharedKey && sharedKey.length > 0) {
  4717. sharedKeyText =
  4718. APP.translation.translateString("email.sharedKey",
  4719. {sharedKey: sharedKey});
  4720. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4721. }
  4722. var supportedBrowsers = "Chromium, Google Chrome " +
  4723. APP.translation.translateString("email.and") + " Opera";
  4724. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4725. var subject = APP.translation.translateString("email.subject",
  4726. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4727. var body = APP.translation.translateString("email.body",
  4728. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4729. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4730. body = body.replace(/\n/g, "%0D%0A");
  4731. if (window.localStorage.displayname) {
  4732. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4733. }
  4734. if (interfaceConfig.INVITATION_POWERED_BY) {
  4735. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4736. }
  4737. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4738. }
  4739. function dialpadButtonClicked()
  4740. {
  4741. //TODO show the dialpad window
  4742. }
  4743. function callSipButtonClicked()
  4744. {
  4745. var defaultNumber
  4746. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4747. var sipMsg = APP.translation.generateTranslatonHTML(
  4748. "dialog.sipMsg");
  4749. messageHandler.openTwoButtonDialog(null, null, null,
  4750. '<h2>' + sipMsg + '</h2>' +
  4751. '<input name="sipNumber" type="text"' +
  4752. ' value="' + defaultNumber + '" autofocus>',
  4753. false,
  4754. "dialog.Dial",
  4755. function (e, v, m, f) {
  4756. if (v) {
  4757. var numberInput = f.sipNumber;
  4758. if (numberInput) {
  4759. APP.xmpp.dial(
  4760. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4761. }
  4762. }
  4763. },
  4764. null, null, ':input:first'
  4765. );
  4766. }
  4767. var Toolbar = (function (my) {
  4768. my.init = function (ui) {
  4769. for(var k in buttonHandlers)
  4770. $("#" + k).click(buttonHandlers[k]);
  4771. UI = ui;
  4772. // Update login info
  4773. APP.xmpp.addListener(
  4774. AuthenticationEvents.IDENTITY_UPDATED,
  4775. function (authenticationEnabled, userIdentity) {
  4776. var loggedIn = false;
  4777. if (userIdentity) {
  4778. loggedIn = true;
  4779. }
  4780. Toolbar.showAuthenticateButton(authenticationEnabled);
  4781. if (authenticationEnabled) {
  4782. Toolbar.setAuthenticatedIdentity(userIdentity);
  4783. Toolbar.showLoginButton(!loggedIn);
  4784. Toolbar.showLogoutButton(loggedIn);
  4785. }
  4786. }
  4787. );
  4788. },
  4789. /**
  4790. * Sets shared key
  4791. * @param sKey the shared key
  4792. */
  4793. my.setSharedKey = function (sKey) {
  4794. sharedKey = sKey;
  4795. };
  4796. my.authenticateClicked = function () {
  4797. Authentication.focusAuthenticationWindow();
  4798. if (!APP.xmpp.isExternalAuthEnabled()) {
  4799. Authentication.xmppAuthenticate();
  4800. return;
  4801. }
  4802. // Get authentication URL
  4803. if (!APP.xmpp.getMUCJoined()) {
  4804. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4805. // If conference has not been started yet - redirect to login page
  4806. window.location.href = url;
  4807. });
  4808. } else {
  4809. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4810. // Otherwise - open popup with authentication URL
  4811. var authenticationWindow = Authentication.createAuthenticationWindow(
  4812. function () {
  4813. // On popup closed - retry room allocation
  4814. APP.xmpp.allocateConferenceFocus(
  4815. APP.UI.getRoomName(),
  4816. function () { console.info("AUTH DONE"); }
  4817. );
  4818. }, url);
  4819. if (!authenticationWindow) {
  4820. messageHandler.openMessageDialog(
  4821. null, "dialog.popupError");
  4822. }
  4823. });
  4824. }
  4825. };
  4826. /**
  4827. * Updates the room invite url.
  4828. */
  4829. my.updateRoomUrl = function (newRoomUrl) {
  4830. roomUrl = newRoomUrl;
  4831. // If the invite dialog has been already opened we update the information.
  4832. var inviteLink = document.getElementById('inviteLinkRef');
  4833. if (inviteLink) {
  4834. inviteLink.value = roomUrl;
  4835. inviteLink.select();
  4836. $('#inviteLinkRef').parent()
  4837. .find('button[value=true]').prop('disabled', false);
  4838. }
  4839. };
  4840. /**
  4841. * Disables and enables some of the buttons.
  4842. */
  4843. my.setupButtonsFromConfig = function () {
  4844. if (config.disablePrezi)
  4845. {
  4846. $("#prezi_button").css({display: "none"});
  4847. }
  4848. };
  4849. /**
  4850. * Opens the lock room dialog.
  4851. */
  4852. my.openLockDialog = function () {
  4853. // Only the focus is able to set a shared key.
  4854. if (!APP.xmpp.isModerator()) {
  4855. if (sharedKey) {
  4856. messageHandler.openMessageDialog(null,
  4857. "dialog.passwordError");
  4858. } else {
  4859. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4860. }
  4861. } else {
  4862. if (sharedKey) {
  4863. messageHandler.openTwoButtonDialog(null, null,
  4864. "dialog.passwordCheck",
  4865. null,
  4866. false,
  4867. "dialog.Remove",
  4868. function (e, v) {
  4869. if (v) {
  4870. Toolbar.setSharedKey('');
  4871. lockRoom(false);
  4872. }
  4873. });
  4874. } else {
  4875. var msg = APP.translation.generateTranslatonHTML(
  4876. "dialog.passwordMsg");
  4877. var yourPassword = APP.translation.translateString(
  4878. "dialog.yourPassword");
  4879. messageHandler.openTwoButtonDialog(null, null, null,
  4880. '<h2>' + msg + '</h2>' +
  4881. '<input name="lockKey" type="text"' +
  4882. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4883. 'placeholder="' + yourPassword + '" autofocus>',
  4884. false,
  4885. "dialog.Save",
  4886. function (e, v, m, f) {
  4887. if (v) {
  4888. var lockKey = f.lockKey;
  4889. if (lockKey) {
  4890. Toolbar.setSharedKey(
  4891. UIUtil.escapeHtml(lockKey));
  4892. lockRoom(true);
  4893. }
  4894. }
  4895. },
  4896. null, null, 'input:first'
  4897. );
  4898. }
  4899. }
  4900. };
  4901. /**
  4902. * Opens the invite link dialog.
  4903. */
  4904. my.openLinkDialog = function () {
  4905. var inviteAttreibutes;
  4906. if (roomUrl === null) {
  4907. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4908. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4909. } else {
  4910. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4911. }
  4912. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4913. null, null,
  4914. '<input id="inviteLinkRef" type="text" ' +
  4915. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4916. false,
  4917. "dialog.Invite",
  4918. function (e, v) {
  4919. if (v) {
  4920. if (roomUrl) {
  4921. inviteParticipants();
  4922. }
  4923. }
  4924. },
  4925. function (event) {
  4926. if (roomUrl) {
  4927. document.getElementById('inviteLinkRef').select();
  4928. } else {
  4929. if (event && event.target)
  4930. $(event.target)
  4931. .find('button[value=true]').prop('disabled', true);
  4932. }
  4933. }
  4934. );
  4935. };
  4936. /**
  4937. * Opens the settings dialog.
  4938. * FIXME: not used ?
  4939. */
  4940. my.openSettingsDialog = function () {
  4941. var settings1 = APP.translation.generateTranslatonHTML(
  4942. "dialog.settings1");
  4943. var settings2 = APP.translation.generateTranslatonHTML(
  4944. "dialog.settings2");
  4945. var settings3 = APP.translation.generateTranslatonHTML(
  4946. "dialog.settings3");
  4947. var yourPassword = APP.translation.translateString(
  4948. "dialog.yourPassword");
  4949. messageHandler.openTwoButtonDialog(null,
  4950. '<h2>' + settings1 + '</h2>' +
  4951. '<input type="checkbox" id="initMuted">' +
  4952. settings2 + '<br/>' +
  4953. '<input type="checkbox" id="requireNicknames">' +
  4954. settings3 +
  4955. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4956. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4957. null,
  4958. null,
  4959. false,
  4960. "dialog.Save",
  4961. function () {
  4962. document.getElementById('lockKey').focus();
  4963. },
  4964. function (e, v) {
  4965. if (v) {
  4966. if ($('#initMuted').is(":checked")) {
  4967. // it is checked
  4968. }
  4969. if ($('#requireNicknames').is(":checked")) {
  4970. // it is checked
  4971. }
  4972. /*
  4973. var lockKey = document.getElementById('lockKey');
  4974. if (lockKey.value) {
  4975. setSharedKey(lockKey.value);
  4976. lockRoom(true);
  4977. }
  4978. */
  4979. }
  4980. }
  4981. );
  4982. };
  4983. /**
  4984. * Toggles the application in and out of full screen mode
  4985. * (a.k.a. presentation mode in Chrome).
  4986. */
  4987. my.toggleFullScreen = function () {
  4988. var fsElement = document.documentElement;
  4989. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4990. //Enter Full Screen
  4991. if (fsElement.mozRequestFullScreen) {
  4992. fsElement.mozRequestFullScreen();
  4993. }
  4994. else {
  4995. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4996. }
  4997. } else {
  4998. //Exit Full Screen
  4999. if (document.mozCancelFullScreen) {
  5000. document.mozCancelFullScreen();
  5001. } else {
  5002. document.webkitCancelFullScreen();
  5003. }
  5004. }
  5005. };
  5006. /**
  5007. * Unlocks the lock button state.
  5008. */
  5009. my.unlockLockButton = function () {
  5010. if ($("#lockIcon").hasClass("icon-security-locked"))
  5011. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5012. };
  5013. /**
  5014. * Updates the lock button state to locked.
  5015. */
  5016. my.lockLockButton = function () {
  5017. if ($("#lockIcon").hasClass("icon-security"))
  5018. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5019. };
  5020. /**
  5021. * Shows or hides authentication button
  5022. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  5023. */
  5024. my.showAuthenticateButton = function (show) {
  5025. if (show) {
  5026. $('#authentication').css({display: "inline"});
  5027. }
  5028. else {
  5029. $('#authentication').css({display: "none"});
  5030. }
  5031. };
  5032. // Shows or hides the 'recording' button.
  5033. my.showRecordingButton = function (show) {
  5034. if (!config.enableRecording) {
  5035. return;
  5036. }
  5037. if (show) {
  5038. $('#recording').css({display: "inline"});
  5039. }
  5040. else {
  5041. $('#recording').css({display: "none"});
  5042. }
  5043. };
  5044. // Sets the state of the recording button
  5045. my.setRecordingButtonState = function (isRecording) {
  5046. var selector = $('#recordButton');
  5047. if (isRecording) {
  5048. selector.removeClass("icon-recEnable");
  5049. selector.addClass("icon-recEnable active");
  5050. } else {
  5051. selector.removeClass("icon-recEnable active");
  5052. selector.addClass("icon-recEnable");
  5053. }
  5054. };
  5055. // Shows or hides SIP calls button
  5056. my.showSipCallButton = function (show) {
  5057. if (APP.xmpp.isSipGatewayEnabled() && show) {
  5058. $('#sipCallButton').css({display: "inline-block"});
  5059. } else {
  5060. $('#sipCallButton').css({display: "none"});
  5061. }
  5062. };
  5063. // Shows or hides the dialpad button
  5064. my.showDialPadButton = function (show) {
  5065. if (show) {
  5066. $('#dialPadButton').css({display: "inline-block"});
  5067. } else {
  5068. $('#dialPadButton').css({display: "none"});
  5069. }
  5070. };
  5071. /**
  5072. * Displays user authenticated identity name(login).
  5073. * @param authIdentity identity name to be displayed.
  5074. */
  5075. my.setAuthenticatedIdentity = function (authIdentity) {
  5076. if (authIdentity) {
  5077. var selector = $('#toolbar_auth_identity');
  5078. selector.css({display: "list-item"});
  5079. selector.text(authIdentity);
  5080. } else {
  5081. $('#toolbar_auth_identity').css({display: "none"});
  5082. }
  5083. };
  5084. /**
  5085. * Shows/hides login button.
  5086. * @param show <tt>true</tt> to show
  5087. */
  5088. my.showLoginButton = function (show) {
  5089. if (show) {
  5090. $('#toolbar_button_login').css({display: "list-item"});
  5091. } else {
  5092. $('#toolbar_button_login').css({display: "none"});
  5093. }
  5094. };
  5095. /**
  5096. * Shows/hides logout button.
  5097. * @param show <tt>true</tt> to show
  5098. */
  5099. my.showLogoutButton = function (show) {
  5100. if (show) {
  5101. $('#toolbar_button_logout').css({display: "list-item"});
  5102. } else {
  5103. $('#toolbar_button_logout').css({display: "none"});
  5104. }
  5105. };
  5106. /**
  5107. * Sets the state of the button. The button has blue glow if desktop
  5108. * streaming is active.
  5109. * @param active the state of the desktop streaming.
  5110. */
  5111. my.changeDesktopSharingButtonState = function (active) {
  5112. var button = $("#desktopsharing > a");
  5113. if (active)
  5114. {
  5115. button.addClass("glow");
  5116. }
  5117. else
  5118. {
  5119. button.removeClass("glow");
  5120. }
  5121. };
  5122. return my;
  5123. }(Toolbar || {}));
  5124. module.exports = Toolbar;
  5125. },{"../../../service/authentication/AuthenticationEvents":107,"../authentication/Authentication":12,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/SidePanelToggler":18,"../util/MessageHandler":29,"../util/UIUtil":31,"./BottomToolbar":25}],27:[function(require,module,exports){
  5126. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  5127. var toolbarTimeoutObject,
  5128. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  5129. function showDesktopSharingButton() {
  5130. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  5131. $('#desktopsharing').css({display: "inline"});
  5132. } else {
  5133. $('#desktopsharing').css({display: "none"});
  5134. }
  5135. }
  5136. /**
  5137. * Hides the toolbar.
  5138. */
  5139. function hideToolbar() {
  5140. if(config.alwaysVisibleToolbar)
  5141. return;
  5142. var header = $("#header"),
  5143. bottomToolbar = $("#bottomToolbar");
  5144. var isToolbarHover = false;
  5145. header.find('*').each(function () {
  5146. var id = $(this).attr('id');
  5147. if ($("#" + id + ":hover").length > 0) {
  5148. isToolbarHover = true;
  5149. }
  5150. });
  5151. if ($("#bottomToolbar:hover").length > 0) {
  5152. isToolbarHover = true;
  5153. }
  5154. clearTimeout(toolbarTimeoutObject);
  5155. toolbarTimeoutObject = null;
  5156. if (!isToolbarHover) {
  5157. header.hide("slide", { direction: "up", duration: 300});
  5158. $('#subject').animate({top: "-=40"}, 300);
  5159. if ($("#remoteVideos").hasClass("hidden")) {
  5160. bottomToolbar.hide(
  5161. "slide", {direction: "right", duration: 300});
  5162. }
  5163. }
  5164. else {
  5165. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5166. }
  5167. }
  5168. var ToolbarToggler = {
  5169. /**
  5170. * Shows the main toolbar.
  5171. */
  5172. showToolbar: function () {
  5173. var header = $("#header"),
  5174. bottomToolbar = $("#bottomToolbar");
  5175. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  5176. header.show("slide", { direction: "up", duration: 300});
  5177. $('#subject').animate({top: "+=40"}, 300);
  5178. if (!bottomToolbar.is(":visible")) {
  5179. bottomToolbar.show(
  5180. "slide", {direction: "right", duration: 300});
  5181. }
  5182. if (toolbarTimeoutObject) {
  5183. clearTimeout(toolbarTimeoutObject);
  5184. toolbarTimeoutObject = null;
  5185. }
  5186. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5187. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  5188. }
  5189. if (APP.xmpp.isModerator())
  5190. {
  5191. // TODO: Enable settings functionality.
  5192. // Need to uncomment the settings button in index.html.
  5193. // $('#settingsButton').css({visibility:"visible"});
  5194. }
  5195. // Show/hide desktop sharing button
  5196. showDesktopSharingButton();
  5197. },
  5198. /**
  5199. * Docks/undocks the toolbar.
  5200. *
  5201. * @param isDock indicates what operation to perform
  5202. */
  5203. dockToolbar: function (isDock) {
  5204. if (isDock) {
  5205. // First make sure the toolbar is shown.
  5206. if (!$('#header').is(':visible')) {
  5207. this.showToolbar();
  5208. }
  5209. // Then clear the time out, to dock the toolbar.
  5210. if (toolbarTimeoutObject) {
  5211. clearTimeout(toolbarTimeoutObject);
  5212. toolbarTimeoutObject = null;
  5213. }
  5214. }
  5215. else {
  5216. if (!$('#header').is(':visible')) {
  5217. this.showToolbar();
  5218. }
  5219. else {
  5220. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5221. }
  5222. }
  5223. },
  5224. showDesktopSharingButton: showDesktopSharingButton
  5225. };
  5226. module.exports = ToolbarToggler;
  5227. },{}],28:[function(require,module,exports){
  5228. var JitsiPopover = (function () {
  5229. /**
  5230. * Constructs new JitsiPopover and attaches it to the element
  5231. * @param element jquery selector
  5232. * @param options the options for the popover.
  5233. * @constructor
  5234. */
  5235. function JitsiPopover(element, options)
  5236. {
  5237. this.options = {
  5238. skin: "white",
  5239. content: ""
  5240. };
  5241. if(options)
  5242. {
  5243. if(options.skin)
  5244. this.options.skin = options.skin;
  5245. if(options.content)
  5246. this.options.content = options.content;
  5247. }
  5248. this.elementIsHovered = false;
  5249. this.popoverIsHovered = false;
  5250. this.popoverShown = false;
  5251. element.data("jitsi_popover", this);
  5252. this.element = element;
  5253. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5254. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5255. '<div class="jitsiPopupmenuPadding"></div></div>';
  5256. var self = this;
  5257. this.element.on("mouseenter", function () {
  5258. self.elementIsHovered = true;
  5259. self.show();
  5260. }).on("mouseleave", function () {
  5261. self.elementIsHovered = false;
  5262. setTimeout(function () {
  5263. self.hide();
  5264. }, 10);
  5265. });
  5266. }
  5267. /**
  5268. * Shows the popover
  5269. */
  5270. JitsiPopover.prototype.show = function () {
  5271. this.createPopover();
  5272. this.popoverShown = true;
  5273. };
  5274. /**
  5275. * Hides the popover
  5276. */
  5277. JitsiPopover.prototype.hide = function () {
  5278. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5279. {
  5280. this.forceHide();
  5281. }
  5282. };
  5283. /**
  5284. * Hides the popover
  5285. */
  5286. JitsiPopover.prototype.forceHide = function () {
  5287. $(".jitsipopover").remove();
  5288. this.popoverShown = false;
  5289. };
  5290. /**
  5291. * Creates the popover html
  5292. */
  5293. JitsiPopover.prototype.createPopover = function () {
  5294. $("body").append(this.template);
  5295. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5296. var self = this;
  5297. $(".jitsipopover").on("mouseenter", function () {
  5298. self.popoverIsHovered = true;
  5299. }).on("mouseleave", function () {
  5300. self.popoverIsHovered = false;
  5301. self.hide();
  5302. });
  5303. this.refreshPosition();
  5304. };
  5305. /**
  5306. * Refreshes the position of the popover
  5307. */
  5308. JitsiPopover.prototype.refreshPosition = function () {
  5309. $(".jitsipopover").position({
  5310. my: "bottom",
  5311. at: "top",
  5312. collision: "fit",
  5313. of: this.element,
  5314. using: function (position, elements) {
  5315. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5316. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5317. $(".jitsipopover > .arrow").css({left: calcLeft});
  5318. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5319. }
  5320. });
  5321. };
  5322. /**
  5323. * Updates the content of popover.
  5324. * @param content new content
  5325. */
  5326. JitsiPopover.prototype.updateContent = function (content) {
  5327. this.options.content = content;
  5328. if(!this.popoverShown)
  5329. return;
  5330. $(".jitsipopover").remove();
  5331. this.createPopover();
  5332. };
  5333. return JitsiPopover;
  5334. })();
  5335. module.exports = JitsiPopover;
  5336. },{}],29:[function(require,module,exports){
  5337. /* global $, APP, jQuery, toastr */
  5338. var messageHandler = (function(my) {
  5339. /**
  5340. * Shows a message to the user.
  5341. *
  5342. * @param titleString the title of the message
  5343. * @param messageString the text of the message
  5344. */
  5345. my.openMessageDialog = function(titleKey, messageKey) {
  5346. var title = null;
  5347. if(titleKey)
  5348. {
  5349. title = APP.translation.generateTranslatonHTML(titleKey);
  5350. }
  5351. var message = APP.translation.generateTranslatonHTML(messageKey);
  5352. $.prompt(message,
  5353. {
  5354. title: title,
  5355. persistent: false
  5356. }
  5357. );
  5358. };
  5359. /**
  5360. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5361. *
  5362. * @param titleString the title of the message
  5363. * @param msgString the text of the message
  5364. * @param persistent boolean value which determines whether the message is persistent or not
  5365. * @param leftButton the fist button's text
  5366. * @param submitFunction function to be called on submit
  5367. * @param loadedFunction function to be called after the prompt is fully loaded
  5368. * @param closeFunction function to be called after the prompt is closed
  5369. * @param focus optional focus selector or button index to be focused after
  5370. * the dialog is opened
  5371. * @param defaultButton index of default button which will be activated when
  5372. * the user press 'enter'. Indexed from 0.
  5373. */
  5374. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5375. persistent, leftButtonKey, submitFunction, loadedFunction,
  5376. closeFunction, focus, defaultButton)
  5377. {
  5378. var buttons = [];
  5379. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5380. buttons.push({ title: leftButton, value: true});
  5381. var cancelButton
  5382. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5383. buttons.push({title: cancelButton, value: false});
  5384. var message = msgString, title = titleString;
  5385. if (titleKey)
  5386. {
  5387. title = APP.translation.generateTranslatonHTML(titleKey);
  5388. }
  5389. if (msgKey) {
  5390. message = APP.translation.generateTranslatonHTML(msgKey);
  5391. }
  5392. $.prompt(message, {
  5393. title: title,
  5394. persistent: false,
  5395. buttons: buttons,
  5396. defaultButton: defaultButton,
  5397. focus: focus,
  5398. loaded: loadedFunction,
  5399. submit: submitFunction,
  5400. close: closeFunction
  5401. });
  5402. };
  5403. /**
  5404. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5405. *
  5406. * @param titleString the title of the message
  5407. * @param msgString the text of the message
  5408. * @param persistent boolean value which determines whether the message is persistent or not
  5409. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5410. * that will be passed to submitFunction
  5411. * @param submitFunction function to be called on submit
  5412. * @param loadedFunction function to be called after the prompt is fully loaded
  5413. */
  5414. my.openDialog = function (titleString, msgString, persistent, buttons,
  5415. submitFunction, loadedFunction) {
  5416. var args = {
  5417. title: titleString,
  5418. persistent: persistent,
  5419. buttons: buttons,
  5420. defaultButton: 1,
  5421. loaded: loadedFunction,
  5422. submit: submitFunction
  5423. };
  5424. if (persistent) {
  5425. args.closeText = '';
  5426. }
  5427. return new Impromptu(msgString, args);
  5428. };
  5429. /**
  5430. * Closes currently opened dialog.
  5431. */
  5432. my.closeDialog = function () {
  5433. $.prompt.close();
  5434. };
  5435. /**
  5436. * Shows a dialog with different states to the user.
  5437. *
  5438. * @param statesObject object containing all the states of the dialog
  5439. */
  5440. my.openDialogWithStates = function (statesObject, options) {
  5441. return new Impromptu(statesObject, options);
  5442. };
  5443. /**
  5444. * Opens new popup window for given <tt>url</tt> centered over current
  5445. * window.
  5446. *
  5447. * @param url the URL to be displayed in the popup window
  5448. * @param w the width of the popup window
  5449. * @param h the height of the popup window
  5450. * @param onPopupClosed optional callback function called when popup window
  5451. * has been closed.
  5452. *
  5453. * @returns popup window object if opened successfully or undefined
  5454. * in case we failed to open it(popup blocked)
  5455. */
  5456. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5457. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5458. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5459. var popup = window.open(
  5460. url, '_blank',
  5461. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5462. if (popup && onPopupClosed) {
  5463. var pollTimer = window.setInterval(function () {
  5464. if (popup.closed !== false) {
  5465. window.clearInterval(pollTimer);
  5466. onPopupClosed();
  5467. }
  5468. }, 200);
  5469. }
  5470. return popup;
  5471. };
  5472. /**
  5473. * Shows a dialog prompting the user to send an error report.
  5474. *
  5475. * @param titleString the title of the message
  5476. * @param msgString the text of the message
  5477. * @param error the error that is being reported
  5478. */
  5479. my.openReportDialog = function(titleKey, msgKey, error) {
  5480. my.openMessageDialog(titleKey, msgKey);
  5481. console.log(error);
  5482. //FIXME send the error to the server
  5483. };
  5484. /**
  5485. * Shows an error dialog to the user.
  5486. * @param title the title of the message
  5487. * @param message the text of the messafe
  5488. */
  5489. my.showError = function(titleKey, msgKey) {
  5490. if(!titleKey) {
  5491. titleKey = "dialog.oops";
  5492. }
  5493. if(!msgKey)
  5494. {
  5495. msgKey = "dialog.defaultError";
  5496. }
  5497. messageHandler.openMessageDialog(titleKey, msgKey);
  5498. };
  5499. my.notify = function(displayName, displayNameKey,
  5500. cls, messageKey, messageArguments, options) {
  5501. var displayNameSpan = '<span class="nickname" ';
  5502. if(displayName)
  5503. {
  5504. displayNameSpan += ">" + displayName;
  5505. }
  5506. else
  5507. {
  5508. displayNameSpan += "data-i18n='" + displayNameKey +
  5509. "'>" + APP.translation.translateString(displayNameKey);
  5510. }
  5511. displayNameSpan += "</span>";
  5512. toastr.info(
  5513. displayNameSpan + '<br>' +
  5514. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5515. (messageArguments?
  5516. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5517. : "") + ">" +
  5518. APP.translation.translateString(messageKey,
  5519. messageArguments) +
  5520. '</span>', null, options);
  5521. };
  5522. return my;
  5523. }(messageHandler || {}));
  5524. module.exports = messageHandler;
  5525. },{}],30:[function(require,module,exports){
  5526. var UIEvents = require("../../../service/UI/UIEvents");
  5527. var nickname = null;
  5528. var eventEmitter = null;
  5529. var NickanameHandler = {
  5530. init: function (emitter) {
  5531. eventEmitter = emitter;
  5532. var storedDisplayName = window.localStorage.displayname;
  5533. if (storedDisplayName) {
  5534. nickname = storedDisplayName;
  5535. }
  5536. },
  5537. setNickname: function (newNickname) {
  5538. if (!newNickname || nickname === newNickname)
  5539. return;
  5540. nickname = newNickname;
  5541. window.localStorage.displayname = nickname;
  5542. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5543. },
  5544. getNickname: function () {
  5545. return nickname;
  5546. },
  5547. addListener: function (type, listener) {
  5548. eventEmitter.on(type, listener);
  5549. }
  5550. };
  5551. module.exports = NickanameHandler;
  5552. },{"../../../service/UI/UIEvents":106}],31:[function(require,module,exports){
  5553. /**
  5554. * Created by hristo on 12/22/14.
  5555. */
  5556. module.exports = {
  5557. /**
  5558. * Returns the available video width.
  5559. */
  5560. getAvailableVideoWidth: function () {
  5561. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5562. var rightPanelWidth
  5563. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5564. return window.innerWidth - rightPanelWidth;
  5565. },
  5566. /**
  5567. * Changes the style class of the element given by id.
  5568. */
  5569. buttonClick: function(id, classname) {
  5570. $(id).toggleClass(classname); // add the class to the clicked element
  5571. },
  5572. /**
  5573. * Returns the text width for the given element.
  5574. *
  5575. * @param el the element
  5576. */
  5577. getTextWidth: function (el) {
  5578. return (el.clientWidth + 1);
  5579. },
  5580. /**
  5581. * Returns the text height for the given element.
  5582. *
  5583. * @param el the element
  5584. */
  5585. getTextHeight: function (el) {
  5586. return (el.clientHeight + 1);
  5587. },
  5588. /**
  5589. * Plays the sound given by id.
  5590. *
  5591. * @param id the identifier of the audio element.
  5592. */
  5593. playSoundNotification: function (id) {
  5594. document.getElementById(id).play();
  5595. },
  5596. /**
  5597. * Escapes the given text.
  5598. */
  5599. escapeHtml: function (unsafeText) {
  5600. return $('<div/>').text(unsafeText).html();
  5601. },
  5602. imageToGrayScale: function (canvas) {
  5603. var context = canvas.getContext('2d');
  5604. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5605. var pixels = imgData.data;
  5606. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5607. var grayscale
  5608. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5609. pixels[i ] = grayscale; // red
  5610. pixels[i+1] = grayscale; // green
  5611. pixels[i+2] = grayscale; // blue
  5612. // pixels[i+3] is alpha
  5613. }
  5614. // redraw the image in black & white
  5615. context.putImageData(imgData, 0, 0);
  5616. },
  5617. setTooltip: function (element, key, position) {
  5618. element.setAttribute("data-i18n", "[data-content]" + key);
  5619. element.setAttribute("data-toggle", "popover");
  5620. element.setAttribute("data-placement", position);
  5621. element.setAttribute("data-html", true);
  5622. element.setAttribute("data-container", "body");
  5623. }
  5624. };
  5625. },{"../side_pannels/SidePanelToggler":18}],32:[function(require,module,exports){
  5626. var JitsiPopover = require("../util/JitsiPopover");
  5627. /**
  5628. * Constructs new connection indicator.
  5629. * @param videoContainer the video container associated with the indicator.
  5630. * @constructor
  5631. */
  5632. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5633. {
  5634. this.videoContainer = videoContainer;
  5635. this.bandwidth = null;
  5636. this.packetLoss = null;
  5637. this.bitrate = null;
  5638. this.showMoreValue = false;
  5639. this.resolution = null;
  5640. this.transport = [];
  5641. this.popover = null;
  5642. this.jid = jid;
  5643. this.create();
  5644. this.videoLayout = VideoLayout;
  5645. }
  5646. /**
  5647. * Values for the connection quality
  5648. * @type {{98: string,
  5649. * 81: string,
  5650. * 64: string,
  5651. * 47: string,
  5652. * 30: string,
  5653. * 0: string}}
  5654. */
  5655. ConnectionIndicator.connectionQualityValues = {
  5656. 98: "18px", //full
  5657. 81: "15px",//4 bars
  5658. 64: "11px",//3 bars
  5659. 47: "7px",//2 bars
  5660. 30: "3px",//1 bar
  5661. 0: "0px"//empty
  5662. };
  5663. ConnectionIndicator.getIP = function(value)
  5664. {
  5665. return value.substring(0, value.lastIndexOf(":"));
  5666. };
  5667. ConnectionIndicator.getPort = function(value)
  5668. {
  5669. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5670. };
  5671. ConnectionIndicator.getStringFromArray = function (array) {
  5672. var res = "";
  5673. for(var i = 0; i < array.length; i++)
  5674. {
  5675. res += (i === 0? "" : ", ") + array[i];
  5676. }
  5677. return res;
  5678. };
  5679. /**
  5680. * Generates the html content.
  5681. * @returns {string} the html content.
  5682. */
  5683. ConnectionIndicator.prototype.generateText = function () {
  5684. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5685. var translate = APP.translation.translateString;
  5686. if(this.bitrate === null)
  5687. {
  5688. downloadBitrate = "N/A";
  5689. uploadBitrate = "N/A";
  5690. }
  5691. else
  5692. {
  5693. downloadBitrate =
  5694. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5695. uploadBitrate =
  5696. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5697. }
  5698. if(this.packetLoss === null)
  5699. {
  5700. packetLoss = "N/A";
  5701. }
  5702. else
  5703. {
  5704. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5705. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5706. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5707. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5708. }
  5709. var resolutionValue = null;
  5710. if(this.resolution && this.jid != null)
  5711. {
  5712. var keys = Object.keys(this.resolution);
  5713. for(var ssrc in this.resolution)
  5714. {
  5715. resolutionValue = this.resolution[ssrc];
  5716. }
  5717. }
  5718. if(this.jid === null)
  5719. {
  5720. resolution = "";
  5721. if(this.resolution === null || !Object.keys(this.resolution) ||
  5722. Object.keys(this.resolution).length === 0)
  5723. {
  5724. resolution = "N/A";
  5725. }
  5726. else
  5727. for(i in this.resolution)
  5728. {
  5729. resolutionValue = this.resolution[i];
  5730. if(resolutionValue)
  5731. {
  5732. if(resolutionValue.height &&
  5733. resolutionValue.width)
  5734. {
  5735. resolution += (resolution === ""? "" : ", ") +
  5736. resolutionValue.width + "x" +
  5737. resolutionValue.height;
  5738. }
  5739. }
  5740. }
  5741. }
  5742. else if(!resolutionValue ||
  5743. !resolutionValue.height ||
  5744. !resolutionValue.width)
  5745. {
  5746. resolution = "N/A";
  5747. }
  5748. else
  5749. {
  5750. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5751. }
  5752. var result = "<table style='width:100%'>" +
  5753. "<tr>" +
  5754. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5755. translate("connectionindicator.bitrate") + "</span></td>" +
  5756. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5757. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5758. uploadBitrate + "</td>" +
  5759. "</tr><tr>" +
  5760. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5761. translate("connectionindicator.packetloss") + "</span></td>" +
  5762. "<td>" + packetLoss + "</td>" +
  5763. "</tr><tr>" +
  5764. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5765. translate("connectionindicator.resolution") + "</span></td>" +
  5766. "<td>" + resolution + "</td></tr></table>";
  5767. if(this.videoContainer.id == "localVideoContainer") {
  5768. result += "<div class=\"jitsipopover_showmore\" " +
  5769. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5770. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5771. (this.showMoreValue ? "less" : "more") + "'>" +
  5772. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5773. "</div><br />";
  5774. }
  5775. if(this.showMoreValue)
  5776. {
  5777. var downloadBandwidth, uploadBandwidth, transport;
  5778. if(this.bandwidth === null)
  5779. {
  5780. downloadBandwidth = "N/A";
  5781. uploadBandwidth = "N/A";
  5782. }
  5783. else
  5784. {
  5785. downloadBandwidth = this.bandwidth.download?
  5786. this.bandwidth.download + " Kbps" :
  5787. "N/A";
  5788. uploadBandwidth = this.bandwidth.upload?
  5789. this.bandwidth.upload + " Kbps" :
  5790. "N/A";
  5791. }
  5792. if(!this.transport || this.transport.length === 0)
  5793. {
  5794. transport = "<tr>" +
  5795. "<td><span class='jitsipopover_blue' " +
  5796. "data-i18n='connectionindicator.address'>" +
  5797. translate("connectionindicator.address") + "</span></td>" +
  5798. "<td> N/A</td></tr>";
  5799. }
  5800. else
  5801. {
  5802. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5803. for(i = 0; i < this.transport.length; i++)
  5804. {
  5805. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5806. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5807. var localIP =
  5808. ConnectionIndicator.getIP(this.transport[i].localip);
  5809. var localPort =
  5810. ConnectionIndicator.getPort(this.transport[i].localip);
  5811. if(data.remoteIP.indexOf(ip) == -1)
  5812. {
  5813. data.remoteIP.push(ip);
  5814. }
  5815. if(data.remotePort.indexOf(port) == -1)
  5816. {
  5817. data.remotePort.push(port);
  5818. }
  5819. if(data.localIP.indexOf(localIP) == -1)
  5820. {
  5821. data.localIP.push(localIP);
  5822. }
  5823. if(data.localPort.indexOf(localPort) == -1)
  5824. {
  5825. data.localPort.push(localPort);
  5826. }
  5827. }
  5828. var local_address_key = "connectionindicator.localaddress";
  5829. var remote_address_key = "connectionindicator.remoteaddress";
  5830. var localTransport =
  5831. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5832. local_address_key +"' data-i18n-options='" +
  5833. JSON.stringify({count: data.localIP.length}) + "'>" +
  5834. translate(local_address_key, {count: data.localIP.length}) +
  5835. "</span></td><td> " +
  5836. ConnectionIndicator.getStringFromArray(data.localIP) +
  5837. "</td></tr>";
  5838. transport =
  5839. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5840. remote_address_key + "' data-i18n-options='" +
  5841. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5842. translate(remote_address_key,
  5843. {count: data.remoteIP.length}) +
  5844. "</span></td><td> " +
  5845. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5846. "</td></tr>";
  5847. var key_remote = "connectionindicator.remoteport",
  5848. key_local = "connectionindicator.localport";
  5849. transport += "<tr>" +
  5850. "<td>" +
  5851. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5852. "' data-i18n-options='" +
  5853. JSON.stringify({count: this.transport.length}) + "'>" +
  5854. translate(key_remote, {count: this.transport.length}) +
  5855. "</span></td><td>";
  5856. localTransport += "<tr>" +
  5857. "<td>" +
  5858. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5859. "' data-i18n-options='" +
  5860. JSON.stringify({count: this.transport.length}) + "'>" +
  5861. translate(key_local, {count: this.transport.length}) +
  5862. "</span></td><td>";
  5863. transport +=
  5864. ConnectionIndicator.getStringFromArray(data.remotePort);
  5865. localTransport +=
  5866. ConnectionIndicator.getStringFromArray(data.localPort);
  5867. transport += "</td></tr>";
  5868. transport += localTransport + "</td></tr>";
  5869. transport +="<tr>" +
  5870. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5871. translate("connectionindicator.transport") + "</span></td>" +
  5872. "<td>" + this.transport[0].type + "</td></tr>";
  5873. }
  5874. result += "<table style='width:100%'>" +
  5875. "<tr>" +
  5876. "<td>" +
  5877. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5878. translate("connectionindicator.bandwidth") + "</span>" +
  5879. "</td><td>" +
  5880. "<span class='jitsipopover_green'>&darr;</span>" +
  5881. downloadBandwidth +
  5882. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5883. uploadBandwidth + "</td></tr>";
  5884. result += transport + "</table>";
  5885. }
  5886. return result;
  5887. };
  5888. /**
  5889. * Shows or hide the additional information.
  5890. */
  5891. ConnectionIndicator.prototype.showMore = function () {
  5892. this.showMoreValue = !this.showMoreValue;
  5893. this.updatePopoverData();
  5894. };
  5895. function createIcon(classes)
  5896. {
  5897. var icon = document.createElement("span");
  5898. for(var i in classes)
  5899. {
  5900. icon.classList.add(classes[i]);
  5901. }
  5902. icon.appendChild(
  5903. document.createElement("i")).classList.add("icon-connection");
  5904. return icon;
  5905. }
  5906. /**
  5907. * Creates the indicator
  5908. */
  5909. ConnectionIndicator.prototype.create = function () {
  5910. this.connectionIndicatorContainer = document.createElement("div");
  5911. this.connectionIndicatorContainer.className = "connectionindicator";
  5912. this.connectionIndicatorContainer.style.display = "none";
  5913. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5914. this.popover = new JitsiPopover(
  5915. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5916. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5917. APP.translation.translateString("connectionindicator.na") + "</div>",
  5918. skin: "black"});
  5919. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5920. createIcon(["connection", "connection_empty"]));
  5921. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5922. createIcon(["connection", "connection_full"]));
  5923. };
  5924. /**
  5925. * Removes the indicator
  5926. */
  5927. ConnectionIndicator.prototype.remove = function()
  5928. {
  5929. this.connectionIndicatorContainer.remove();
  5930. this.popover.forceHide();
  5931. };
  5932. /**
  5933. * Updates the data of the indicator
  5934. * @param percent the percent of connection quality
  5935. * @param object the statistics data.
  5936. */
  5937. ConnectionIndicator.prototype.updateConnectionQuality =
  5938. function (percent, object) {
  5939. if(percent === null)
  5940. {
  5941. this.connectionIndicatorContainer.style.display = "none";
  5942. this.popover.forceHide();
  5943. return;
  5944. }
  5945. else
  5946. {
  5947. if(this.connectionIndicatorContainer.style.display == "none") {
  5948. this.connectionIndicatorContainer.style.display = "block";
  5949. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5950. }
  5951. }
  5952. this.bandwidth = object.bandwidth;
  5953. this.bitrate = object.bitrate;
  5954. this.packetLoss = object.packetLoss;
  5955. this.transport = object.transport;
  5956. if(object.resolution)
  5957. {
  5958. this.resolution = object.resolution;
  5959. }
  5960. for(var quality in ConnectionIndicator.connectionQualityValues)
  5961. {
  5962. if(percent >= quality)
  5963. {
  5964. this.fullIcon.style.width =
  5965. ConnectionIndicator.connectionQualityValues[quality];
  5966. }
  5967. }
  5968. this.updatePopoverData();
  5969. };
  5970. /**
  5971. * Updates the resolution
  5972. * @param resolution the new resolution
  5973. */
  5974. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5975. this.resolution = resolution;
  5976. this.updatePopoverData();
  5977. };
  5978. /**
  5979. * Updates the content of the popover
  5980. */
  5981. ConnectionIndicator.prototype.updatePopoverData = function () {
  5982. this.popover.updateContent(
  5983. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5984. APP.translation.translateElement($(".connection_info"));
  5985. };
  5986. /**
  5987. * Hides the popover
  5988. */
  5989. ConnectionIndicator.prototype.hide = function () {
  5990. this.popover.forceHide();
  5991. };
  5992. /**
  5993. * Hides the indicator
  5994. */
  5995. ConnectionIndicator.prototype.hideIndicator = function () {
  5996. this.connectionIndicatorContainer.style.display = "none";
  5997. if(this.popover)
  5998. this.popover.forceHide();
  5999. };
  6000. module.exports = ConnectionIndicator;
  6001. },{"../util/JitsiPopover":28}],33:[function(require,module,exports){
  6002. var AudioLevels = require("../audio_levels/AudioLevels");
  6003. var Avatar = require("../avatar/Avatar");
  6004. var Chat = require("../side_pannels/chat/Chat");
  6005. var ContactList = require("../side_pannels/contactlist/ContactList");
  6006. var UIUtil = require("../util/UIUtil");
  6007. var ConnectionIndicator = require("./ConnectionIndicator");
  6008. var NicknameHandler = require("../util/NicknameHandler");
  6009. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  6010. var UIEvents = require("../../../service/UI/UIEvents");
  6011. var currentDominantSpeaker = null;
  6012. var lastNCount = config.channelLastN;
  6013. var localLastNCount = config.channelLastN;
  6014. var localLastNSet = [];
  6015. var lastNEndpointsCache = [];
  6016. var lastNPickupJid = null;
  6017. var largeVideoState = {
  6018. updateInProgress: false,
  6019. newSrc: ''
  6020. };
  6021. var eventEmitter = null;
  6022. /**
  6023. * Currently focused video "src"(displayed in large video).
  6024. * @type {String}
  6025. */
  6026. var focusedVideoInfo = null;
  6027. var mutedAudios = {};
  6028. var flipXLocalVideo = true;
  6029. var currentVideoWidth = null;
  6030. var currentVideoHeight = null;
  6031. var localVideoSrc = null;
  6032. function videoactive( videoelem) {
  6033. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  6034. // ignore mixedmslabela0 and v0
  6035. videoelem.show();
  6036. VideoLayout.resizeThumbnails();
  6037. var videoParent = videoelem.parent();
  6038. var parentResourceJid = null;
  6039. if (videoParent)
  6040. parentResourceJid
  6041. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  6042. // Update the large video to the last added video only if there's no
  6043. // current dominant, focused speaker or prezi playing or update it to
  6044. // the current dominant speaker.
  6045. if ((!focusedVideoInfo &&
  6046. !VideoLayout.getDominantSpeakerResourceJid() &&
  6047. !require("../prezi/Prezi").isPresentationVisible()) ||
  6048. (parentResourceJid &&
  6049. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  6050. VideoLayout.updateLargeVideo(
  6051. APP.RTC.getVideoSrc(videoelem[0]),
  6052. 1,
  6053. parentResourceJid);
  6054. }
  6055. VideoLayout.showModeratorIndicator();
  6056. }
  6057. }
  6058. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  6059. // XXX(gp) so, every call to this function is *always* preceded by a call
  6060. // to the RTC.attachMediaStream() function but that call is *not* followed
  6061. // by an update to the videoSrcToSsrc map!
  6062. //
  6063. // The above way of doing things results in video SRCs that don't correspond
  6064. // to any SSRC for a short period of time (to be more precise, for as long
  6065. // the waitForRemoteVideo takes to complete). This causes problems (see
  6066. // bellow).
  6067. //
  6068. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  6069. // a second time in here and only then update the videoSrcToSsrc map? Why
  6070. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  6071. // is called the first time? I actually do that in the lastN changed event
  6072. // handler because the "orphan" video SRC is causing troubles there. The
  6073. // purpose of this method would then be to fire the "videoactive.jingle".
  6074. //
  6075. // Food for though I guess :-)
  6076. if (selector.removed || !selector.parent().is(":visible")) {
  6077. console.warn("Media removed before had started", selector);
  6078. return;
  6079. }
  6080. if (stream.id === 'mixedmslabel') return;
  6081. if (selector[0].currentTime > 0) {
  6082. APP.RTC.attachMediaStream(selector, stream); // FIXME: why do i have to do this for FF?
  6083. videoactive(selector);
  6084. } else {
  6085. setTimeout(function () {
  6086. waitForRemoteVideo(selector, ssrc, stream, jid);
  6087. }, 250);
  6088. }
  6089. }
  6090. /**
  6091. * Returns an array of the video horizontal and vertical indents,
  6092. * so that if fits its parent.
  6093. *
  6094. * @return an array with 2 elements, the horizontal indent and the vertical
  6095. * indent
  6096. */
  6097. function getCameraVideoPosition(videoWidth,
  6098. videoHeight,
  6099. videoSpaceWidth,
  6100. videoSpaceHeight) {
  6101. // Parent height isn't completely calculated when we position the video in
  6102. // full screen mode and this is why we use the screen height in this case.
  6103. // Need to think it further at some point and implement it properly.
  6104. var isFullScreen = document.fullScreen ||
  6105. document.mozFullScreen ||
  6106. document.webkitIsFullScreen;
  6107. if (isFullScreen)
  6108. videoSpaceHeight = window.innerHeight;
  6109. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6110. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  6111. return [horizontalIndent, verticalIndent];
  6112. }
  6113. /**
  6114. * Returns an array of the video horizontal and vertical indents.
  6115. * Centers horizontally and top aligns vertically.
  6116. *
  6117. * @return an array with 2 elements, the horizontal indent and the vertical
  6118. * indent
  6119. */
  6120. function getDesktopVideoPosition(videoWidth,
  6121. videoHeight,
  6122. videoSpaceWidth,
  6123. videoSpaceHeight) {
  6124. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6125. var verticalIndent = 0;// Top aligned
  6126. return [horizontalIndent, verticalIndent];
  6127. }
  6128. /**
  6129. * Returns an array of the video dimensions, so that it covers the screen.
  6130. * It leaves no empty areas, but some parts of the video might not be visible.
  6131. *
  6132. * @return an array with 2 elements, the video width and the video height
  6133. */
  6134. function getCameraVideoSize(videoWidth,
  6135. videoHeight,
  6136. videoSpaceWidth,
  6137. videoSpaceHeight) {
  6138. if (!videoWidth)
  6139. videoWidth = currentVideoWidth;
  6140. if (!videoHeight)
  6141. videoHeight = currentVideoHeight;
  6142. var aspectRatio = videoWidth / videoHeight;
  6143. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6144. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6145. if (availableWidth / aspectRatio < videoSpaceHeight) {
  6146. availableHeight = videoSpaceHeight;
  6147. availableWidth = availableHeight * aspectRatio;
  6148. }
  6149. if (availableHeight * aspectRatio < videoSpaceWidth) {
  6150. availableWidth = videoSpaceWidth;
  6151. availableHeight = availableWidth / aspectRatio;
  6152. }
  6153. return [availableWidth, availableHeight];
  6154. }
  6155. /**
  6156. * Sets the display name for the given video span id.
  6157. */
  6158. function setDisplayName(videoSpanId, displayName, key) {
  6159. if (!$('#' + videoSpanId).length) {
  6160. console.warn(
  6161. "Unable to set displayName - " + videoSpanId + " does not exist");
  6162. return;
  6163. }
  6164. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  6165. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  6166. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6167. // If we already have a display name for this video.
  6168. if (nameSpan.length > 0) {
  6169. var nameSpanElement = nameSpan.get(0);
  6170. if (nameSpanElement.id === 'localDisplayName' &&
  6171. $('#localDisplayName').text() !== displayName) {
  6172. if (displayName && displayName.length > 0)
  6173. {
  6174. var meHTML = APP.translation.generateTranslatonHTML("me");
  6175. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  6176. }
  6177. else
  6178. $('#localDisplayName').html(defaultLocalDisplayName);
  6179. } else {
  6180. if (displayName && displayName.length > 0)
  6181. {
  6182. $('#' + videoSpanId + '_name').html(displayName);
  6183. }
  6184. else if (key && key.length > 0)
  6185. {
  6186. var nameHtml = APP.translation.generateTranslatonHTML(key);
  6187. $('#' + videoSpanId + '_name').html(nameHtml);
  6188. }
  6189. else
  6190. $('#' + videoSpanId + '_name').text(
  6191. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  6192. }
  6193. } else {
  6194. var editButton = null;
  6195. nameSpan = document.createElement('span');
  6196. nameSpan.className = 'displayname';
  6197. $('#' + videoSpanId)[0].appendChild(nameSpan);
  6198. if (videoSpanId === 'localVideoContainer') {
  6199. editButton = createEditDisplayNameButton();
  6200. if (displayName && displayName.length > 0) {
  6201. var meHTML = APP.translation.generateTranslatonHTML("me");
  6202. nameSpan.innerHTML = displayName + meHTML;
  6203. }
  6204. else
  6205. nameSpan.innerHTML = defaultLocalDisplayName;
  6206. }
  6207. else {
  6208. if (displayName && displayName.length > 0) {
  6209. nameSpan.innerText = displayName;
  6210. }
  6211. else
  6212. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  6213. }
  6214. if (!editButton) {
  6215. nameSpan.id = videoSpanId + '_name';
  6216. } else {
  6217. nameSpan.id = 'localDisplayName';
  6218. $('#' + videoSpanId)[0].appendChild(editButton);
  6219. //translates popover of edit button
  6220. APP.translation.translateElement($("a.displayname"));
  6221. var editableText = document.createElement('input');
  6222. editableText.className = 'displayname';
  6223. editableText.type = 'text';
  6224. editableText.id = 'editDisplayName';
  6225. if (displayName && displayName.length) {
  6226. editableText.value
  6227. = displayName;
  6228. }
  6229. var defaultNickname = APP.translation.translateString(
  6230. "defaultNickname", {name: "Jane Pink"});
  6231. editableText.setAttribute('style', 'display:none;');
  6232. editableText.setAttribute('data-18n',
  6233. '[placeholder]defaultNickname');
  6234. editableText.setAttribute("data-i18n-options",
  6235. JSON.stringify({name: "Jane Pink"}));
  6236. editableText.setAttribute("placeholder", defaultNickname);
  6237. $('#' + videoSpanId)[0].appendChild(editableText);
  6238. $('#localVideoContainer .displayname')
  6239. .bind("click", function (e) {
  6240. e.preventDefault();
  6241. e.stopPropagation();
  6242. $('#localDisplayName').hide();
  6243. $('#editDisplayName').show();
  6244. $('#editDisplayName').focus();
  6245. $('#editDisplayName').select();
  6246. $('#editDisplayName').one("focusout", function (e) {
  6247. VideoLayout.inputDisplayNameHandler(this.value);
  6248. });
  6249. $('#editDisplayName').on('keydown', function (e) {
  6250. if (e.keyCode === 13) {
  6251. e.preventDefault();
  6252. VideoLayout.inputDisplayNameHandler(this.value);
  6253. }
  6254. });
  6255. });
  6256. }
  6257. }
  6258. }
  6259. /**
  6260. * Gets the selector of video thumbnail container for the user identified by
  6261. * given <tt>userJid</tt>
  6262. * @param resourceJid user's Jid for whom we want to get the video container.
  6263. */
  6264. function getParticipantContainer(resourceJid)
  6265. {
  6266. if (!resourceJid)
  6267. return null;
  6268. if (resourceJid === APP.xmpp.myResource())
  6269. return $("#localVideoContainer");
  6270. else
  6271. return $("#participant_" + resourceJid);
  6272. }
  6273. /**
  6274. * Sets the size and position of the given video element.
  6275. *
  6276. * @param video the video element to position
  6277. * @param width the desired video width
  6278. * @param height the desired video height
  6279. * @param horizontalIndent the left and right indent
  6280. * @param verticalIndent the top and bottom indent
  6281. */
  6282. function positionVideo(video,
  6283. width,
  6284. height,
  6285. horizontalIndent,
  6286. verticalIndent) {
  6287. video.width(width);
  6288. video.height(height);
  6289. video.css({ top: verticalIndent + 'px',
  6290. bottom: verticalIndent + 'px',
  6291. left: horizontalIndent + 'px',
  6292. right: horizontalIndent + 'px'});
  6293. }
  6294. /**
  6295. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6296. * given <tt>parentElement</tt>.
  6297. *
  6298. * @param jid the jid indicating the video for which we're adding a menu.
  6299. * @param parentElement the parent element where this menu will be added
  6300. */
  6301. function addRemoteVideoMenu(jid, parentElement) {
  6302. var spanElement = document.createElement('span');
  6303. spanElement.className = 'remotevideomenu';
  6304. parentElement.appendChild(spanElement);
  6305. var menuElement = document.createElement('i');
  6306. menuElement.className = 'fa fa-angle-down';
  6307. menuElement.title = 'Remote user controls';
  6308. spanElement.appendChild(menuElement);
  6309. // <ul class="popupmenu">
  6310. // <li><a href="#">Mute</a></li>
  6311. // <li><a href="#">Eject</a></li>
  6312. // </ul>
  6313. var popupmenuElement = document.createElement('ul');
  6314. popupmenuElement.className = 'popupmenu';
  6315. popupmenuElement.id
  6316. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6317. spanElement.appendChild(popupmenuElement);
  6318. var muteMenuItem = document.createElement('li');
  6319. var muteLinkItem = document.createElement('a');
  6320. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6321. if (!mutedAudios[jid]) {
  6322. muteLinkItem.innerHTML = mutedIndicator +
  6323. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6324. muteLinkItem.className = 'mutelink';
  6325. }
  6326. else {
  6327. muteLinkItem.innerHTML = mutedIndicator +
  6328. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6329. muteLinkItem.className = 'mutelink disabled';
  6330. }
  6331. muteLinkItem.onclick = function(){
  6332. if ($(this).attr('disabled') != undefined) {
  6333. event.preventDefault();
  6334. }
  6335. var isMute = mutedAudios[jid] == true;
  6336. APP.xmpp.setMute(jid, !isMute);
  6337. popupmenuElement.setAttribute('style', 'display:none;');
  6338. if (isMute) {
  6339. this.innerHTML = mutedIndicator +
  6340. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6341. this.className = 'mutelink disabled';
  6342. }
  6343. else {
  6344. this.innerHTML = mutedIndicator +
  6345. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6346. this.className = 'mutelink';
  6347. }
  6348. };
  6349. muteMenuItem.appendChild(muteLinkItem);
  6350. popupmenuElement.appendChild(muteMenuItem);
  6351. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6352. var ejectMenuItem = document.createElement('li');
  6353. var ejectLinkItem = document.createElement('a');
  6354. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6355. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6356. ejectLinkItem.onclick = function(){
  6357. APP.xmpp.eject(jid);
  6358. popupmenuElement.setAttribute('style', 'display:none;');
  6359. };
  6360. ejectMenuItem.appendChild(ejectLinkItem);
  6361. popupmenuElement.appendChild(ejectMenuItem);
  6362. var paddingSpan = document.createElement('span');
  6363. paddingSpan.className = 'popupmenuPadding';
  6364. popupmenuElement.appendChild(paddingSpan);
  6365. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6366. }
  6367. /**
  6368. * Removes remote video menu element from video element identified by
  6369. * given <tt>videoElementId</tt>.
  6370. *
  6371. * @param videoElementId the id of local or remote video element.
  6372. */
  6373. function removeRemoteVideoMenu(videoElementId) {
  6374. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6375. if (menuSpan.length) {
  6376. menuSpan.remove();
  6377. }
  6378. }
  6379. /**
  6380. * Updates the data for the indicator
  6381. * @param id the id of the indicator
  6382. * @param percent the percent for connection quality
  6383. * @param object the data
  6384. */
  6385. function updateStatsIndicator(id, percent, object) {
  6386. if(VideoLayout.connectionIndicators[id])
  6387. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6388. }
  6389. /**
  6390. * Returns an array of the video dimensions, so that it keeps it's aspect
  6391. * ratio and fits available area with it's larger dimension. This method
  6392. * ensures that whole video will be visible and can leave empty areas.
  6393. *
  6394. * @return an array with 2 elements, the video width and the video height
  6395. */
  6396. function getDesktopVideoSize(videoWidth,
  6397. videoHeight,
  6398. videoSpaceWidth,
  6399. videoSpaceHeight) {
  6400. if (!videoWidth)
  6401. videoWidth = currentVideoWidth;
  6402. if (!videoHeight)
  6403. videoHeight = currentVideoHeight;
  6404. var aspectRatio = videoWidth / videoHeight;
  6405. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6406. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6407. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6408. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6409. {
  6410. availableHeight = videoSpaceHeight;
  6411. availableWidth = availableHeight * aspectRatio;
  6412. }
  6413. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6414. {
  6415. availableWidth = videoSpaceWidth;
  6416. availableHeight = availableWidth / aspectRatio;
  6417. }
  6418. return [availableWidth, availableHeight];
  6419. }
  6420. /**
  6421. * Creates the edit display name button.
  6422. *
  6423. * @returns the edit button
  6424. */
  6425. function createEditDisplayNameButton() {
  6426. var editButton = document.createElement('a');
  6427. editButton.className = 'displayname';
  6428. UIUtil.setTooltip(editButton,
  6429. "videothumbnail.editnickname",
  6430. "top");
  6431. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6432. return editButton;
  6433. }
  6434. /**
  6435. * Creates the element indicating the moderator(owner) of the conference.
  6436. *
  6437. * @param parentElement the parent element where the owner indicator will
  6438. * be added
  6439. */
  6440. function createModeratorIndicatorElement(parentElement) {
  6441. var moderatorIndicator = document.createElement('i');
  6442. moderatorIndicator.className = 'fa fa-star';
  6443. parentElement.appendChild(moderatorIndicator);
  6444. UIUtil.setTooltip(parentElement,
  6445. "videothumbnail.moderator",
  6446. "top");
  6447. }
  6448. var VideoLayout = (function (my) {
  6449. my.connectionIndicators = {};
  6450. // By default we use camera
  6451. my.getVideoSize = getCameraVideoSize;
  6452. my.getVideoPosition = getCameraVideoPosition;
  6453. my.init = function (emitter) {
  6454. // Listen for large video size updates
  6455. document.getElementById('largeVideo')
  6456. .addEventListener('loadedmetadata', function (e) {
  6457. currentVideoWidth = this.videoWidth;
  6458. currentVideoHeight = this.videoHeight;
  6459. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6460. });
  6461. eventEmitter = emitter;
  6462. };
  6463. my.isInLastN = function(resource) {
  6464. return lastNCount < 0 // lastN is disabled, return true
  6465. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6466. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6467. };
  6468. my.changeLocalStream = function (stream, isMuted) {
  6469. VideoLayout.changeLocalVideo(stream, isMuted);
  6470. };
  6471. my.changeLocalAudio = function(stream, isMuted) {
  6472. if(isMuted)
  6473. APP.UI.setAudioMuted(true, true);
  6474. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6475. document.getElementById('localAudio').autoplay = true;
  6476. document.getElementById('localAudio').volume = 0;
  6477. };
  6478. my.changeLocalVideo = function(stream, isMuted) {
  6479. // Set default display name.
  6480. setDisplayName('localVideoContainer');
  6481. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6482. VideoLayout.connectionIndicators["localVideoContainer"]
  6483. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6484. }
  6485. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6486. var localVideo = null;
  6487. function localVideoClick(event) {
  6488. event.stopPropagation();
  6489. VideoLayout.handleVideoThumbClicked(
  6490. APP.RTC.getVideoSrc(localVideo),
  6491. false,
  6492. APP.xmpp.myResource());
  6493. }
  6494. $('#localVideoContainer').click(localVideoClick);
  6495. // Add hover handler
  6496. $('#localVideoContainer').hover(
  6497. function() {
  6498. VideoLayout.showDisplayName('localVideoContainer', true);
  6499. },
  6500. function() {
  6501. if (!VideoLayout.isLargeVideoVisible()
  6502. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6503. VideoLayout.showDisplayName('localVideoContainer', false);
  6504. }
  6505. );
  6506. if(isMuted)
  6507. {
  6508. APP.UI.setVideoMute(true);
  6509. return;
  6510. }
  6511. var flipX = true;
  6512. if(stream.videoType == "screen")
  6513. flipX = false;
  6514. var localVideo = document.createElement('video');
  6515. localVideo.id = 'localVideo_' +
  6516. APP.RTC.getStreamID(stream.getOriginalStream());
  6517. localVideo.autoplay = true;
  6518. localVideo.volume = 0; // is it required if audio is separated ?
  6519. localVideo.oncontextmenu = function () { return false; };
  6520. var localVideoContainer = document.getElementById('localVideoWrapper');
  6521. localVideoContainer.appendChild(localVideo);
  6522. var localVideoSelector = $('#' + localVideo.id);
  6523. // Add click handler to both video and video wrapper elements in case
  6524. // there's no video.
  6525. localVideoSelector.click(localVideoClick);
  6526. // Flip video x axis if needed
  6527. flipXLocalVideo = flipX;
  6528. if (flipX) {
  6529. localVideoSelector.addClass("flipVideoX");
  6530. }
  6531. // Attach WebRTC stream
  6532. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  6533. // Add stream ended handler
  6534. stream.getOriginalStream().onended = function () {
  6535. localVideoContainer.removeChild(localVideo);
  6536. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6537. };
  6538. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6539. var myResourceJid = APP.xmpp.myResource();
  6540. VideoLayout.updateLargeVideo(localVideoSrc, 0, myResourceJid);
  6541. };
  6542. my.mucJoined = function () {
  6543. var myResourceJid = APP.xmpp.myResource();
  6544. if (!largeVideoState.userResourceJid)
  6545. VideoLayout.updateLargeVideo(localVideoSrc, 0, myResourceJid, true);
  6546. };
  6547. /**
  6548. * Adds or removes icons for not available camera and microphone.
  6549. * @param resourceJid the jid of user
  6550. * @param devices available devices
  6551. */
  6552. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  6553. if(!devices)
  6554. return;
  6555. var container = null
  6556. if(!resourceJid)
  6557. {
  6558. container = $("#localVideoContainer")[0];
  6559. }
  6560. else
  6561. {
  6562. container = $("#participant_" + resourceJid)[0];
  6563. }
  6564. if(!container)
  6565. return;
  6566. $("#" + container.id + " > .noMic").remove();
  6567. $("#" + container.id + " > .noVideo").remove();
  6568. if(!devices.audio)
  6569. {
  6570. container.appendChild(document.createElement("div")).setAttribute("class","noMic");
  6571. }
  6572. if(!devices.video)
  6573. {
  6574. container.appendChild(document.createElement("div")).setAttribute("class","noVideo");
  6575. }
  6576. if(!devices.audio && !devices.video)
  6577. {
  6578. $("#" + container.id + " > .noMic").css("background-position", "75%");
  6579. $("#" + container.id + " > .noVideo").css("background-position", "25%");
  6580. $("#" + container.id + " > .noVideo").css("background-color", "transparent");
  6581. }
  6582. }
  6583. /**
  6584. * Checks if removed video is currently displayed and tries to display
  6585. * another one instead.
  6586. * @param removedVideoSrc src stream identifier of the video.
  6587. */
  6588. my.updateRemovedVideo = function(removedVideoSrc) {
  6589. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6590. // this is currently displayed as large
  6591. // pick the last visible video in the row
  6592. // if nobody else is left, this picks the local video
  6593. var pick
  6594. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6595. .get(0);
  6596. if (!pick) {
  6597. console.info("Last visible video no longer exists");
  6598. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6599. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6600. // Try local video
  6601. console.info("Fallback to local video...");
  6602. pick = $('#remoteVideos>span>span>video').get(0);
  6603. }
  6604. }
  6605. var src = null, volume = null;
  6606. // mute if localvideo
  6607. if (pick) {
  6608. var container = pick.parentNode;
  6609. src = APP.RTC.getVideoSrc(pick);
  6610. volume = pick.volume;
  6611. } else {
  6612. console.warn("Failed to elect large video");
  6613. container = $('#remoteVideos>span[id!="mixedstream"]:visible:last').get(0);
  6614. }
  6615. var jid = null;
  6616. if(container)
  6617. {
  6618. if(container.id == "localVideoWrapper")
  6619. {
  6620. jid = APP.xmpp.myResource();
  6621. }
  6622. else
  6623. {
  6624. jid = VideoLayout.getPeerContainerResourceJid(container);
  6625. }
  6626. }
  6627. else
  6628. return;
  6629. VideoLayout.updateLargeVideo(src, volume, jid);
  6630. }
  6631. };
  6632. my.onRemoteStreamAdded = function (stream) {
  6633. var container;
  6634. var remotes = document.getElementById('remoteVideos');
  6635. if (stream.peerjid) {
  6636. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6637. container = document.getElementById(
  6638. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6639. } else {
  6640. var id = stream.getOriginalStream().id;
  6641. if (id !== 'mixedmslabel'
  6642. // FIXME: default stream is added always with new focus
  6643. // (to be investigated)
  6644. && id !== 'default') {
  6645. console.error('can not associate stream',
  6646. id,
  6647. 'with a participant');
  6648. // We don't want to add it here since it will cause troubles
  6649. return;
  6650. }
  6651. // FIXME: for the mixed ms we dont need a video -- currently
  6652. container = document.createElement('span');
  6653. container.id = 'mixedstream';
  6654. container.className = 'videocontainer';
  6655. remotes.appendChild(container);
  6656. }
  6657. if (container) {
  6658. VideoLayout.addRemoteStreamElement( container,
  6659. stream.sid,
  6660. stream.getOriginalStream(),
  6661. stream.peerjid,
  6662. stream.ssrc);
  6663. }
  6664. }
  6665. my.getLargeVideoState = function () {
  6666. return largeVideoState;
  6667. };
  6668. /**
  6669. * Updates the large video with the given new video source.
  6670. */
  6671. my.updateLargeVideo = function(newSrc, vol, resourceJid, forceUpdate) {
  6672. console.log('hover in', newSrc, resourceJid);
  6673. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc || forceUpdate) {
  6674. $('#activeSpeaker').css('visibility', 'hidden');
  6675. // Due to the simulcast the localVideoSrc may have changed when the
  6676. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6677. // isVideoSrcDesktop methods will not function correctly.
  6678. //
  6679. // Also, again due to the simulcast, the updateLargeVideo method can
  6680. // be called multiple times almost simultaneously. Therefore, we
  6681. // store the state here and update only once.
  6682. largeVideoState.newSrc = newSrc;
  6683. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6684. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6685. APP.xmpp.findJidFromResource(resourceJid));
  6686. if(largeVideoState.userResourceJid) {
  6687. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6688. } else {
  6689. largeVideoState.oldResourceJid = null;
  6690. }
  6691. largeVideoState.userResourceJid = resourceJid;
  6692. // Screen stream is already rotated
  6693. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6694. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6695. // we want the notification to trigger even if userJid is undefined,
  6696. // or null.
  6697. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6698. largeVideoState.userResourceJid);
  6699. }
  6700. $('#largeVideo').fadeOut(300, function () {
  6701. Avatar.updateActiveSpeakerAvatarSrc(
  6702. APP.xmpp.findJidFromResource(
  6703. largeVideoState.userResourceJid));
  6704. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6705. var videoTransform = document.getElementById('largeVideo')
  6706. .style.webkitTransform;
  6707. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6708. document.getElementById('largeVideo').style.webkitTransform
  6709. = "scaleX(-1)";
  6710. }
  6711. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6712. document.getElementById('largeVideo').style.webkitTransform
  6713. = "none";
  6714. }
  6715. // Change the way we'll be measuring and positioning large video
  6716. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6717. ? getDesktopVideoSize
  6718. : getCameraVideoSize;
  6719. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6720. ? getDesktopVideoPosition
  6721. : getCameraVideoPosition;
  6722. // Only if the large video is currently visible.
  6723. // Disable previous dominant speaker video.
  6724. if (largeVideoState.oldResourceJid) {
  6725. VideoLayout.enableDominantSpeaker(
  6726. largeVideoState.oldResourceJid,
  6727. false);
  6728. }
  6729. // Enable new dominant speaker in the remote videos section.
  6730. if (largeVideoState.userResourceJid) {
  6731. VideoLayout.enableDominantSpeaker(
  6732. largeVideoState.userResourceJid,
  6733. true);
  6734. }
  6735. if (largeVideoState.isVisible) {
  6736. // using "this" should be ok because we're called
  6737. // from within the fadeOut event.
  6738. $(this).fadeIn(300);
  6739. }
  6740. Avatar.showUserAvatar(
  6741. APP.xmpp.findJidFromResource(
  6742. largeVideoState.oldResourceJid));
  6743. });
  6744. } else {
  6745. Avatar.showUserAvatar(
  6746. APP.xmpp.findJidFromResource(
  6747. largeVideoState.userResourceJid));
  6748. }
  6749. };
  6750. my.handleVideoThumbClicked = function(videoSrc,
  6751. noPinnedEndpointChangedEvent,
  6752. resourceJid) {
  6753. // Restore style for previously focused video
  6754. var oldContainer = null;
  6755. if(focusedVideoInfo) {
  6756. var focusResourceJid = focusedVideoInfo.resourceJid;
  6757. oldContainer = getParticipantContainer(focusResourceJid);
  6758. }
  6759. if (oldContainer) {
  6760. oldContainer.removeClass("videoContainerFocused");
  6761. }
  6762. // Unlock current focused.
  6763. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6764. {
  6765. focusedVideoInfo = null;
  6766. var dominantSpeakerVideo = null;
  6767. // Enable the currently set dominant speaker.
  6768. if (currentDominantSpeaker) {
  6769. dominantSpeakerVideo
  6770. = $('#participant_' + currentDominantSpeaker + '>video')
  6771. .get(0);
  6772. if (dominantSpeakerVideo) {
  6773. VideoLayout.updateLargeVideo(
  6774. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6775. 1,
  6776. currentDominantSpeaker);
  6777. }
  6778. }
  6779. if (!noPinnedEndpointChangedEvent) {
  6780. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6781. }
  6782. return;
  6783. }
  6784. // Lock new video
  6785. focusedVideoInfo = {
  6786. src: videoSrc,
  6787. resourceJid: resourceJid
  6788. };
  6789. // Update focused/pinned interface.
  6790. if (resourceJid)
  6791. {
  6792. var container = getParticipantContainer(resourceJid);
  6793. container.addClass("videoContainerFocused");
  6794. if (!noPinnedEndpointChangedEvent) {
  6795. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6796. }
  6797. }
  6798. if ($('#largeVideo').attr('src') === videoSrc &&
  6799. VideoLayout.isLargeVideoOnTop()) {
  6800. return;
  6801. }
  6802. // Triggers a "video.selected" event. The "false" parameter indicates
  6803. // this isn't a prezi.
  6804. $(document).trigger("video.selected", [false]);
  6805. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6806. $('audio').each(function (idx, el) {
  6807. if (el.id.indexOf('mixedmslabel') !== -1) {
  6808. el.volume = 0;
  6809. el.volume = 1;
  6810. }
  6811. });
  6812. };
  6813. /**
  6814. * Positions the large video.
  6815. *
  6816. * @param videoWidth the stream video width
  6817. * @param videoHeight the stream video height
  6818. */
  6819. my.positionLarge = function (videoWidth, videoHeight) {
  6820. var videoSpaceWidth = $('#videospace').width();
  6821. var videoSpaceHeight = window.innerHeight;
  6822. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6823. videoHeight,
  6824. videoSpaceWidth,
  6825. videoSpaceHeight);
  6826. var largeVideoWidth = videoSize[0];
  6827. var largeVideoHeight = videoSize[1];
  6828. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6829. largeVideoHeight,
  6830. videoSpaceWidth,
  6831. videoSpaceHeight);
  6832. var horizontalIndent = videoPosition[0];
  6833. var verticalIndent = videoPosition[1];
  6834. positionVideo($('#largeVideo'),
  6835. largeVideoWidth,
  6836. largeVideoHeight,
  6837. horizontalIndent, verticalIndent);
  6838. };
  6839. /**
  6840. * Shows/hides the large video.
  6841. */
  6842. my.setLargeVideoVisible = function(isVisible) {
  6843. var resourceJid = largeVideoState.userResourceJid;
  6844. if (isVisible) {
  6845. $('#largeVideo').css({visibility: 'visible'});
  6846. $('.watermark').css({visibility: 'visible'});
  6847. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6848. }
  6849. else {
  6850. $('#largeVideo').css({visibility: 'hidden'});
  6851. $('#activeSpeaker').css('visibility', 'hidden');
  6852. $('.watermark').css({visibility: 'hidden'});
  6853. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6854. if(focusedVideoInfo) {
  6855. var focusResourceJid = focusedVideoInfo.resourceJid;
  6856. var oldContainer = getParticipantContainer(focusResourceJid);
  6857. if (oldContainer && oldContainer.length > 0) {
  6858. oldContainer.removeClass("videoContainerFocused");
  6859. }
  6860. focusedVideoInfo = null;
  6861. if(focusResourceJid) {
  6862. Avatar.showUserAvatar(
  6863. APP.xmpp.findJidFromResource(focusResourceJid));
  6864. }
  6865. }
  6866. }
  6867. };
  6868. /**
  6869. * Indicates if the large video is currently visible.
  6870. *
  6871. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6872. */
  6873. my.isLargeVideoVisible = function() {
  6874. return $('#largeVideo').is(':visible');
  6875. };
  6876. my.isLargeVideoOnTop = function () {
  6877. var Etherpad = require("../etherpad/Etherpad");
  6878. var Prezi = require("../prezi/Prezi");
  6879. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6880. };
  6881. /**
  6882. * Checks if container for participant identified by given peerJid exists
  6883. * in the document and creates it eventually.
  6884. *
  6885. * @param peerJid peer Jid to check.
  6886. * @param userId user email or id for setting the avatar
  6887. *
  6888. * @return Returns <tt>true</tt> if the peer container exists,
  6889. * <tt>false</tt> - otherwise
  6890. */
  6891. my.ensurePeerContainerExists = function(peerJid, userId) {
  6892. ContactList.ensureAddContact(peerJid, userId);
  6893. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6894. var videoSpanId = 'participant_' + resourceJid;
  6895. if (!$('#' + videoSpanId).length) {
  6896. var container =
  6897. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6898. Avatar.setUserAvatar(peerJid, userId);
  6899. // Set default display name.
  6900. setDisplayName(videoSpanId);
  6901. VideoLayout.connectionIndicators[videoSpanId] =
  6902. new ConnectionIndicator(container, peerJid, VideoLayout);
  6903. var nickfield = document.createElement('span');
  6904. nickfield.className = "nick";
  6905. nickfield.appendChild(document.createTextNode(resourceJid));
  6906. container.appendChild(nickfield);
  6907. // In case this is not currently in the last n we don't show it.
  6908. if (localLastNCount
  6909. && localLastNCount > 0
  6910. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6911. showPeerContainer(resourceJid, 'hide');
  6912. }
  6913. else
  6914. VideoLayout.resizeThumbnails();
  6915. }
  6916. };
  6917. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6918. var container = document.createElement('span');
  6919. container.id = spanId;
  6920. container.className = 'videocontainer';
  6921. var remotes = document.getElementById('remoteVideos');
  6922. remotes.appendChild(container);
  6923. // If the peerJid is null then this video span couldn't be directly
  6924. // associated with a participant (this could happen in the case of prezi).
  6925. if (APP.xmpp.isModerator() && peerJid !== null)
  6926. addRemoteVideoMenu(peerJid, container);
  6927. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6928. return container;
  6929. };
  6930. /**
  6931. * Creates an audio or video stream element.
  6932. */
  6933. my.createStreamElement = function (sid, stream) {
  6934. var isVideo = stream.getVideoTracks().length > 0;
  6935. var element = isVideo
  6936. ? document.createElement('video')
  6937. : document.createElement('audio');
  6938. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6939. + sid + '_' + APP.RTC.getStreamID(stream);
  6940. element.id = id;
  6941. element.autoplay = true;
  6942. element.oncontextmenu = function () { return false; };
  6943. return element;
  6944. };
  6945. my.addRemoteStreamElement
  6946. = function (container, sid, stream, peerJid, thessrc) {
  6947. var newElementId = null;
  6948. var isVideo = stream.getVideoTracks().length > 0;
  6949. if (container) {
  6950. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6951. newElementId = streamElement.id;
  6952. container.appendChild(streamElement);
  6953. var sel = $('#' + newElementId);
  6954. sel.hide();
  6955. // If the container is currently visible we attach the stream.
  6956. if (!isVideo
  6957. || (container.offsetParent !== null && isVideo)) {
  6958. APP.RTC.attachMediaStream(sel, stream);
  6959. if (isVideo)
  6960. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6961. }
  6962. stream.onended = function () {
  6963. console.log('stream ended', this);
  6964. VideoLayout.removeRemoteStreamElement(
  6965. stream, isVideo, container, newElementId);
  6966. // NOTE(gp) it seems that under certain circumstances, the
  6967. // onended event is not fired and thus the contact list is not
  6968. // updated.
  6969. //
  6970. // The onended event of a stream should be fired when the SSRCs
  6971. // corresponding to that stream are removed from the SDP; but
  6972. // this doesn't seem to always be the case, resulting in ghost
  6973. // contacts.
  6974. //
  6975. // In an attempt to fix the ghost contacts problem, I'm moving
  6976. // the removeContact() method call in app.js, inside the
  6977. // 'muc.left' event handler.
  6978. //if (peerJid)
  6979. // ContactList.removeContact(peerJid);
  6980. };
  6981. // Add click handler.
  6982. container.onclick = function (event) {
  6983. /*
  6984. * FIXME It turns out that videoThumb may not exist (if there is
  6985. * no actual video).
  6986. */
  6987. var videoThumb = $('#' + container.id + '>video').get(0);
  6988. if (videoThumb) {
  6989. VideoLayout.handleVideoThumbClicked(
  6990. APP.RTC.getVideoSrc(videoThumb),
  6991. false,
  6992. Strophe.getResourceFromJid(peerJid));
  6993. }
  6994. event.stopPropagation();
  6995. event.preventDefault();
  6996. return false;
  6997. };
  6998. // Add hover handler
  6999. $(container).hover(
  7000. function() {
  7001. VideoLayout.showDisplayName(container.id, true);
  7002. },
  7003. function() {
  7004. var videoSrc = null;
  7005. if ($('#' + container.id + '>video')
  7006. && $('#' + container.id + '>video').length > 0) {
  7007. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  7008. }
  7009. // If the video has been "pinned" by the user we want to
  7010. // keep the display name on place.
  7011. if (!VideoLayout.isLargeVideoVisible()
  7012. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  7013. VideoLayout.showDisplayName(container.id, false);
  7014. }
  7015. );
  7016. }
  7017. return newElementId;
  7018. };
  7019. /**
  7020. * Removes the remote stream element corresponding to the given stream and
  7021. * parent container.
  7022. *
  7023. * @param stream the stream
  7024. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  7025. * @param container
  7026. */
  7027. my.removeRemoteStreamElement = function (stream, isVideo, container, id) {
  7028. if (!container)
  7029. return;
  7030. var select = null;
  7031. var removedVideoSrc = null;
  7032. if (isVideo) {
  7033. select = $('#' + id);
  7034. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  7035. }
  7036. else
  7037. select = $('#' + container.id + '>audio');
  7038. // Mark video as removed to cancel waiting loop(if video is removed
  7039. // before has started)
  7040. select.removed = true;
  7041. select.remove();
  7042. var audioCount = $('#' + container.id + '>audio').length;
  7043. var videoCount = $('#' + container.id + '>video').length;
  7044. if (!audioCount && !videoCount) {
  7045. console.log("Remove whole user", container.id);
  7046. if(VideoLayout.connectionIndicators[container.id])
  7047. VideoLayout.connectionIndicators[container.id].remove();
  7048. // Remove whole container
  7049. container.remove();
  7050. VideoLayout.resizeThumbnails();
  7051. }
  7052. if (removedVideoSrc)
  7053. VideoLayout.updateRemovedVideo(removedVideoSrc);
  7054. };
  7055. /**
  7056. * Show/hide peer container for the given resourceJid.
  7057. */
  7058. function showPeerContainer(resourceJid, state) {
  7059. var peerContainer = $('#participant_' + resourceJid);
  7060. if (!peerContainer)
  7061. return;
  7062. var isHide = state === 'hide';
  7063. var resizeThumbnails = false;
  7064. if (!isHide) {
  7065. if (!peerContainer.is(':visible')) {
  7066. resizeThumbnails = true;
  7067. peerContainer.show();
  7068. }
  7069. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7070. if (state == 'show')
  7071. {
  7072. // peerContainer.css('-webkit-filter', '');
  7073. Avatar.showUserAvatar(jid, false);
  7074. }
  7075. else // if (state == 'avatar')
  7076. {
  7077. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  7078. Avatar.showUserAvatar(jid, true);
  7079. }
  7080. }
  7081. else if (peerContainer.is(':visible') && isHide)
  7082. {
  7083. resizeThumbnails = true;
  7084. peerContainer.hide();
  7085. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  7086. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  7087. }
  7088. if (resizeThumbnails) {
  7089. VideoLayout.resizeThumbnails();
  7090. }
  7091. // We want to be able to pin a participant from the contact list, even
  7092. // if he's not in the lastN set!
  7093. // ContactList.setClickable(resourceJid, !isHide);
  7094. };
  7095. my.inputDisplayNameHandler = function (name) {
  7096. NicknameHandler.setNickname(name);
  7097. if (!$('#localDisplayName').is(":visible")) {
  7098. if (NicknameHandler.getNickname())
  7099. {
  7100. var meHTML = APP.translation.generateTranslatonHTML("me");
  7101. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  7102. }
  7103. else
  7104. {
  7105. var defaultHTML = APP.translation.generateTranslatonHTML(
  7106. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7107. $('#localDisplayName')
  7108. .html(defaultHTML);
  7109. }
  7110. $('#localDisplayName').show();
  7111. }
  7112. $('#editDisplayName').hide();
  7113. };
  7114. /**
  7115. * Shows/hides the display name on the remote video.
  7116. * @param videoSpanId the identifier of the video span element
  7117. * @param isShow indicates if the display name should be shown or hidden
  7118. */
  7119. my.showDisplayName = function(videoSpanId, isShow) {
  7120. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  7121. if (isShow) {
  7122. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  7123. nameSpan.setAttribute("style", "display:inline-block;");
  7124. }
  7125. else {
  7126. if (nameSpan)
  7127. nameSpan.setAttribute("style", "display:none;");
  7128. }
  7129. };
  7130. /**
  7131. * Shows the presence status message for the given video.
  7132. */
  7133. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  7134. if (!$('#' + videoSpanId).length) {
  7135. // No container
  7136. return;
  7137. }
  7138. var statusSpan = $('#' + videoSpanId + '>span.status');
  7139. if (!statusSpan.length) {
  7140. //Add status span
  7141. statusSpan = document.createElement('span');
  7142. statusSpan.className = 'status';
  7143. statusSpan.id = videoSpanId + '_status';
  7144. $('#' + videoSpanId)[0].appendChild(statusSpan);
  7145. statusSpan = $('#' + videoSpanId + '>span.status');
  7146. }
  7147. // Display status
  7148. if (statusMsg && statusMsg.length) {
  7149. $('#' + videoSpanId + '_status').text(statusMsg);
  7150. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  7151. }
  7152. else {
  7153. // Hide
  7154. statusSpan.get(0).setAttribute("style", "display:none;");
  7155. }
  7156. };
  7157. /**
  7158. * Shows a visual indicator for the moderator of the conference.
  7159. */
  7160. my.showModeratorIndicator = function () {
  7161. var isModerator = APP.xmpp.isModerator();
  7162. if (isModerator) {
  7163. var indicatorSpan = $('#localVideoContainer .focusindicator');
  7164. if (indicatorSpan.children().length === 0)
  7165. {
  7166. createModeratorIndicatorElement(indicatorSpan[0]);
  7167. //translates text in focus indicator
  7168. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  7169. }
  7170. }
  7171. var members = APP.xmpp.getMembers();
  7172. Object.keys(members).forEach(function (jid) {
  7173. if (Strophe.getResourceFromJid(jid) === 'focus') {
  7174. // Skip server side focus
  7175. return;
  7176. }
  7177. var resourceJid = Strophe.getResourceFromJid(jid);
  7178. var videoSpanId = 'participant_' + resourceJid;
  7179. var videoContainer = document.getElementById(videoSpanId);
  7180. if (!videoContainer) {
  7181. console.error("No video container for " + jid);
  7182. return;
  7183. }
  7184. var member = members[jid];
  7185. if (member.role === 'moderator') {
  7186. // Remove menu if peer is moderator
  7187. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  7188. if (menuSpan.length) {
  7189. removeRemoteVideoMenu(videoSpanId);
  7190. }
  7191. // Show moderator indicator
  7192. var indicatorSpan
  7193. = $('#' + videoSpanId + ' .focusindicator');
  7194. if (!indicatorSpan || indicatorSpan.length === 0) {
  7195. indicatorSpan = document.createElement('span');
  7196. indicatorSpan.className = 'focusindicator';
  7197. videoContainer.appendChild(indicatorSpan);
  7198. createModeratorIndicatorElement(indicatorSpan);
  7199. //translates text in focus indicators
  7200. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  7201. }
  7202. } else if (isModerator) {
  7203. // We are moderator, but user is not - add menu
  7204. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7205. addRemoteVideoMenu(
  7206. jid,
  7207. document.getElementById('participant_' + resourceJid));
  7208. }
  7209. }
  7210. });
  7211. };
  7212. /**
  7213. * Shows video muted indicator over small videos.
  7214. */
  7215. my.showVideoIndicator = function(videoSpanId, isMuted) {
  7216. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7217. if (isMuted === 'false') {
  7218. if (videoMutedSpan.length > 0) {
  7219. videoMutedSpan.remove();
  7220. }
  7221. }
  7222. else {
  7223. if(videoMutedSpan.length == 0) {
  7224. videoMutedSpan = document.createElement('span');
  7225. videoMutedSpan.className = 'videoMuted';
  7226. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  7227. var mutedIndicator = document.createElement('i');
  7228. mutedIndicator.className = 'icon-camera-disabled';
  7229. UIUtil.setTooltip(mutedIndicator,
  7230. "videothumbnail.videomute",
  7231. "top");
  7232. videoMutedSpan.appendChild(mutedIndicator);
  7233. //translate texts for muted indicator
  7234. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  7235. }
  7236. VideoLayout.updateMutePosition(videoSpanId);
  7237. }
  7238. };
  7239. my.updateMutePosition = function (videoSpanId) {
  7240. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7241. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  7242. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7243. if(connectionIndicator.length > 0
  7244. && connectionIndicator[0].style.display != "none") {
  7245. audioMutedSpan.css({right: "23px"});
  7246. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7247. }
  7248. else
  7249. {
  7250. audioMutedSpan.css({right: "0px"});
  7251. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7252. }
  7253. }
  7254. /**
  7255. * Shows audio muted indicator over small videos.
  7256. * @param {string} isMuted
  7257. */
  7258. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7259. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7260. if (isMuted === 'false') {
  7261. if (audioMutedSpan.length > 0) {
  7262. audioMutedSpan.popover('hide');
  7263. audioMutedSpan.remove();
  7264. }
  7265. }
  7266. else {
  7267. if(audioMutedSpan.length == 0 ) {
  7268. audioMutedSpan = document.createElement('span');
  7269. audioMutedSpan.className = 'audioMuted';
  7270. UIUtil.setTooltip(audioMutedSpan,
  7271. "videothumbnail.mute",
  7272. "top");
  7273. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7274. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7275. var mutedIndicator = document.createElement('i');
  7276. mutedIndicator.className = 'icon-mic-disabled';
  7277. audioMutedSpan.appendChild(mutedIndicator);
  7278. }
  7279. VideoLayout.updateMutePosition(videoSpanId);
  7280. }
  7281. };
  7282. /*
  7283. * Shows or hides the audio muted indicator over the local thumbnail video.
  7284. * @param {boolean} isMuted
  7285. */
  7286. my.showLocalAudioIndicator = function(isMuted) {
  7287. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7288. };
  7289. /**
  7290. * Resizes the large video container.
  7291. */
  7292. my.resizeLargeVideoContainer = function () {
  7293. Chat.resizeChat();
  7294. var availableHeight = window.innerHeight;
  7295. var availableWidth = UIUtil.getAvailableVideoWidth();
  7296. if (availableWidth < 0 || availableHeight < 0) return;
  7297. $('#videospace').width(availableWidth);
  7298. $('#videospace').height(availableHeight);
  7299. $('#largeVideoContainer').width(availableWidth);
  7300. $('#largeVideoContainer').height(availableHeight);
  7301. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7302. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7303. $('#activeSpeaker').css('top', top);
  7304. VideoLayout.resizeThumbnails();
  7305. };
  7306. /**
  7307. * Resizes thumbnails.
  7308. */
  7309. my.resizeThumbnails = function() {
  7310. var videoSpaceWidth = $('#remoteVideos').width();
  7311. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7312. var width = thumbnailSize[0];
  7313. var height = thumbnailSize[1];
  7314. // size videos so that while keeping AR and max height, we have a
  7315. // nice fit
  7316. $('#remoteVideos').height(height);
  7317. $('#remoteVideos>span').width(width);
  7318. $('#remoteVideos>span').height(height);
  7319. $('.userAvatar').css('left', (width - height) / 2);
  7320. $(document).trigger("remotevideo.resized", [width, height]);
  7321. };
  7322. /**
  7323. * Enables the dominant speaker UI.
  7324. *
  7325. * @param resourceJid the jid indicating the video element to
  7326. * activate/deactivate
  7327. * @param isEnable indicates if the dominant speaker should be enabled or
  7328. * disabled
  7329. */
  7330. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7331. var videoSpanId = null;
  7332. var videoContainerId = null;
  7333. if (resourceJid
  7334. === APP.xmpp.myResource()) {
  7335. videoSpanId = 'localVideoWrapper';
  7336. videoContainerId = 'localVideoContainer';
  7337. }
  7338. else {
  7339. videoSpanId = 'participant_' + resourceJid;
  7340. videoContainerId = videoSpanId;
  7341. }
  7342. var displayName = resourceJid;
  7343. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7344. if (nameSpan.length > 0)
  7345. displayName = nameSpan.html();
  7346. console.log("UI enable dominant speaker",
  7347. displayName,
  7348. resourceJid,
  7349. isEnable);
  7350. videoSpan = document.getElementById(videoContainerId);
  7351. if (!videoSpan) {
  7352. return;
  7353. }
  7354. var video = $('#' + videoSpanId + '>video');
  7355. if (video && video.length > 0) {
  7356. if (isEnable) {
  7357. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7358. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7359. if (!videoSpan.classList.contains("dominantspeaker"))
  7360. videoSpan.classList.add("dominantspeaker");
  7361. }
  7362. else {
  7363. VideoLayout.showDisplayName(videoContainerId, false);
  7364. if (videoSpan.classList.contains("dominantspeaker"))
  7365. videoSpan.classList.remove("dominantspeaker");
  7366. }
  7367. }
  7368. Avatar.showUserAvatar(
  7369. APP.xmpp.findJidFromResource(resourceJid));
  7370. };
  7371. /**
  7372. * Calculates the thumbnail size.
  7373. *
  7374. * @param videoSpaceWidth the width of the video space
  7375. */
  7376. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7377. // Calculate the available height, which is the inner window height minus
  7378. // 39px for the header minus 2px for the delimiter lines on the top and
  7379. // bottom of the large video, minus the 36px space inside the remoteVideos
  7380. // container used for highlighting shadow.
  7381. var availableHeight = 100;
  7382. var numvids = $('#remoteVideos>span:visible').length;
  7383. if (localLastNCount && localLastNCount > 0) {
  7384. numvids = Math.min(localLastNCount + 1, numvids);
  7385. }
  7386. // Remove the 3px borders arround videos and border around the remote
  7387. // videos area and the 4 pixels between the local video and the others
  7388. //TODO: Find out where the 4 pixels come from and remove them
  7389. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7390. var availableWidth = availableWinWidth / numvids;
  7391. var aspectRatio = 16.0 / 9.0;
  7392. var maxHeight = Math.min(160, availableHeight);
  7393. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7394. if (availableHeight < availableWidth / aspectRatio) {
  7395. availableWidth = Math.floor(availableHeight * aspectRatio);
  7396. }
  7397. return [availableWidth, availableHeight];
  7398. };
  7399. /**
  7400. * Updates the remote video menu.
  7401. *
  7402. * @param jid the jid indicating the video for which we're adding a menu.
  7403. * @param isMuted indicates the current mute state
  7404. */
  7405. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7406. var muteMenuItem
  7407. = $('#remote_popupmenu_'
  7408. + Strophe.getResourceFromJid(jid)
  7409. + '>li>a.mutelink');
  7410. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7411. if (muteMenuItem.length) {
  7412. var muteLink = muteMenuItem.get(0);
  7413. if (isMuted === 'true') {
  7414. muteLink.innerHTML = mutedIndicator + ' Muted';
  7415. muteLink.className = 'mutelink disabled';
  7416. }
  7417. else {
  7418. muteLink.innerHTML = mutedIndicator + ' Mute';
  7419. muteLink.className = 'mutelink';
  7420. }
  7421. }
  7422. };
  7423. /**
  7424. * Returns the current dominant speaker resource jid.
  7425. */
  7426. my.getDominantSpeakerResourceJid = function () {
  7427. return currentDominantSpeaker;
  7428. };
  7429. /**
  7430. * Returns the corresponding resource jid to the given peer container
  7431. * DOM element.
  7432. *
  7433. * @return the corresponding resource jid to the given peer container
  7434. * DOM element
  7435. */
  7436. my.getPeerContainerResourceJid = function (containerElement) {
  7437. var i = containerElement.id.indexOf('participant_');
  7438. if (i >= 0)
  7439. return containerElement.id.substring(i + 12);
  7440. };
  7441. /**
  7442. * On contact list item clicked.
  7443. */
  7444. $(ContactList).bind('contactclicked', function(event, jid) {
  7445. if (!jid) {
  7446. return;
  7447. }
  7448. var resource = Strophe.getResourceFromJid(jid);
  7449. var videoContainer = $("#participant_" + resource);
  7450. if (videoContainer.length > 0) {
  7451. var videoThumb = $('video', videoContainer).get(0);
  7452. // It is not always the case that a videoThumb exists (if there is
  7453. // no actual video).
  7454. if (videoThumb) {
  7455. if (videoThumb.src && videoThumb.src != '') {
  7456. // We have a video src, great! Let's update the large video
  7457. // now.
  7458. VideoLayout.handleVideoThumbClicked(
  7459. videoThumb.src,
  7460. false,
  7461. Strophe.getResourceFromJid(jid));
  7462. } else {
  7463. // If we don't have a video src for jid, there's absolutely
  7464. // no point in calling handleVideoThumbClicked; Quite
  7465. // simply, it won't work because it needs an src to attach
  7466. // to the large video.
  7467. //
  7468. // Instead, we trigger the pinned endpoint changed event to
  7469. // let the bridge adjust its lastN set for myjid and store
  7470. // the pinned user in the lastNPickupJid variable to be
  7471. // picked up later by the lastN changed event handler.
  7472. lastNPickupJid = jid;
  7473. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7474. Strophe.getResourceFromJid(jid));
  7475. }
  7476. } else if (jid == APP.xmpp.myJid()) {
  7477. $("#localVideoContainer").click();
  7478. }
  7479. }
  7480. });
  7481. /**
  7482. * On audio muted event.
  7483. */
  7484. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7485. /*
  7486. // FIXME: but focus can not mute in this case ? - check
  7487. if (jid === xmpp.myJid()) {
  7488. // The local mute indicator is controlled locally
  7489. return;
  7490. }*/
  7491. var videoSpanId = null;
  7492. if (jid === APP.xmpp.myJid()) {
  7493. videoSpanId = 'localVideoContainer';
  7494. } else {
  7495. VideoLayout.ensurePeerContainerExists(jid);
  7496. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7497. }
  7498. mutedAudios[jid] = isMuted;
  7499. if (APP.xmpp.isModerator()) {
  7500. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7501. }
  7502. if (videoSpanId)
  7503. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7504. });
  7505. /**
  7506. * On video muted event.
  7507. */
  7508. $(document).bind('videomuted.muc', function (event, jid, value) {
  7509. var isMuted = (value === "true");
  7510. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7511. return;
  7512. Avatar.showUserAvatar(jid, isMuted);
  7513. var videoSpanId = null;
  7514. if (jid === APP.xmpp.myJid()) {
  7515. videoSpanId = 'localVideoContainer';
  7516. } else {
  7517. VideoLayout.ensurePeerContainerExists(jid);
  7518. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7519. }
  7520. if (videoSpanId)
  7521. VideoLayout.showVideoIndicator(videoSpanId, value);
  7522. });
  7523. /**
  7524. * Display name changed.
  7525. */
  7526. my.onDisplayNameChanged =
  7527. function (jid, displayName, status) {
  7528. if (jid === 'localVideoContainer'
  7529. || jid === APP.xmpp.myJid()) {
  7530. setDisplayName('localVideoContainer',
  7531. displayName);
  7532. } else {
  7533. VideoLayout.ensurePeerContainerExists(jid);
  7534. setDisplayName(
  7535. 'participant_' + Strophe.getResourceFromJid(jid),
  7536. displayName,
  7537. status);
  7538. }
  7539. };
  7540. /**
  7541. * On dominant speaker changed event.
  7542. */
  7543. my.onDominantSpeakerChanged = function (resourceJid) {
  7544. // We ignore local user events.
  7545. if (resourceJid === APP.xmpp.myResource())
  7546. return;
  7547. var members = APP.xmpp.getMembers();
  7548. // Update the current dominant speaker.
  7549. if (resourceJid !== currentDominantSpeaker) {
  7550. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7551. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7552. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7553. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7554. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7555. !members[currentJID].displayName)) {
  7556. setDisplayName(oldSpeakerVideoSpanId, null);
  7557. }
  7558. if(resourceJid && (!members || !members[newJID] ||
  7559. !members[newJID].displayName)) {
  7560. setDisplayName(newSpeakerVideoSpanId, null,
  7561. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7562. }
  7563. currentDominantSpeaker = resourceJid;
  7564. } else {
  7565. return;
  7566. }
  7567. // Obtain container for new dominant speaker.
  7568. var container = document.getElementById(
  7569. 'participant_' + resourceJid);
  7570. // Local video will not have container found, but that's ok
  7571. // since we don't want to switch to local video.
  7572. if (container && !focusedVideoInfo)
  7573. {
  7574. var video = container.getElementsByTagName("video");
  7575. // Update the large video if the video source is already available,
  7576. // otherwise wait for the "videoactive.jingle" event.
  7577. if (video.length && video[0].currentTime > 0) {
  7578. VideoLayout.updateLargeVideo(
  7579. APP.RTC.getVideoSrc(video[0]), 1, resourceJid);
  7580. }
  7581. }
  7582. };
  7583. /**
  7584. * On last N change event.
  7585. *
  7586. * @param lastNEndpoints the list of last N endpoints
  7587. * @param endpointsEnteringLastN the list currently entering last N
  7588. * endpoints
  7589. */
  7590. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7591. endpointsEnteringLastN,
  7592. stream) {
  7593. if (lastNCount !== lastNEndpoints.length)
  7594. lastNCount = lastNEndpoints.length;
  7595. lastNEndpointsCache = lastNEndpoints;
  7596. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7597. //
  7598. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7599. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7600. // so E sees them. C is only in E's local LastN set.
  7601. //
  7602. // If F starts talking and LastN = 3, then E should see thumbnails for
  7603. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7604. // enters E's local LastN ejecting C.
  7605. // Increase the local LastN set size, if necessary.
  7606. if (lastNCount > localLastNCount) {
  7607. localLastNCount = lastNCount;
  7608. }
  7609. // Update the local LastN set preserving the order in which the
  7610. // endpoints appeared in the LastN/local LastN set.
  7611. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7612. for (var i = 0; i < localLastNSet.length; i++) {
  7613. if (nextLocalLastNSet.length >= localLastNCount) {
  7614. break;
  7615. }
  7616. var resourceJid = localLastNSet[i];
  7617. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7618. nextLocalLastNSet.push(resourceJid);
  7619. }
  7620. }
  7621. localLastNSet = nextLocalLastNSet;
  7622. var updateLargeVideo = false;
  7623. // Handle LastN/local LastN changes.
  7624. $('#remoteVideos>span').each(function( index, element ) {
  7625. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7626. var isReceived = true;
  7627. if (resourceJid
  7628. && lastNEndpoints.indexOf(resourceJid) < 0
  7629. && localLastNSet.indexOf(resourceJid) < 0) {
  7630. console.log("Remove from last N", resourceJid);
  7631. showPeerContainer(resourceJid, 'hide');
  7632. isReceived = false;
  7633. } else if (resourceJid
  7634. && $('#participant_' + resourceJid).is(':visible')
  7635. && lastNEndpoints.indexOf(resourceJid) < 0
  7636. && localLastNSet.indexOf(resourceJid) >= 0) {
  7637. showPeerContainer(resourceJid, 'avatar');
  7638. isReceived = false;
  7639. }
  7640. if (!isReceived) {
  7641. // resourceJid has dropped out of the server side lastN set, so
  7642. // it is no longer being received. If resourceJid was being
  7643. // displayed in the large video we have to switch to another
  7644. // user.
  7645. var largeVideoResource = largeVideoState.userResourceJid;
  7646. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7647. updateLargeVideo = true;
  7648. }
  7649. }
  7650. });
  7651. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7652. endpointsEnteringLastN = lastNEndpoints;
  7653. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7654. endpointsEnteringLastN.forEach(function (resourceJid) {
  7655. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7656. showPeerContainer(resourceJid, 'show');
  7657. if (!isVisible) {
  7658. console.log("Add to last N", resourceJid);
  7659. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7660. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7661. var sel = $('#participant_' + resourceJid + '>video');
  7662. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  7663. if (lastNPickupJid == mediaStream.peerjid) {
  7664. // Clean up the lastN pickup jid.
  7665. lastNPickupJid = null;
  7666. // Don't fire the events again, they've already
  7667. // been fired in the contact list click handler.
  7668. VideoLayout.handleVideoThumbClicked(
  7669. $(sel).attr('src'),
  7670. false,
  7671. Strophe.getResourceFromJid(mediaStream.peerjid));
  7672. updateLargeVideo = false;
  7673. }
  7674. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7675. }
  7676. })
  7677. }
  7678. // The endpoint that was being shown in the large video has dropped out
  7679. // of the lastN set and there was no lastN pickup jid. We need to update
  7680. // the large video now.
  7681. if (updateLargeVideo) {
  7682. var resource, container, src;
  7683. var myResource
  7684. = APP.xmpp.myResource();
  7685. // Find out which endpoint to show in the large video.
  7686. for (var i = 0; i < lastNEndpoints.length; i++) {
  7687. resource = lastNEndpoints[i];
  7688. if (!resource || resource === myResource)
  7689. continue;
  7690. container = $("#participant_" + resource);
  7691. if (container.length == 0)
  7692. continue;
  7693. src = $('video', container).attr('src');
  7694. if (!src)
  7695. continue;
  7696. // videoSrcToSsrc needs to be update for this call to succeed.
  7697. VideoLayout.updateLargeVideo(src, 1, resource);
  7698. break;
  7699. }
  7700. }
  7701. };
  7702. /**
  7703. * Updates local stats
  7704. * @param percent
  7705. * @param object
  7706. */
  7707. my.updateLocalConnectionStats = function (percent, object) {
  7708. var resolution = null;
  7709. if(object.resolution !== null)
  7710. {
  7711. resolution = object.resolution;
  7712. object.resolution = resolution[APP.xmpp.myJid()];
  7713. delete resolution[APP.xmpp.myJid()];
  7714. }
  7715. updateStatsIndicator("localVideoContainer", percent, object);
  7716. for(var jid in resolution)
  7717. {
  7718. if(resolution[jid] === null)
  7719. continue;
  7720. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7721. if(VideoLayout.connectionIndicators[id])
  7722. {
  7723. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7724. }
  7725. }
  7726. };
  7727. /**
  7728. * Updates remote stats.
  7729. * @param jid the jid associated with the stats
  7730. * @param percent the connection quality percent
  7731. * @param object the stats data
  7732. */
  7733. my.updateConnectionStats = function (jid, percent, object) {
  7734. var resourceJid = Strophe.getResourceFromJid(jid);
  7735. var videoSpanId = 'participant_' + resourceJid;
  7736. updateStatsIndicator(videoSpanId, percent, object);
  7737. };
  7738. /**
  7739. * Removes the connection
  7740. * @param jid
  7741. */
  7742. my.removeConnectionIndicator = function (jid) {
  7743. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7744. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7745. };
  7746. /**
  7747. * Hides the connection indicator
  7748. * @param jid
  7749. */
  7750. my.hideConnectionIndicator = function (jid) {
  7751. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7752. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7753. };
  7754. /**
  7755. * Hides all the indicators
  7756. */
  7757. my.onStatsStop = function () {
  7758. for(var indicator in VideoLayout.connectionIndicators)
  7759. {
  7760. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7761. }
  7762. };
  7763. my.participantLeft = function (jid) {
  7764. // Unlock large video
  7765. var resourceJid = Strophe.getResourceFromJid(jid);
  7766. if (focusedVideoInfo && focusedVideoInfo.resourceJid === resourceJid)
  7767. {
  7768. console.info("Focused video owner has left the conference");
  7769. focusedVideoInfo = null;
  7770. }
  7771. }
  7772. my.onVideoTypeChanged = function (jid) {
  7773. if(jid &&
  7774. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7775. {
  7776. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7777. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7778. ? getDesktopVideoSize
  7779. : getCameraVideoSize;
  7780. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7781. ? getDesktopVideoPosition
  7782. : getCameraVideoPosition;
  7783. VideoLayout.positionLarge(null, null);
  7784. }
  7785. }
  7786. return my;
  7787. }(VideoLayout || {}));
  7788. module.exports = VideoLayout;
  7789. },{"../../../service/RTC/MediaStreamTypes":101,"../../../service/UI/UIEvents":106,"../audio_levels/AudioLevels":10,"../avatar/Avatar":14,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/chat/Chat":19,"../side_pannels/contactlist/ContactList":23,"../util/NicknameHandler":30,"../util/UIUtil":31,"./ConnectionIndicator":32}],34:[function(require,module,exports){
  7790. //var nouns = [
  7791. //];
  7792. var pluralNouns = [
  7793. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7794. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7795. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7796. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7797. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7798. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7799. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7800. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7801. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7802. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7803. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7804. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7805. ];
  7806. //var places = [
  7807. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7808. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7809. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7810. // "Bridge"
  7811. //];
  7812. var verbs = [
  7813. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7814. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7815. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7816. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7817. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7818. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7819. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7820. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7821. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7822. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7823. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7824. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7825. ];
  7826. var adverbs = [
  7827. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7828. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7829. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7830. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7831. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7832. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7833. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7834. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7835. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7836. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7837. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7838. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7839. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7840. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7841. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7842. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7843. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7844. ];
  7845. var adjectives = [
  7846. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7847. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7848. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7849. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7850. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7851. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7852. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7853. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7854. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7855. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7856. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7857. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7858. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7859. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7860. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7861. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7862. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7863. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7864. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7865. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7866. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7867. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7868. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7869. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7870. "Zealous"
  7871. ];
  7872. //var pronouns = [
  7873. //];
  7874. //var conjunctions = [
  7875. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7876. //];
  7877. /*
  7878. * Maps a string (category name) to the array of words from that category.
  7879. */
  7880. var CATEGORIES =
  7881. {
  7882. //"_NOUN_": nouns,
  7883. "_PLURALNOUN_": pluralNouns,
  7884. //"_PLACE_": places,
  7885. "_VERB_": verbs,
  7886. "_ADVERB_": adverbs,
  7887. "_ADJECTIVE_": adjectives
  7888. //"_PRONOUN_": pronouns,
  7889. //"_CONJUNCTION_": conjunctions,
  7890. };
  7891. var PATTERNS = [
  7892. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7893. // BeautifulFungiOrSpaghetti
  7894. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7895. // AmazinglyScaryToy
  7896. //"_ADVERB__ADJECTIVE__NOUN_",
  7897. // NeitherTrashNorRifle
  7898. //"Neither_NOUN_Nor_NOUN_",
  7899. //"Either_NOUN_Or_NOUN_",
  7900. // EitherCopulateOrInvestigate
  7901. //"Either_VERB_Or_VERB_",
  7902. //"Neither_VERB_Nor_VERB_",
  7903. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7904. //"The_ADVERB__ADJECTIVE__NOUN_",
  7905. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7906. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7907. // WolvesComputeBadly
  7908. //"_PLURALNOUN__VERB__ADVERB_",
  7909. // UniteFacilitateAndMerge
  7910. //"_VERB__VERB_And_VERB_",
  7911. //NastyWitchesAtThePub
  7912. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7913. ];
  7914. /*
  7915. * Returns a random element from the array 'arr'
  7916. */
  7917. function randomElement(arr)
  7918. {
  7919. return arr[Math.floor(Math.random() * arr.length)];
  7920. }
  7921. /*
  7922. * Returns true if the string 's' contains one of the
  7923. * template strings.
  7924. */
  7925. function hasTemplate(s)
  7926. {
  7927. for (var template in CATEGORIES){
  7928. if (s.indexOf(template) >= 0){
  7929. return true;
  7930. }
  7931. }
  7932. }
  7933. /**
  7934. * Generates new room name.
  7935. */
  7936. var RoomNameGenerator = {
  7937. generateRoomWithoutSeparator: function()
  7938. {
  7939. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7940. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7941. var name = randomElement(PATTERNS);
  7942. var word;
  7943. while (hasTemplate(name)){
  7944. for (var template in CATEGORIES){
  7945. word = randomElement(CATEGORIES[template]);
  7946. name = name.replace(template, word);
  7947. }
  7948. }
  7949. return name;
  7950. }
  7951. }
  7952. module.exports = RoomNameGenerator;
  7953. },{}],35:[function(require,module,exports){
  7954. var animateTimeout, updateTimeout;
  7955. var RoomNameGenerator = require("./RoomnameGenerator");
  7956. function enter_room()
  7957. {
  7958. var val = $("#enter_room_field").val();
  7959. if(!val) {
  7960. val = $("#enter_room_field").attr("room_name");
  7961. }
  7962. if (val) {
  7963. window.location.pathname = "/" + val;
  7964. }
  7965. }
  7966. function animate(word) {
  7967. var currentVal = $("#enter_room_field").attr("placeholder");
  7968. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7969. animateTimeout = setTimeout(function() {
  7970. animate(word.substring(1, word.length))
  7971. }, 70);
  7972. }
  7973. function update_roomname()
  7974. {
  7975. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7976. $("#enter_room_field").attr("room_name", word);
  7977. $("#enter_room_field").attr("placeholder", "");
  7978. clearTimeout(animateTimeout);
  7979. animate(word);
  7980. updateTimeout = setTimeout(update_roomname, 10000);
  7981. }
  7982. function setupWelcomePage()
  7983. {
  7984. $("#videoconference_page").hide();
  7985. $("#domain_name").text(
  7986. window.location.protocol + "//" + window.location.host + "/");
  7987. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7988. var leftWatermarkDiv
  7989. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7990. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7991. {
  7992. leftWatermarkDiv.css({display: 'block'});
  7993. leftWatermarkDiv.parent().get(0).href
  7994. = interfaceConfig.JITSI_WATERMARK_LINK;
  7995. }
  7996. }
  7997. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7998. var rightWatermarkDiv
  7999. = $("#welcome_page_header div[class='watermark rightwatermark']");
  8000. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  8001. rightWatermarkDiv.css({display: 'block'});
  8002. rightWatermarkDiv.parent().get(0).href
  8003. = interfaceConfig.BRAND_WATERMARK_LINK;
  8004. rightWatermarkDiv.get(0).style.backgroundImage
  8005. = "url(images/rightwatermark.png)";
  8006. }
  8007. }
  8008. if (interfaceConfig.SHOW_POWERED_BY) {
  8009. $("#welcome_page_header>a[class='poweredby']")
  8010. .css({display: 'block'});
  8011. }
  8012. $("#enter_room_button").click(function()
  8013. {
  8014. enter_room();
  8015. });
  8016. $("#enter_room_field").keydown(function (event) {
  8017. if (event.keyCode === 13 /* enter */) {
  8018. enter_room();
  8019. }
  8020. });
  8021. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  8022. var updateTimeout;
  8023. var animateTimeout;
  8024. $("#reload_roomname").click(function () {
  8025. clearTimeout(updateTimeout);
  8026. clearTimeout(animateTimeout);
  8027. update_roomname();
  8028. });
  8029. $("#reload_roomname").show();
  8030. update_roomname();
  8031. }
  8032. $("#disable_welcome").click(function () {
  8033. window.localStorage.welcomePageDisabled
  8034. = $("#disable_welcome").is(":checked");
  8035. });
  8036. }
  8037. module.exports = setupWelcomePage;
  8038. },{"./RoomnameGenerator":34}],36:[function(require,module,exports){
  8039. var params = {};
  8040. function getConfigParamsFromUrl() {
  8041. if(!location.hash)
  8042. return {};
  8043. var hash = location.hash.substr(1);
  8044. var result = {};
  8045. hash.split("&").forEach(function(part) {
  8046. var item = part.split("=");
  8047. result[item[0]] = JSON.parse(
  8048. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  8049. });
  8050. return result;
  8051. }
  8052. params = getConfigParamsFromUrl();
  8053. var URLProcessor = {
  8054. setConfigParametersFromUrl: function () {
  8055. for(var k in params)
  8056. {
  8057. if(typeof k !== "string" || k.indexOf("config.") === -1)
  8058. continue;
  8059. var v = params[k];
  8060. var confKey = k.substr(7);
  8061. if(config[confKey] && typeof config[confKey] !== typeof v)
  8062. {
  8063. console.warn("The type of " + k +
  8064. " is wrong. That parameter won't be updated in config.js.");
  8065. continue;
  8066. }
  8067. config[confKey] = v;
  8068. }
  8069. }
  8070. };
  8071. module.exports = URLProcessor;
  8072. },{}],37:[function(require,module,exports){
  8073. var EventEmitter = require("events");
  8074. var eventEmitter = new EventEmitter();
  8075. var CQEvents = require("../../service/connectionquality/CQEvents");
  8076. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8077. /**
  8078. * local stats
  8079. * @type {{}}
  8080. */
  8081. var stats = {};
  8082. /**
  8083. * remote stats
  8084. * @type {{}}
  8085. */
  8086. var remoteStats = {};
  8087. /**
  8088. * Interval for sending statistics to other participants
  8089. * @type {null}
  8090. */
  8091. var sendIntervalId = null;
  8092. /**
  8093. * Start statistics sending.
  8094. */
  8095. function startSendingStats() {
  8096. sendStats();
  8097. sendIntervalId = setInterval(sendStats, 10000);
  8098. }
  8099. /**
  8100. * Sends statistics to other participants
  8101. */
  8102. function sendStats() {
  8103. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  8104. }
  8105. /**
  8106. * Converts statistics to format for sending through XMPP
  8107. * @param stats the statistics
  8108. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8109. */
  8110. function convertToMUCStats(stats) {
  8111. return {
  8112. "bitrate_download": stats.bitrate.download,
  8113. "bitrate_upload": stats.bitrate.upload,
  8114. "packetLoss_total": stats.packetLoss.total,
  8115. "packetLoss_download": stats.packetLoss.download,
  8116. "packetLoss_upload": stats.packetLoss.upload
  8117. };
  8118. }
  8119. /**
  8120. * Converts statitistics to format used by VideoLayout
  8121. * @param stats
  8122. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8123. */
  8124. function parseMUCStats(stats) {
  8125. return {
  8126. bitrate: {
  8127. download: stats.bitrate_download,
  8128. upload: stats.bitrate_upload
  8129. },
  8130. packetLoss: {
  8131. total: stats.packetLoss_total,
  8132. download: stats.packetLoss_download,
  8133. upload: stats.packetLoss_upload
  8134. }
  8135. };
  8136. }
  8137. var ConnectionQuality = {
  8138. init: function () {
  8139. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8140. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8141. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8142. },
  8143. /**
  8144. * Updates the local statistics
  8145. * @param data new statistics
  8146. */
  8147. updateLocalStats: function (data) {
  8148. stats = data;
  8149. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8150. if (sendIntervalId == null) {
  8151. startSendingStats();
  8152. }
  8153. },
  8154. /**
  8155. * Updates remote statistics
  8156. * @param jid the jid associated with the statistics
  8157. * @param data the statistics
  8158. */
  8159. updateRemoteStats: function (jid, data) {
  8160. if (data == null || data.packetLoss_total == null) {
  8161. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8162. return;
  8163. }
  8164. remoteStats[jid] = parseMUCStats(data);
  8165. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8166. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8167. },
  8168. /**
  8169. * Stops statistics sending.
  8170. */
  8171. stopSendingStats: function () {
  8172. clearInterval(sendIntervalId);
  8173. sendIntervalId = null;
  8174. //notify UI about stopping statistics gathering
  8175. eventEmitter.emit(CQEvents.STOP);
  8176. },
  8177. /**
  8178. * Returns the local statistics.
  8179. */
  8180. getStats: function () {
  8181. return stats;
  8182. },
  8183. addListener: function (type, listener) {
  8184. eventEmitter.on(type, listener);
  8185. }
  8186. };
  8187. module.exports = ConnectionQuality;
  8188. },{"../../service/connectionquality/CQEvents":108,"../../service/xmpp/XMPPEvents":112,"events":62}],38:[function(require,module,exports){
  8189. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8190. getUserMediaWithConstraints */
  8191. /**
  8192. * Indicates that desktop stream is currently in use(for toggle purpose).
  8193. * @type {boolean}
  8194. */
  8195. var isUsingScreenStream = false;
  8196. /**
  8197. * Indicates that switch stream operation is in progress and prevent from
  8198. * triggering new events.
  8199. * @type {boolean}
  8200. */
  8201. var switchInProgress = false;
  8202. /**
  8203. * Method used to get screen sharing stream.
  8204. *
  8205. * @type {function (stream_callback, failure_callback}
  8206. */
  8207. var obtainDesktopStream = null;
  8208. /**
  8209. * Indicates whether desktop sharing extension is installed.
  8210. * @type {boolean}
  8211. */
  8212. var extInstalled = false;
  8213. /**
  8214. * Indicates whether update of desktop sharing extension is required.
  8215. * @type {boolean}
  8216. */
  8217. var extUpdateRequired = false;
  8218. /**
  8219. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8220. * it can be <tt>null</tt>.
  8221. *
  8222. * @type {null|boolean}
  8223. */
  8224. var _desktopSharingEnabled = null;
  8225. var EventEmitter = require("events");
  8226. var eventEmitter = new EventEmitter();
  8227. var DesktopSharingEventTypes
  8228. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8229. /**
  8230. * Method obtains desktop stream from WebRTC 'screen' source.
  8231. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8232. */
  8233. function obtainWebRTCScreen(streamCallback, failCallback) {
  8234. APP.RTC.getUserMediaWithConstraints(
  8235. ['screen'],
  8236. streamCallback,
  8237. failCallback
  8238. );
  8239. }
  8240. /**
  8241. * Constructs inline install URL for Chrome desktop streaming extension.
  8242. * The 'chromeExtensionId' must be defined in config.js.
  8243. * @returns {string}
  8244. */
  8245. function getWebStoreInstallUrl()
  8246. {
  8247. return "https://chrome.google.com/webstore/detail/" +
  8248. config.chromeExtensionId;
  8249. }
  8250. /**
  8251. * Checks whether extension update is required.
  8252. * @param minVersion minimal required version
  8253. * @param extVersion current extension version
  8254. * @returns {boolean}
  8255. */
  8256. function isUpdateRequired(minVersion, extVersion)
  8257. {
  8258. try
  8259. {
  8260. var s1 = minVersion.split('.');
  8261. var s2 = extVersion.split('.');
  8262. var len = Math.max(s1.length, s2.length);
  8263. for (var i = 0; i < len; i++)
  8264. {
  8265. var n1 = 0,
  8266. n2 = 0;
  8267. if (i < s1.length)
  8268. n1 = parseInt(s1[i]);
  8269. if (i < s2.length)
  8270. n2 = parseInt(s2[i]);
  8271. if (isNaN(n1) || isNaN(n2))
  8272. {
  8273. return true;
  8274. }
  8275. else if (n1 !== n2)
  8276. {
  8277. return n1 > n2;
  8278. }
  8279. }
  8280. // will happen if boths version has identical numbers in
  8281. // their components (even if one of them is longer, has more components)
  8282. return false;
  8283. }
  8284. catch (e)
  8285. {
  8286. console.error("Failed to parse extension version", e);
  8287. APP.UI.messageHandler.showError("dialog.error",
  8288. "dialog.detectext");
  8289. return true;
  8290. }
  8291. }
  8292. function checkExtInstalled(callback) {
  8293. if (!chrome.runtime) {
  8294. // No API, so no extension for sure
  8295. callback(false, false);
  8296. return;
  8297. }
  8298. chrome.runtime.sendMessage(
  8299. config.chromeExtensionId,
  8300. { getVersion: true },
  8301. function (response) {
  8302. if (!response || !response.version) {
  8303. // Communication failure - assume that no endpoint exists
  8304. console.warn(
  8305. "Extension not installed?: ", chrome.runtime.lastError);
  8306. callback(false, false);
  8307. return;
  8308. }
  8309. // Check installed extension version
  8310. var extVersion = response.version;
  8311. console.log('Extension version is: ' + extVersion);
  8312. var updateRequired
  8313. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8314. callback(!updateRequired, updateRequired);
  8315. }
  8316. );
  8317. }
  8318. function doGetStreamFromExtension(streamCallback, failCallback) {
  8319. // Sends 'getStream' msg to the extension.
  8320. // Extension id must be defined in the config.
  8321. chrome.runtime.sendMessage(
  8322. config.chromeExtensionId,
  8323. { getStream: true, sources: config.desktopSharingSources },
  8324. function (response) {
  8325. if (!response) {
  8326. failCallback(chrome.runtime.lastError);
  8327. return;
  8328. }
  8329. console.log("Response from extension: " + response);
  8330. if (response.streamId) {
  8331. APP.RTC.getUserMediaWithConstraints(
  8332. ['desktop'],
  8333. function (stream) {
  8334. streamCallback(stream);
  8335. },
  8336. failCallback,
  8337. null, null, null,
  8338. response.streamId);
  8339. } else {
  8340. failCallback("Extension failed to get the stream");
  8341. }
  8342. }
  8343. );
  8344. }
  8345. /**
  8346. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8347. * stream for returned stream token.
  8348. */
  8349. function obtainScreenFromExtension(streamCallback, failCallback) {
  8350. if (extInstalled) {
  8351. doGetStreamFromExtension(streamCallback, failCallback);
  8352. } else {
  8353. if (extUpdateRequired) {
  8354. alert(
  8355. 'Jitsi Desktop Streamer requires update. ' +
  8356. 'Changes will take effect after next Chrome restart.');
  8357. }
  8358. chrome.webstore.install(
  8359. getWebStoreInstallUrl(),
  8360. function (arg) {
  8361. console.log("Extension installed successfully", arg);
  8362. // We need to reload the page in order to get the access to
  8363. // chrome.runtime
  8364. window.location.reload(false);
  8365. },
  8366. function (arg) {
  8367. console.log("Failed to install the extension", arg);
  8368. failCallback(arg);
  8369. APP.UI.messageHandler.showError("dialog.error",
  8370. "dialog.failtoinstall");
  8371. }
  8372. );
  8373. }
  8374. }
  8375. /**
  8376. * Call this method to toggle desktop sharing feature.
  8377. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8378. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8379. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8380. * enabled), pass any other string or nothing in order to disable this
  8381. * feature completely.
  8382. */
  8383. function setDesktopSharing(method) {
  8384. // Check if we are running chrome
  8385. if (!navigator.webkitGetUserMedia) {
  8386. obtainDesktopStream = null;
  8387. console.info("Desktop sharing disabled");
  8388. } else if (method == "ext") {
  8389. obtainDesktopStream = obtainScreenFromExtension;
  8390. console.info("Using Chrome extension for desktop sharing");
  8391. } else if (method == "webrtc") {
  8392. obtainDesktopStream = obtainWebRTCScreen;
  8393. console.info("Using Chrome WebRTC for desktop sharing");
  8394. }
  8395. // Reset enabled cache
  8396. _desktopSharingEnabled = null;
  8397. }
  8398. /**
  8399. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8400. * config.js to support inline installs. Host site must be selected as main
  8401. * website of published extension.
  8402. */
  8403. function initInlineInstalls()
  8404. {
  8405. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8406. }
  8407. function getVideoStreamFailed(error) {
  8408. console.error("Failed to obtain the stream to switch to", error);
  8409. switchInProgress = false;
  8410. isUsingScreenStream = false;
  8411. newStreamCreated(null);
  8412. }
  8413. function getDesktopStreamFailed(error) {
  8414. console.error("Failed to obtain the stream to switch to", error);
  8415. switchInProgress = false;
  8416. }
  8417. function streamSwitchDone() {
  8418. switchInProgress = false;
  8419. eventEmitter.emit(
  8420. DesktopSharingEventTypes.SWITCHING_DONE,
  8421. isUsingScreenStream);
  8422. }
  8423. function newStreamCreated(stream)
  8424. {
  8425. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8426. stream, isUsingScreenStream, streamSwitchDone);
  8427. }
  8428. module.exports = {
  8429. isUsingScreenStream: function () {
  8430. return isUsingScreenStream;
  8431. },
  8432. /**
  8433. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8434. * and enabled.
  8435. */
  8436. isDesktopSharingEnabled: function () {
  8437. if (_desktopSharingEnabled === null) {
  8438. if (obtainDesktopStream === obtainScreenFromExtension) {
  8439. // Parse chrome version
  8440. var userAgent = navigator.userAgent.toLowerCase();
  8441. // We can assume that user agent is chrome, because it's
  8442. // enforced when 'ext' streaming method is set
  8443. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8444. console.log("Chrome version" + userAgent, ver);
  8445. _desktopSharingEnabled = ver >= 34;
  8446. } else {
  8447. _desktopSharingEnabled =
  8448. obtainDesktopStream === obtainWebRTCScreen;
  8449. }
  8450. }
  8451. return _desktopSharingEnabled;
  8452. },
  8453. init: function () {
  8454. setDesktopSharing(config.desktopSharing);
  8455. // Initialize Chrome extension inline installs
  8456. if (config.chromeExtensionId) {
  8457. initInlineInstalls();
  8458. // Check if extension is installed
  8459. checkExtInstalled(function (installed, updateRequired) {
  8460. extInstalled = installed;
  8461. extUpdateRequired = updateRequired;
  8462. console.info(
  8463. "Chrome extension installed: " + extInstalled +
  8464. " updateRequired: " + extUpdateRequired);
  8465. });
  8466. }
  8467. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8468. },
  8469. addListener: function (listener, type)
  8470. {
  8471. eventEmitter.on(type, listener);
  8472. },
  8473. removeListener: function (listener, type) {
  8474. eventEmitter.removeListener(type, listener);
  8475. },
  8476. /*
  8477. * Toggles screen sharing.
  8478. */
  8479. toggleScreenSharing: function () {
  8480. if (switchInProgress || !obtainDesktopStream) {
  8481. console.warn("Switch in progress or no method defined");
  8482. return;
  8483. }
  8484. switchInProgress = true;
  8485. if (!isUsingScreenStream)
  8486. {
  8487. // Switch to desktop stream
  8488. obtainDesktopStream(
  8489. function (stream) {
  8490. // We now use screen stream
  8491. isUsingScreenStream = true;
  8492. // Hook 'ended' event to restore camera
  8493. // when screen stream stops
  8494. stream.addEventListener('ended',
  8495. function (e) {
  8496. if (!switchInProgress && isUsingScreenStream) {
  8497. APP.desktopsharing.toggleScreenSharing();
  8498. }
  8499. }
  8500. );
  8501. newStreamCreated(stream);
  8502. },
  8503. getDesktopStreamFailed);
  8504. } else {
  8505. // Disable screen stream
  8506. APP.RTC.getUserMediaWithConstraints(
  8507. ['video'],
  8508. function (stream) {
  8509. // We are now using camera stream
  8510. isUsingScreenStream = false;
  8511. newStreamCreated(stream);
  8512. },
  8513. getVideoStreamFailed, config.resolution || '360'
  8514. );
  8515. }
  8516. }
  8517. };
  8518. },{"../../service/desktopsharing/DesktopSharingEventTypes":109,"events":62}],39:[function(require,module,exports){
  8519. //maps keycode to character, id of popover for given function and function
  8520. var shortcuts = {
  8521. 67: {
  8522. character: "C",
  8523. id: "toggleChatPopover",
  8524. function: APP.UI.toggleChat
  8525. },
  8526. 70: {
  8527. character: "F",
  8528. id: "filmstripPopover",
  8529. function: APP.UI.toggleFilmStrip
  8530. },
  8531. 77: {
  8532. character: "M",
  8533. id: "mutePopover",
  8534. function: APP.UI.toggleAudio
  8535. },
  8536. 84: {
  8537. character: "T",
  8538. function: function() {
  8539. if(!APP.RTC.localAudio.isMuted()) {
  8540. APP.UI.toggleAudio();
  8541. }
  8542. }
  8543. },
  8544. 86: {
  8545. character: "V",
  8546. id: "toggleVideoPopover",
  8547. function: APP.UI.toggleVideo
  8548. }
  8549. };
  8550. var KeyboardShortcut = {
  8551. init: function () {
  8552. window.onkeyup = function(e) {
  8553. var keycode = e.which;
  8554. if(!($(":focus").is("input[type=text]") ||
  8555. $(":focus").is("input[type=password]") ||
  8556. $(":focus").is("textarea"))) {
  8557. if (typeof shortcuts[keycode] === "object") {
  8558. shortcuts[keycode].function();
  8559. }
  8560. else if (keycode >= "0".charCodeAt(0) &&
  8561. keycode <= "9".charCodeAt(0)) {
  8562. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8563. }
  8564. //esc while the smileys are visible hides them
  8565. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8566. APP.UI.toggleSmileys();
  8567. }
  8568. };
  8569. window.onkeydown = function(e) {
  8570. if(!($(":focus").is("input[type=text]") ||
  8571. $(":focus").is("input[type=password]") ||
  8572. $(":focus").is("textarea"))) {
  8573. if(e.which === "T".charCodeAt(0)) {
  8574. if(APP.RTC.localAudio.isMuted()) {
  8575. APP.UI.toggleAudio();
  8576. }
  8577. }
  8578. }
  8579. };
  8580. var self = this;
  8581. $('body').popover({ selector: '[data-toggle=popover]',
  8582. trigger: 'click hover',
  8583. content: function() {
  8584. return this.getAttribute("content") +
  8585. self.getShortcut(this.getAttribute("shortcut"));
  8586. }
  8587. });
  8588. },
  8589. /**
  8590. *
  8591. * @param id indicates the popover associated with the shortcut
  8592. * @returns {string} the keyboard shortcut used for the id given
  8593. */
  8594. getShortcut: function (id) {
  8595. for (var keycode in shortcuts) {
  8596. if (shortcuts.hasOwnProperty(keycode)) {
  8597. if (shortcuts[keycode].id === id) {
  8598. return " (" + shortcuts[keycode].character + ")";
  8599. }
  8600. }
  8601. }
  8602. return "";
  8603. }
  8604. };
  8605. module.exports = KeyboardShortcut;
  8606. },{}],40:[function(require,module,exports){
  8607. /* global APP */
  8608. /**
  8609. * This module is meant to (eventually) contain and manage all information
  8610. * about members/participants of the conference, so that other modules don't
  8611. * have to do it on their own, and so that other modules can access members'
  8612. * information from a single place.
  8613. *
  8614. * Currently this module only manages information about the support of jingle
  8615. * DTMF of the members. Other fields, as well as accessor methods are meant to
  8616. * be added as needed.
  8617. */
  8618. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8619. var Events = require("../../service/members/Events");
  8620. var EventEmitter = require("events");
  8621. var eventEmitter = new EventEmitter();
  8622. /**
  8623. * The actual container.
  8624. */
  8625. var members = {};
  8626. /**
  8627. * There is at least one member that supports DTMF (i.e. is jigasi).
  8628. */
  8629. var atLeastOneDtmf = false;
  8630. function registerListeners() {
  8631. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  8632. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  8633. }
  8634. /**
  8635. * Handles a new member joining the MUC.
  8636. */
  8637. function onMucMemberJoined(jid, id, displayName) {
  8638. var member = {
  8639. displayName: displayName
  8640. };
  8641. APP.xmpp.getConnection().disco.info(
  8642. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  8643. members[jid] = member;
  8644. }
  8645. /**
  8646. * Handles a member leaving the MUC.
  8647. */
  8648. function onMucMemberLeft(jid) {
  8649. delete members[jid];
  8650. updateAtLeastOneDtmf();
  8651. }
  8652. /**
  8653. * Handles the reception of a disco#info packet from a particular JID.
  8654. * @param jid the JID sending the packet.
  8655. * @param iq the packet.
  8656. */
  8657. function onDiscoInfoReceived(jid, iq) {
  8658. if (!members[jid])
  8659. return;
  8660. var supportsDtmf
  8661. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  8662. updateDtmf(jid, supportsDtmf);
  8663. }
  8664. /**
  8665. * Updates the 'supportsDtmf' field for a member.
  8666. * @param jid the jid of the member.
  8667. * @param newValue the new value for the 'supportsDtmf' field.
  8668. */
  8669. function updateDtmf(jid, newValue) {
  8670. var oldValue = members[jid].supportsDtmf;
  8671. members[jid].supportsDtmf = newValue;
  8672. if (newValue != oldValue) {
  8673. updateAtLeastOneDtmf();
  8674. }
  8675. }
  8676. /**
  8677. * Checks each member's 'supportsDtmf' field and updates
  8678. * 'atLastOneSupportsDtmf'.
  8679. */
  8680. function updateAtLeastOneDtmf(){
  8681. var newAtLeastOneDtmf = false;
  8682. for (var key in members) {
  8683. if (typeof members[key].supportsDtmf !== 'undefined'
  8684. && members[key].supportsDtmf) {
  8685. newAtLeastOneDtmf= true;
  8686. break;
  8687. }
  8688. }
  8689. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  8690. atLeastOneDtmf = newAtLeastOneDtmf;
  8691. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  8692. }
  8693. }
  8694. /**
  8695. * Exported interface.
  8696. */
  8697. var Members = {
  8698. start: function(){
  8699. registerListeners();
  8700. },
  8701. addListener: function(type, listener)
  8702. {
  8703. eventEmitter.on(type, listener);
  8704. },
  8705. removeListener: function (type, listener) {
  8706. eventEmitter.removeListener(type, listener);
  8707. },
  8708. size: function () {
  8709. return Object.keys(members).length;
  8710. },
  8711. getMembers: function () {
  8712. return members;
  8713. }
  8714. };
  8715. module.exports = Members;
  8716. },{"../../service/members/Events":110,"../../service/xmpp/XMPPEvents":112,"events":62}],41:[function(require,module,exports){
  8717. var email = '';
  8718. var displayName = '';
  8719. var userId;
  8720. var language = null;
  8721. function supportsLocalStorage() {
  8722. try {
  8723. return 'localStorage' in window && window.localStorage !== null;
  8724. } catch (e) {
  8725. console.log("localstorage is not supported");
  8726. return false;
  8727. }
  8728. }
  8729. function generateUniqueId() {
  8730. function _p8() {
  8731. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8732. }
  8733. return _p8() + _p8() + _p8() + _p8();
  8734. }
  8735. if (supportsLocalStorage()) {
  8736. if (!window.localStorage.jitsiMeetId) {
  8737. window.localStorage.jitsiMeetId = generateUniqueId();
  8738. console.log("generated id", window.localStorage.jitsiMeetId);
  8739. }
  8740. userId = window.localStorage.jitsiMeetId || '';
  8741. email = window.localStorage.email || '';
  8742. displayName = window.localStorage.displayname || '';
  8743. language = window.localStorage.language;
  8744. } else {
  8745. console.log("local storage is not supported");
  8746. userId = generateUniqueId();
  8747. }
  8748. var Settings =
  8749. {
  8750. setDisplayName: function (newDisplayName) {
  8751. displayName = newDisplayName;
  8752. window.localStorage.displayname = displayName;
  8753. return displayName;
  8754. },
  8755. setEmail: function (newEmail)
  8756. {
  8757. email = newEmail;
  8758. window.localStorage.email = newEmail;
  8759. return email;
  8760. },
  8761. getSettings: function () {
  8762. return {
  8763. email: email,
  8764. displayName: displayName,
  8765. uid: userId,
  8766. language: language
  8767. };
  8768. },
  8769. setLanguage: function (lang) {
  8770. language = lang;
  8771. window.localStorage.language = lang;
  8772. }
  8773. };
  8774. module.exports = Settings;
  8775. },{}],42:[function(require,module,exports){
  8776. /**
  8777. * Provides statistics for the local stream.
  8778. */
  8779. /**
  8780. * Size of the webaudio analizer buffer.
  8781. * @type {number}
  8782. */
  8783. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  8784. /**
  8785. * Value of the webaudio analizer smoothing time parameter.
  8786. * @type {number}
  8787. */
  8788. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  8789. /**
  8790. * Converts time domain data array to audio level.
  8791. * @param array the time domain data array.
  8792. * @returns {number} the audio level
  8793. */
  8794. function timeDomainDataToAudioLevel(samples) {
  8795. var maxVolume = 0;
  8796. var length = samples.length;
  8797. for (var i = 0; i < length; i++) {
  8798. if (maxVolume < samples[i])
  8799. maxVolume = samples[i];
  8800. }
  8801. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  8802. };
  8803. /**
  8804. * Animates audio level change
  8805. * @param newLevel the new audio level
  8806. * @param lastLevel the last audio level
  8807. * @returns {Number} the audio level to be set
  8808. */
  8809. function animateLevel(newLevel, lastLevel)
  8810. {
  8811. var value = 0;
  8812. var diff = lastLevel - newLevel;
  8813. if(diff > 0.2)
  8814. {
  8815. value = lastLevel - 0.2;
  8816. }
  8817. else if(diff < -0.4)
  8818. {
  8819. value = lastLevel + 0.4;
  8820. }
  8821. else
  8822. {
  8823. value = newLevel;
  8824. }
  8825. return parseFloat(value.toFixed(3));
  8826. }
  8827. /**
  8828. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  8829. *
  8830. * @param stream the local stream
  8831. * @param interval stats refresh interval given in ms.
  8832. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  8833. * update.
  8834. * @constructor
  8835. */
  8836. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  8837. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  8838. this.stream = stream;
  8839. this.intervalId = null;
  8840. this.intervalMilis = interval;
  8841. this.eventEmitter = eventEmitter;
  8842. this.audioLevel = 0;
  8843. this.statisticsService = statisticsService;
  8844. }
  8845. /**
  8846. * Starts the collecting the statistics.
  8847. */
  8848. LocalStatsCollector.prototype.start = function () {
  8849. if (config.disableAudioLevels || !window.AudioContext)
  8850. return;
  8851. var context = new AudioContext();
  8852. var analyser = context.createAnalyser();
  8853. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  8854. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  8855. var source = context.createMediaStreamSource(this.stream);
  8856. source.connect(analyser);
  8857. var self = this;
  8858. this.intervalId = setInterval(
  8859. function () {
  8860. var array = new Uint8Array(analyser.frequencyBinCount);
  8861. analyser.getByteTimeDomainData(array);
  8862. var audioLevel = timeDomainDataToAudioLevel(array);
  8863. if(audioLevel != self.audioLevel) {
  8864. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  8865. self.eventEmitter.emit(
  8866. "statistics.audioLevel",
  8867. self.statisticsService.LOCAL_JID,
  8868. self.audioLevel);
  8869. }
  8870. },
  8871. this.intervalMilis
  8872. );
  8873. };
  8874. /**
  8875. * Stops collecting the statistics.
  8876. */
  8877. LocalStatsCollector.prototype.stop = function () {
  8878. if (this.intervalId) {
  8879. clearInterval(this.intervalId);
  8880. this.intervalId = null;
  8881. }
  8882. };
  8883. module.exports = LocalStatsCollector;
  8884. },{}],43:[function(require,module,exports){
  8885. /* global ssrc2jid */
  8886. /* jshint -W117 */
  8887. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  8888. /**
  8889. * Calculates packet lost percent using the number of lost packets and the
  8890. * number of all packet.
  8891. * @param lostPackets the number of lost packets
  8892. * @param totalPackets the number of all packets.
  8893. * @returns {number} packet loss percent
  8894. */
  8895. function calculatePacketLoss(lostPackets, totalPackets) {
  8896. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  8897. return 0;
  8898. return Math.round((lostPackets/totalPackets)*100);
  8899. }
  8900. function getStatValue(item, name) {
  8901. if(!keyMap[APP.RTC.getBrowserType()][name])
  8902. throw "The property isn't supported!";
  8903. var key = keyMap[APP.RTC.getBrowserType()][name];
  8904. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  8905. }
  8906. /**
  8907. * Peer statistics data holder.
  8908. * @constructor
  8909. */
  8910. function PeerStats()
  8911. {
  8912. this.ssrc2Loss = {};
  8913. this.ssrc2AudioLevel = {};
  8914. this.ssrc2bitrate = {};
  8915. this.ssrc2resolution = {};
  8916. }
  8917. /**
  8918. * The bandwidth
  8919. * @type {{}}
  8920. */
  8921. PeerStats.bandwidth = {};
  8922. /**
  8923. * The bit rate
  8924. * @type {{}}
  8925. */
  8926. PeerStats.bitrate = {};
  8927. /**
  8928. * The packet loss rate
  8929. * @type {{}}
  8930. */
  8931. PeerStats.packetLoss = null;
  8932. /**
  8933. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  8934. * represented by this instance.
  8935. * @param ssrc audio or video RTP stream SSRC.
  8936. * @param lossRate new packet loss rate value to be set.
  8937. */
  8938. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  8939. {
  8940. this.ssrc2Loss[ssrc] = lossRate;
  8941. };
  8942. /**
  8943. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  8944. * represented by this instance.
  8945. * @param ssrc audio or video RTP stream SSRC.
  8946. * @param resolution new resolution value to be set.
  8947. */
  8948. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  8949. {
  8950. if(resolution === null && this.ssrc2resolution[ssrc])
  8951. {
  8952. delete this.ssrc2resolution[ssrc];
  8953. }
  8954. else if(resolution !== null)
  8955. this.ssrc2resolution[ssrc] = resolution;
  8956. };
  8957. /**
  8958. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  8959. * represented by this instance.
  8960. * @param ssrc audio or video RTP stream SSRC.
  8961. * @param bitrate new bitrate value to be set.
  8962. */
  8963. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  8964. {
  8965. if(this.ssrc2bitrate[ssrc])
  8966. {
  8967. this.ssrc2bitrate[ssrc].download += bitrate.download;
  8968. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  8969. }
  8970. else {
  8971. this.ssrc2bitrate[ssrc] = bitrate;
  8972. }
  8973. };
  8974. /**
  8975. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  8976. * the stream which belongs to the peer represented by this instance.
  8977. * @param ssrc RTP stream SSRC for which current audio level value will be
  8978. * updated.
  8979. * @param audioLevel the new audio level value to be set. Value is truncated to
  8980. * fit the range from 0 to 1.
  8981. */
  8982. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  8983. {
  8984. // Range limit 0 - 1
  8985. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  8986. };
  8987. function formatAudioLevel(audioLevel) {
  8988. return Math.min(Math.max(audioLevel, 0), 1);
  8989. }
  8990. /**
  8991. * Array with the transport information.
  8992. * @type {Array}
  8993. */
  8994. PeerStats.transport = [];
  8995. /**
  8996. * <tt>StatsCollector</tt> registers for stats updates of given
  8997. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  8998. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  8999. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9000. * instance as an event source.
  9001. *
  9002. * @param peerconnection webRTC peer connection object.
  9003. * @param interval stats refresh interval given in ms.
  9004. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9005. * called on stats update.
  9006. * @constructor
  9007. */
  9008. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9009. {
  9010. this.peerconnection = peerconnection;
  9011. this.baselineAudioLevelsReport = null;
  9012. this.currentAudioLevelsReport = null;
  9013. this.currentStatsReport = null;
  9014. this.baselineStatsReport = null;
  9015. this.audioLevelsIntervalId = null;
  9016. this.eventEmitter = eventEmitter;
  9017. /**
  9018. * Gather PeerConnection stats once every this many milliseconds.
  9019. */
  9020. this.GATHER_INTERVAL = 15000;
  9021. /**
  9022. * Log stats via the focus once every this many milliseconds.
  9023. */
  9024. this.LOG_INTERVAL = 60000;
  9025. /**
  9026. * Gather stats and store them in this.statsToBeLogged.
  9027. */
  9028. this.gatherStatsIntervalId = null;
  9029. /**
  9030. * Send the stats already saved in this.statsToBeLogged to be logged via
  9031. * the focus.
  9032. */
  9033. this.logStatsIntervalId = null;
  9034. /**
  9035. * Stores the statistics which will be send to the focus to be logged.
  9036. */
  9037. this.statsToBeLogged =
  9038. {
  9039. timestamps: [],
  9040. stats: {}
  9041. };
  9042. // Updates stats interval
  9043. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9044. this.statsIntervalId = null;
  9045. this.statsIntervalMilis = statsInterval;
  9046. // Map of jids to PeerStats
  9047. this.jid2stats = {};
  9048. }
  9049. module.exports = StatsCollector;
  9050. /**
  9051. * Stops stats updates.
  9052. */
  9053. StatsCollector.prototype.stop = function () {
  9054. if (this.audioLevelsIntervalId) {
  9055. clearInterval(this.audioLevelsIntervalId);
  9056. this.audioLevelsIntervalId = null;
  9057. }
  9058. if (this.statsIntervalId)
  9059. {
  9060. clearInterval(this.statsIntervalId);
  9061. this.statsIntervalId = null;
  9062. }
  9063. if(this.logStatsIntervalId)
  9064. {
  9065. clearInterval(this.logStatsIntervalId);
  9066. this.logStatsIntervalId = null;
  9067. }
  9068. if(this.gatherStatsIntervalId)
  9069. {
  9070. clearInterval(this.gatherStatsIntervalId);
  9071. this.gatherStatsIntervalId = null;
  9072. }
  9073. };
  9074. /**
  9075. * Callback passed to <tt>getStats</tt> method.
  9076. * @param error an error that occurred on <tt>getStats</tt> call.
  9077. */
  9078. StatsCollector.prototype.errorCallback = function (error)
  9079. {
  9080. console.error("Get stats error", error);
  9081. this.stop();
  9082. };
  9083. /**
  9084. * Starts stats updates.
  9085. */
  9086. StatsCollector.prototype.start = function ()
  9087. {
  9088. var self = this;
  9089. if(!config.disableAudioLevels) {
  9090. this.audioLevelsIntervalId = setInterval(
  9091. function () {
  9092. // Interval updates
  9093. self.peerconnection.getStats(
  9094. function (report) {
  9095. var results = null;
  9096. if (!report || !report.result ||
  9097. typeof report.result != 'function') {
  9098. results = report;
  9099. }
  9100. else {
  9101. results = report.result();
  9102. }
  9103. //console.error("Got interval report", results);
  9104. self.currentAudioLevelsReport = results;
  9105. self.processAudioLevelReport();
  9106. self.baselineAudioLevelsReport =
  9107. self.currentAudioLevelsReport;
  9108. },
  9109. self.errorCallback
  9110. );
  9111. },
  9112. self.audioLevelsIntervalMilis
  9113. );
  9114. }
  9115. if(!config.disableStats && !navigator.mozGetUserMedia) {
  9116. this.statsIntervalId = setInterval(
  9117. function () {
  9118. // Interval updates
  9119. self.peerconnection.getStats(
  9120. function (report) {
  9121. var results = null;
  9122. if (!report || !report.result ||
  9123. typeof report.result != 'function') {
  9124. //firefox
  9125. results = report;
  9126. }
  9127. else {
  9128. //chrome
  9129. results = report.result();
  9130. }
  9131. //console.error("Got interval report", results);
  9132. self.currentStatsReport = results;
  9133. try {
  9134. self.processStatsReport();
  9135. }
  9136. catch (e) {
  9137. console.error("Unsupported key:" + e, e);
  9138. }
  9139. self.baselineStatsReport = self.currentStatsReport;
  9140. },
  9141. self.errorCallback
  9142. );
  9143. },
  9144. self.statsIntervalMilis
  9145. );
  9146. }
  9147. if (config.logStats && !navigator.mozGetUserMedia) {
  9148. this.gatherStatsIntervalId = setInterval(
  9149. function () {
  9150. self.peerconnection.getStats(
  9151. function (report) {
  9152. self.addStatsToBeLogged(report.result());
  9153. },
  9154. function () {
  9155. }
  9156. );
  9157. },
  9158. this.GATHER_INTERVAL
  9159. );
  9160. this.logStatsIntervalId = setInterval(
  9161. function() { self.logStats(); },
  9162. this.LOG_INTERVAL);
  9163. }
  9164. };
  9165. /**
  9166. * Checks whether a certain record should be included in the logged statistics.
  9167. */
  9168. function acceptStat(reportId, reportType, statName) {
  9169. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9170. return false;
  9171. if (reportType == "ssrc") {
  9172. if (statName == "googTrackId" ||
  9173. statName == "transportId" ||
  9174. statName == "ssrc")
  9175. return false;
  9176. }
  9177. return true;
  9178. }
  9179. /**
  9180. * Checks whether a certain record should be included in the logged statistics.
  9181. */
  9182. function acceptReport(id, type) {
  9183. if (id.substring(0, 15) == "googCertificate" ||
  9184. id.substring(0, 9) == "googTrack" ||
  9185. id.substring(0, 20) == "googLibjingleSession")
  9186. return false;
  9187. if (type == "googComponent")
  9188. return false;
  9189. return true;
  9190. }
  9191. /**
  9192. * Converts the stats to the format used for logging, and saves the data in
  9193. * this.statsToBeLogged.
  9194. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9195. */
  9196. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9197. var self = this;
  9198. var num_records = this.statsToBeLogged.timestamps.length;
  9199. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9200. reports.map(function (report) {
  9201. if (!acceptReport(report.id, report.type))
  9202. return;
  9203. var stat = self.statsToBeLogged.stats[report.id];
  9204. if (!stat) {
  9205. stat = self.statsToBeLogged.stats[report.id] = {};
  9206. }
  9207. stat.type = report.type;
  9208. report.names().map(function (name) {
  9209. if (!acceptStat(report.id, report.type, name))
  9210. return;
  9211. var values = stat[name];
  9212. if (!values) {
  9213. values = stat[name] = [];
  9214. }
  9215. while (values.length < num_records) {
  9216. values.push(null);
  9217. }
  9218. values.push(report.stat(name));
  9219. });
  9220. });
  9221. };
  9222. StatsCollector.prototype.logStats = function () {
  9223. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9224. return;
  9225. // Reset the stats
  9226. this.statsToBeLogged.stats = {};
  9227. this.statsToBeLogged.timestamps = [];
  9228. };
  9229. var keyMap = {};
  9230. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9231. "ssrc": "ssrc",
  9232. "packetsReceived": "packetsReceived",
  9233. "packetsLost": "packetsLost",
  9234. "packetsSent": "packetsSent",
  9235. "bytesReceived": "bytesReceived",
  9236. "bytesSent": "bytesSent"
  9237. };
  9238. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9239. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9240. "sendBandwidth": "googAvailableSendBandwidth",
  9241. "remoteAddress": "googRemoteAddress",
  9242. "transportType": "googTransportType",
  9243. "localAddress": "googLocalAddress",
  9244. "activeConnection": "googActiveConnection",
  9245. "ssrc": "ssrc",
  9246. "packetsReceived": "packetsReceived",
  9247. "packetsSent": "packetsSent",
  9248. "packetsLost": "packetsLost",
  9249. "bytesReceived": "bytesReceived",
  9250. "bytesSent": "bytesSent",
  9251. "googFrameHeightReceived": "googFrameHeightReceived",
  9252. "googFrameWidthReceived": "googFrameWidthReceived",
  9253. "googFrameHeightSent": "googFrameHeightSent",
  9254. "googFrameWidthSent": "googFrameWidthSent",
  9255. "audioInputLevel": "audioInputLevel",
  9256. "audioOutputLevel": "audioOutputLevel"
  9257. };
  9258. /**
  9259. * Stats processing logic.
  9260. */
  9261. StatsCollector.prototype.processStatsReport = function () {
  9262. if (!this.baselineStatsReport) {
  9263. return;
  9264. }
  9265. for (var idx in this.currentStatsReport) {
  9266. var now = this.currentStatsReport[idx];
  9267. try {
  9268. if (getStatValue(now, 'receiveBandwidth') ||
  9269. getStatValue(now, 'sendBandwidth')) {
  9270. PeerStats.bandwidth = {
  9271. "download": Math.round(
  9272. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9273. "upload": Math.round(
  9274. (getStatValue(now, 'sendBandwidth')) / 1000)
  9275. };
  9276. }
  9277. }
  9278. catch(e){/*not supported*/}
  9279. if(now.type == 'googCandidatePair')
  9280. {
  9281. var ip, type, localIP, active;
  9282. try {
  9283. ip = getStatValue(now, 'remoteAddress');
  9284. type = getStatValue(now, "transportType");
  9285. localIP = getStatValue(now, "localAddress");
  9286. active = getStatValue(now, "activeConnection");
  9287. }
  9288. catch(e){/*not supported*/}
  9289. if(!ip || !type || !localIP || active != "true")
  9290. continue;
  9291. var addressSaved = false;
  9292. for(var i = 0; i < PeerStats.transport.length; i++)
  9293. {
  9294. if(PeerStats.transport[i].ip == ip &&
  9295. PeerStats.transport[i].type == type &&
  9296. PeerStats.transport[i].localip == localIP)
  9297. {
  9298. addressSaved = true;
  9299. }
  9300. }
  9301. if(addressSaved)
  9302. continue;
  9303. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9304. continue;
  9305. }
  9306. if(now.type == "candidatepair")
  9307. {
  9308. if(now.state == "succeeded")
  9309. continue;
  9310. var local = this.currentStatsReport[now.localCandidateId];
  9311. var remote = this.currentStatsReport[now.remoteCandidateId];
  9312. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9313. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9314. }
  9315. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9316. now.type != "inboundrtp") {
  9317. continue;
  9318. }
  9319. var before = this.baselineStatsReport[idx];
  9320. if (!before) {
  9321. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9322. continue;
  9323. }
  9324. var ssrc = getStatValue(now, 'ssrc');
  9325. if(!ssrc)
  9326. continue;
  9327. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9328. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9329. console.warn("No jid for ssrc: " + ssrc);
  9330. continue;
  9331. }
  9332. var jidStats = this.jid2stats[jid];
  9333. if (!jidStats) {
  9334. jidStats = new PeerStats();
  9335. this.jid2stats[jid] = jidStats;
  9336. }
  9337. var isDownloadStream = true;
  9338. var key = 'packetsReceived';
  9339. if (!getStatValue(now, key))
  9340. {
  9341. isDownloadStream = false;
  9342. key = 'packetsSent';
  9343. if (!getStatValue(now, key))
  9344. {
  9345. console.warn("No packetsReceived nor packetSent stat found");
  9346. continue;
  9347. }
  9348. }
  9349. var packetsNow = getStatValue(now, key);
  9350. if(!packetsNow || packetsNow < 0)
  9351. packetsNow = 0;
  9352. var packetsBefore = getStatValue(before, key);
  9353. if(!packetsBefore || packetsBefore < 0)
  9354. packetsBefore = 0;
  9355. var packetRate = packetsNow - packetsBefore;
  9356. if(!packetRate || packetRate < 0)
  9357. packetRate = 0;
  9358. var currentLoss = getStatValue(now, 'packetsLost');
  9359. if(!currentLoss || currentLoss < 0)
  9360. currentLoss = 0;
  9361. var previousLoss = getStatValue(before, 'packetsLost');
  9362. if(!previousLoss || previousLoss < 0)
  9363. previousLoss = 0;
  9364. var lossRate = currentLoss - previousLoss;
  9365. if(!lossRate || lossRate < 0)
  9366. lossRate = 0;
  9367. var packetsTotal = (packetRate + lossRate);
  9368. jidStats.setSsrcLoss(ssrc,
  9369. {"packetsTotal": packetsTotal,
  9370. "packetsLost": lossRate,
  9371. "isDownloadStream": isDownloadStream});
  9372. var bytesReceived = 0, bytesSent = 0;
  9373. if(getStatValue(now, "bytesReceived"))
  9374. {
  9375. bytesReceived = getStatValue(now, "bytesReceived") -
  9376. getStatValue(before, "bytesReceived");
  9377. }
  9378. if(getStatValue(now, "bytesSent"))
  9379. {
  9380. bytesSent = getStatValue(now, "bytesSent") -
  9381. getStatValue(before, "bytesSent");
  9382. }
  9383. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9384. if(bytesReceived <= 0 || time <= 0)
  9385. {
  9386. bytesReceived = 0;
  9387. }
  9388. else
  9389. {
  9390. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9391. }
  9392. if(bytesSent <= 0 || time <= 0)
  9393. {
  9394. bytesSent = 0;
  9395. }
  9396. else
  9397. {
  9398. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9399. }
  9400. jidStats.setSsrcBitrate(ssrc, {
  9401. "download": bytesReceived,
  9402. "upload": bytesSent});
  9403. var resolution = {height: null, width: null};
  9404. try {
  9405. if (getStatValue(now, "googFrameHeightReceived") &&
  9406. getStatValue(now, "googFrameWidthReceived")) {
  9407. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9408. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9409. }
  9410. else if (getStatValue(now, "googFrameHeightSent") &&
  9411. getStatValue(now, "googFrameWidthSent")) {
  9412. resolution.height = getStatValue(now, "googFrameHeightSent");
  9413. resolution.width = getStatValue(now, "googFrameWidthSent");
  9414. }
  9415. }
  9416. catch(e){/*not supported*/}
  9417. if(resolution.height && resolution.width)
  9418. {
  9419. jidStats.setSsrcResolution(ssrc, resolution);
  9420. }
  9421. else
  9422. {
  9423. jidStats.setSsrcResolution(ssrc, null);
  9424. }
  9425. }
  9426. var self = this;
  9427. // Jid stats
  9428. var totalPackets = {download: 0, upload: 0};
  9429. var lostPackets = {download: 0, upload: 0};
  9430. var bitrateDownload = 0;
  9431. var bitrateUpload = 0;
  9432. var resolutions = {};
  9433. Object.keys(this.jid2stats).forEach(
  9434. function (jid)
  9435. {
  9436. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9437. function (ssrc)
  9438. {
  9439. var type = "upload";
  9440. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9441. type = "download";
  9442. totalPackets[type] +=
  9443. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9444. lostPackets[type] +=
  9445. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9446. }
  9447. );
  9448. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9449. function (ssrc) {
  9450. bitrateDownload +=
  9451. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9452. bitrateUpload +=
  9453. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9454. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9455. }
  9456. );
  9457. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9458. }
  9459. );
  9460. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9461. PeerStats.packetLoss = {
  9462. total:
  9463. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9464. totalPackets.download + totalPackets.upload),
  9465. download:
  9466. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9467. upload:
  9468. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9469. };
  9470. this.eventEmitter.emit("statistics.connectionstats",
  9471. {
  9472. "bitrate": PeerStats.bitrate,
  9473. "packetLoss": PeerStats.packetLoss,
  9474. "bandwidth": PeerStats.bandwidth,
  9475. "resolution": resolutions,
  9476. "transport": PeerStats.transport
  9477. });
  9478. PeerStats.transport = [];
  9479. };
  9480. /**
  9481. * Stats processing logic.
  9482. */
  9483. StatsCollector.prototype.processAudioLevelReport = function ()
  9484. {
  9485. if (!this.baselineAudioLevelsReport)
  9486. {
  9487. return;
  9488. }
  9489. for (var idx in this.currentAudioLevelsReport)
  9490. {
  9491. var now = this.currentAudioLevelsReport[idx];
  9492. if (now.type != 'ssrc')
  9493. {
  9494. continue;
  9495. }
  9496. var before = this.baselineAudioLevelsReport[idx];
  9497. if (!before)
  9498. {
  9499. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9500. continue;
  9501. }
  9502. var ssrc = getStatValue(now, 'ssrc');
  9503. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9504. if (!jid)
  9505. {
  9506. if((Date.now() - now.timestamp) < 3000)
  9507. console.warn("No jid for ssrc: " + ssrc);
  9508. continue;
  9509. }
  9510. var jidStats = this.jid2stats[jid];
  9511. if (!jidStats)
  9512. {
  9513. jidStats = new PeerStats();
  9514. this.jid2stats[jid] = jidStats;
  9515. }
  9516. // Audio level
  9517. var audioLevel = null;
  9518. try {
  9519. audioLevel = getStatValue(now, 'audioInputLevel');
  9520. if (!audioLevel)
  9521. audioLevel = getStatValue(now, 'audioOutputLevel');
  9522. }
  9523. catch(e) {/*not supported*/
  9524. console.warn("Audio Levels are not available in the statistics.");
  9525. clearInterval(this.audioLevelsIntervalId);
  9526. return;
  9527. }
  9528. if (audioLevel)
  9529. {
  9530. // TODO: can't find specs about what this value really is,
  9531. // but it seems to vary between 0 and around 32k.
  9532. audioLevel = audioLevel / 32767;
  9533. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  9534. if(jid != APP.xmpp.myJid())
  9535. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  9536. }
  9537. }
  9538. };
  9539. },{"../../service/RTC/RTCBrowserType":102}],44:[function(require,module,exports){
  9540. /**
  9541. * Created by hristo on 8/4/14.
  9542. */
  9543. var LocalStats = require("./LocalStatsCollector.js");
  9544. var RTPStats = require("./RTPStatsCollector.js");
  9545. var EventEmitter = require("events");
  9546. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  9547. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9548. var eventEmitter = new EventEmitter();
  9549. var localStats = null;
  9550. var rtpStats = null;
  9551. function stopLocal()
  9552. {
  9553. if(localStats)
  9554. {
  9555. localStats.stop();
  9556. localStats = null;
  9557. }
  9558. }
  9559. function stopRemote()
  9560. {
  9561. if(rtpStats)
  9562. {
  9563. rtpStats.stop();
  9564. eventEmitter.emit("statistics.stop");
  9565. rtpStats = null;
  9566. }
  9567. }
  9568. function startRemoteStats (peerconnection) {
  9569. if(rtpStats)
  9570. {
  9571. rtpStats.stop();
  9572. rtpStats = null;
  9573. }
  9574. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  9575. rtpStats.start();
  9576. }
  9577. function onStreamCreated(stream)
  9578. {
  9579. if(stream.getOriginalStream().getAudioTracks().length === 0)
  9580. return;
  9581. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  9582. eventEmitter);
  9583. localStats.start();
  9584. }
  9585. function onDisposeConference(onUnload) {
  9586. stopRemote();
  9587. if(onUnload) {
  9588. stopLocal();
  9589. eventEmitter.removeAllListeners();
  9590. }
  9591. }
  9592. var statistics =
  9593. {
  9594. /**
  9595. * Indicates that this audio level is for local jid.
  9596. * @type {string}
  9597. */
  9598. LOCAL_JID: 'local',
  9599. addAudioLevelListener: function(listener)
  9600. {
  9601. eventEmitter.on("statistics.audioLevel", listener);
  9602. },
  9603. removeAudioLevelListener: function(listener)
  9604. {
  9605. eventEmitter.removeListener("statistics.audioLevel", listener);
  9606. },
  9607. addConnectionStatsListener: function(listener)
  9608. {
  9609. eventEmitter.on("statistics.connectionstats", listener);
  9610. },
  9611. removeConnectionStatsListener: function(listener)
  9612. {
  9613. eventEmitter.removeListener("statistics.connectionstats", listener);
  9614. },
  9615. addRemoteStatsStopListener: function(listener)
  9616. {
  9617. eventEmitter.on("statistics.stop", listener);
  9618. },
  9619. removeRemoteStatsStopListener: function(listener)
  9620. {
  9621. eventEmitter.removeListener("statistics.stop", listener);
  9622. },
  9623. stop: function () {
  9624. stopLocal();
  9625. stopRemote();
  9626. if(eventEmitter)
  9627. {
  9628. eventEmitter.removeAllListeners();
  9629. }
  9630. },
  9631. stopRemoteStatistics: function()
  9632. {
  9633. stopRemote();
  9634. },
  9635. start: function () {
  9636. APP.RTC.addStreamListener(onStreamCreated,
  9637. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  9638. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  9639. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  9640. startRemoteStats(event.peerconnection);
  9641. });
  9642. }
  9643. };
  9644. module.exports = statistics;
  9645. },{"../../service/RTC/StreamEventTypes.js":105,"../../service/xmpp/XMPPEvents":112,"./LocalStatsCollector.js":42,"./RTPStatsCollector.js":43,"events":62}],45:[function(require,module,exports){
  9646. var i18n = require("i18next-client");
  9647. var languages = require("../../service/translation/languages");
  9648. var Settings = require("../settings/Settings");
  9649. var DEFAULT_LANG = languages.EN;
  9650. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  9651. return value.replace("__app__", interfaceConfig.APP_NAME);
  9652. });
  9653. var defaultOptions = {
  9654. detectLngQS: "lang",
  9655. useCookie: false,
  9656. fallbackLng: DEFAULT_LANG,
  9657. load: "unspecific",
  9658. resGetPath: 'lang/__ns__-__lng__.json',
  9659. ns: {
  9660. namespaces: ['main', 'languages'],
  9661. defaultNs: 'main'
  9662. },
  9663. lngWhitelist : languages.getLanguages(),
  9664. fallbackOnNull: true,
  9665. fallbackOnEmpty: true,
  9666. useDataAttrOptions: true,
  9667. defaultValueFromContent: false,
  9668. app: interfaceConfig.APP_NAME,
  9669. getAsync: false,
  9670. defaultValueFromContent: false,
  9671. customLoad: function(lng, ns, options, done) {
  9672. var resPath = "lang/__ns__-__lng__.json";
  9673. if(lng === languages.EN)
  9674. resPath = "lang/__ns__.json";
  9675. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  9676. i18n.functions.ajax({
  9677. url: url,
  9678. success: function(data, status, xhr) {
  9679. i18n.functions.log('loaded: ' + url);
  9680. done(null, data);
  9681. },
  9682. error : function(xhr, status, error) {
  9683. if ((status && status == 200) ||
  9684. (xhr && xhr.status && xhr.status == 200)) {
  9685. // file loaded but invalid json, stop waste time !
  9686. i18n.functions.error('There is a typo in: ' + url);
  9687. } else if ((status && status == 404) ||
  9688. (xhr && xhr.status && xhr.status == 404)) {
  9689. i18n.functions.log('Does not exist: ' + url);
  9690. } else {
  9691. var theStatus = status ? status :
  9692. ((xhr && xhr.status) ? xhr.status : null);
  9693. i18n.functions.log(theStatus + ' when loading ' + url);
  9694. }
  9695. done(error, {});
  9696. },
  9697. dataType: "json",
  9698. async : options.getAsync
  9699. });
  9700. }
  9701. // options for caching
  9702. // useLocalStorage: true,
  9703. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  9704. };
  9705. function initCompleted(t)
  9706. {
  9707. $("[data-i18n]").i18n();
  9708. }
  9709. function checkForParameter() {
  9710. var query = window.location.search.substring(1);
  9711. var vars = query.split("&");
  9712. for (var i=0;i<vars.length;i++) {
  9713. var pair = vars[i].split("=");
  9714. if(pair[0] == "lang")
  9715. {
  9716. return pair[1];
  9717. }
  9718. }
  9719. return null;
  9720. }
  9721. module.exports = {
  9722. init: function (lang) {
  9723. var options = defaultOptions;
  9724. if(!lang)
  9725. {
  9726. lang = checkForParameter();
  9727. if(!lang)
  9728. {
  9729. var settings = Settings.getSettings();
  9730. if(settings)
  9731. lang = settings.language;
  9732. if(!lang && config.defaultLanguage)
  9733. {
  9734. lang = config.defaultLanguage;
  9735. }
  9736. }
  9737. }
  9738. if(lang) {
  9739. options.lng = lang;
  9740. }
  9741. i18n.init(options, initCompleted);
  9742. },
  9743. translateString: function (key, options) {
  9744. return i18n.t(key, options);
  9745. },
  9746. setLanguage: function (lang) {
  9747. if(!lang)
  9748. lang = DEFAULT_LANG;
  9749. i18n.setLng(lang, defaultOptions, initCompleted);
  9750. },
  9751. getCurrentLanguage: function () {
  9752. return i18n.lng();
  9753. },
  9754. translateElement: function (selector) {
  9755. selector.i18n();
  9756. },
  9757. generateTranslatonHTML: function (key, options) {
  9758. var str = "<span data-i18n=\"" + key + "\"";
  9759. if(options)
  9760. {
  9761. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  9762. }
  9763. str += ">";
  9764. str += this.translateString(key, options);
  9765. str += "</span>";
  9766. return str;
  9767. }
  9768. };
  9769. },{"../../service/translation/languages":111,"../settings/Settings":41,"i18next-client":63}],46:[function(require,module,exports){
  9770. /* jshint -W117 */
  9771. var TraceablePeerConnection = require("./TraceablePeerConnection");
  9772. var SDPDiffer = require("./SDPDiffer");
  9773. var SDPUtil = require("./SDPUtil");
  9774. var SDP = require("./SDP");
  9775. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9776. var async = require("async");
  9777. var transform = require("sdp-transform");
  9778. // Jingle stuff
  9779. function JingleSession(me, sid, connection, service) {
  9780. this.me = me;
  9781. this.sid = sid;
  9782. this.connection = connection;
  9783. this.initiator = null;
  9784. this.responder = null;
  9785. this.isInitiator = null;
  9786. this.peerjid = null;
  9787. this.state = null;
  9788. this.localSDP = null;
  9789. this.remoteSDP = null;
  9790. this.relayedStreams = [];
  9791. this.startTime = null;
  9792. this.stopTime = null;
  9793. this.media_constraints = null;
  9794. this.pc_constraints = null;
  9795. this.ice_config = {};
  9796. this.drip_container = [];
  9797. this.service = service;
  9798. this.usetrickle = true;
  9799. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  9800. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  9801. this.hadstuncandidate = false;
  9802. this.hadturncandidate = false;
  9803. this.lasticecandidate = false;
  9804. this.statsinterval = null;
  9805. this.reason = null;
  9806. this.addssrc = [];
  9807. this.removessrc = [];
  9808. this.pendingop = null;
  9809. this.switchstreams = false;
  9810. this.wait = true;
  9811. this.localStreamsSSRC = null;
  9812. /**
  9813. * The indicator which determines whether the (local) video has been muted
  9814. * in response to a user command in contrast to an automatic decision made
  9815. * by the application logic.
  9816. */
  9817. this.videoMuteByUser = false;
  9818. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  9819. // We start with the queue paused. We resume it when the signaling state is
  9820. // stable and the ice connection state is connected.
  9821. this.modifySourcesQueue.pause();
  9822. }
  9823. JingleSession.prototype.updateModifySourcesQueue = function() {
  9824. var signalingState = this.peerconnection.signalingState;
  9825. var iceConnectionState = this.peerconnection.iceConnectionState;
  9826. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  9827. this.modifySourcesQueue.resume();
  9828. } else {
  9829. this.modifySourcesQueue.pause();
  9830. }
  9831. };
  9832. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  9833. var self = this;
  9834. if (this.state !== null) {
  9835. console.error('attempt to initiate on session ' + this.sid +
  9836. 'in state ' + this.state);
  9837. return;
  9838. }
  9839. this.isInitiator = isInitiator;
  9840. this.state = 'pending';
  9841. this.initiator = isInitiator ? this.me : peerjid;
  9842. this.responder = !isInitiator ? this.me : peerjid;
  9843. this.peerjid = peerjid;
  9844. this.hadstuncandidate = false;
  9845. this.hadturncandidate = false;
  9846. this.lasticecandidate = false;
  9847. this.peerconnection
  9848. = new TraceablePeerConnection(
  9849. this.connection.jingle.ice_config,
  9850. this.connection.jingle.pc_constraints );
  9851. this.peerconnection.onicecandidate = function (event) {
  9852. self.sendIceCandidate(event.candidate);
  9853. };
  9854. this.peerconnection.onaddstream = function (event) {
  9855. if (event.stream.id !== 'default') {
  9856. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  9857. self.remoteStreamAdded(event);
  9858. } else {
  9859. // This is a recvonly stream. Clients that implement Unified Plan,
  9860. // such as Firefox use recvonly "streams/channels/tracks" for
  9861. // receiving remote stream/tracks, as opposed to Plan B where there
  9862. // are only 3 channels: audio, video and data.
  9863. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  9864. }
  9865. };
  9866. this.peerconnection.onremovestream = function (event) {
  9867. // Remove the stream from remoteStreams
  9868. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  9869. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  9870. };
  9871. this.peerconnection.onsignalingstatechange = function (event) {
  9872. if (!(self && self.peerconnection)) return;
  9873. self.updateModifySourcesQueue();
  9874. };
  9875. this.peerconnection.oniceconnectionstatechange = function (event) {
  9876. if (!(self && self.peerconnection)) return;
  9877. self.updateModifySourcesQueue();
  9878. switch (self.peerconnection.iceConnectionState) {
  9879. case 'connected':
  9880. this.startTime = new Date();
  9881. break;
  9882. case 'disconnected':
  9883. this.stopTime = new Date();
  9884. break;
  9885. }
  9886. onIceConnectionStateChange(self.sid, self);
  9887. };
  9888. // add any local and relayed stream
  9889. APP.RTC.localStreams.forEach(function(stream) {
  9890. self.peerconnection.addStream(stream.getOriginalStream());
  9891. });
  9892. this.relayedStreams.forEach(function(stream) {
  9893. self.peerconnection.addStream(stream);
  9894. });
  9895. };
  9896. function onIceConnectionStateChange(sid, session) {
  9897. switch (session.peerconnection.iceConnectionState) {
  9898. case 'checking':
  9899. session.timeChecking = (new Date()).getTime();
  9900. session.firstconnect = true;
  9901. break;
  9902. case 'completed': // on caller side
  9903. case 'connected':
  9904. if (session.firstconnect) {
  9905. session.firstconnect = false;
  9906. var metadata = {};
  9907. metadata.setupTime
  9908. = (new Date()).getTime() - session.timeChecking;
  9909. session.peerconnection.getStats(function (res) {
  9910. if(res && res.result) {
  9911. res.result().forEach(function (report) {
  9912. if (report.type == 'googCandidatePair' &&
  9913. report.stat('googActiveConnection') == 'true') {
  9914. metadata.localCandidateType
  9915. = report.stat('googLocalCandidateType');
  9916. metadata.remoteCandidateType
  9917. = report.stat('googRemoteCandidateType');
  9918. // log pair as well so we can get nice pie
  9919. // charts
  9920. metadata.candidatePair
  9921. = report.stat('googLocalCandidateType') +
  9922. ';' +
  9923. report.stat('googRemoteCandidateType');
  9924. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  9925. {
  9926. metadata.ipv6 = true;
  9927. }
  9928. }
  9929. });
  9930. }
  9931. });
  9932. }
  9933. break;
  9934. }
  9935. }
  9936. JingleSession.prototype.accept = function () {
  9937. var self = this;
  9938. this.state = 'active';
  9939. var pranswer = this.peerconnection.localDescription;
  9940. if (!pranswer || pranswer.type != 'pranswer') {
  9941. return;
  9942. }
  9943. console.log('going from pranswer to answer');
  9944. if (this.usetrickle) {
  9945. // remove candidates already sent from session-accept
  9946. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  9947. for (var i = 0; i < lines.length; i++) {
  9948. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  9949. }
  9950. }
  9951. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  9952. // FIXME: change any inactive to sendrecv or whatever they were originally
  9953. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  9954. }
  9955. var prsdp = new SDP(pranswer.sdp);
  9956. var accept = $iq({to: this.peerjid,
  9957. type: 'set'})
  9958. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  9959. action: 'session-accept',
  9960. initiator: this.initiator,
  9961. responder: this.responder,
  9962. sid: this.sid });
  9963. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  9964. var sdp = this.peerconnection.localDescription.sdp;
  9965. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  9966. // FIXME: change any inactive to sendrecv or whatever they were originally
  9967. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  9968. }
  9969. var self = this;
  9970. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  9971. function () {
  9972. //console.log('setLocalDescription success');
  9973. self.setLocalDescription();
  9974. self.connection.sendIQ(accept,
  9975. function () {
  9976. var ack = {};
  9977. ack.source = 'answer';
  9978. $(document).trigger('ack.jingle', [self.sid, ack]);
  9979. },
  9980. function (stanza) {
  9981. var error = ($(stanza).find('error').length) ? {
  9982. code: $(stanza).find('error').attr('code'),
  9983. reason: $(stanza).find('error :first')[0].tagName
  9984. }:{};
  9985. error.source = 'answer';
  9986. JingleSession.onJingleError(self.sid, error);
  9987. },
  9988. 10000);
  9989. },
  9990. function (e) {
  9991. console.error('setLocalDescription failed', e);
  9992. }
  9993. );
  9994. };
  9995. JingleSession.prototype.terminate = function (reason) {
  9996. this.state = 'ended';
  9997. this.reason = reason;
  9998. this.peerconnection.close();
  9999. if (this.statsinterval !== null) {
  10000. window.clearInterval(this.statsinterval);
  10001. this.statsinterval = null;
  10002. }
  10003. };
  10004. JingleSession.prototype.active = function () {
  10005. return this.state == 'active';
  10006. };
  10007. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10008. var self = this;
  10009. if (candidate && !this.lasticecandidate) {
  10010. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10011. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10012. if (!(ice && jcand)) {
  10013. console.error('failed to get ice && jcand');
  10014. return;
  10015. }
  10016. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10017. if (jcand.type === 'srflx') {
  10018. this.hadstuncandidate = true;
  10019. } else if (jcand.type === 'relay') {
  10020. this.hadturncandidate = true;
  10021. }
  10022. if (this.usetrickle) {
  10023. if (this.usedrip) {
  10024. if (this.drip_container.length === 0) {
  10025. // start 20ms callout
  10026. window.setTimeout(function () {
  10027. if (self.drip_container.length === 0) return;
  10028. self.sendIceCandidates(self.drip_container);
  10029. self.drip_container = [];
  10030. }, 20);
  10031. }
  10032. this.drip_container.push(candidate);
  10033. return;
  10034. } else {
  10035. self.sendIceCandidate([candidate]);
  10036. }
  10037. }
  10038. } else {
  10039. //console.log('sendIceCandidate: last candidate.');
  10040. if (!this.usetrickle) {
  10041. //console.log('should send full offer now...');
  10042. var init = $iq({to: this.peerjid,
  10043. type: 'set'})
  10044. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10045. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10046. initiator: this.initiator,
  10047. sid: this.sid});
  10048. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10049. var self = this;
  10050. var sendJingle = function (ssrc) {
  10051. if(!ssrc)
  10052. ssrc = {};
  10053. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10054. self.connection.sendIQ(init,
  10055. function () {
  10056. //console.log('session initiate ack');
  10057. var ack = {};
  10058. ack.source = 'offer';
  10059. $(document).trigger('ack.jingle', [self.sid, ack]);
  10060. },
  10061. function (stanza) {
  10062. self.state = 'error';
  10063. self.peerconnection.close();
  10064. var error = ($(stanza).find('error').length) ? {
  10065. code: $(stanza).find('error').attr('code'),
  10066. reason: $(stanza).find('error :first')[0].tagName,
  10067. }:{};
  10068. error.source = 'offer';
  10069. JingleSession.onJingleError(self.sid, error);
  10070. },
  10071. 10000);
  10072. }
  10073. sendJingle();
  10074. }
  10075. this.lasticecandidate = true;
  10076. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10077. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10078. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10079. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10080. }
  10081. }
  10082. };
  10083. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10084. console.log('sendIceCandidates', candidates);
  10085. var cand = $iq({to: this.peerjid, type: 'set'})
  10086. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10087. action: 'transport-info',
  10088. initiator: this.initiator,
  10089. sid: this.sid});
  10090. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10091. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10092. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10093. if (cands.length > 0) {
  10094. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10095. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10096. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10097. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10098. }).c('transport', ice);
  10099. for (var i = 0; i < cands.length; i++) {
  10100. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10101. }
  10102. // add fingerprint
  10103. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10104. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10105. tmp.required = true;
  10106. cand.c(
  10107. 'fingerprint',
  10108. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10109. .t(tmp.fingerprint);
  10110. delete tmp.fingerprint;
  10111. cand.attrs(tmp);
  10112. cand.up();
  10113. }
  10114. cand.up(); // transport
  10115. cand.up(); // content
  10116. }
  10117. }
  10118. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10119. //console.log('was this the last candidate', this.lasticecandidate);
  10120. this.connection.sendIQ(cand,
  10121. function () {
  10122. var ack = {};
  10123. ack.source = 'transportinfo';
  10124. $(document).trigger('ack.jingle', [this.sid, ack]);
  10125. },
  10126. function (stanza) {
  10127. var error = ($(stanza).find('error').length) ? {
  10128. code: $(stanza).find('error').attr('code'),
  10129. reason: $(stanza).find('error :first')[0].tagName,
  10130. }:{};
  10131. error.source = 'transportinfo';
  10132. JingleSession.onJingleError(this.sid, error);
  10133. },
  10134. 10000);
  10135. };
  10136. JingleSession.prototype.sendOffer = function () {
  10137. //console.log('sendOffer...');
  10138. var self = this;
  10139. this.peerconnection.createOffer(function (sdp) {
  10140. self.createdOffer(sdp);
  10141. },
  10142. function (e) {
  10143. console.error('createOffer failed', e);
  10144. },
  10145. this.media_constraints
  10146. );
  10147. };
  10148. JingleSession.prototype.createdOffer = function (sdp) {
  10149. //console.log('createdOffer', sdp);
  10150. var self = this;
  10151. this.localSDP = new SDP(sdp.sdp);
  10152. //this.localSDP.mangle();
  10153. var sendJingle = function () {
  10154. var init = $iq({to: this.peerjid,
  10155. type: 'set'})
  10156. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10157. action: 'session-initiate',
  10158. initiator: this.initiator,
  10159. sid: this.sid});
  10160. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10161. self.connection.sendIQ(init,
  10162. function () {
  10163. var ack = {};
  10164. ack.source = 'offer';
  10165. $(document).trigger('ack.jingle', [self.sid, ack]);
  10166. },
  10167. function (stanza) {
  10168. self.state = 'error';
  10169. self.peerconnection.close();
  10170. var error = ($(stanza).find('error').length) ? {
  10171. code: $(stanza).find('error').attr('code'),
  10172. reason: $(stanza).find('error :first')[0].tagName,
  10173. }:{};
  10174. error.source = 'offer';
  10175. JingleSession.onJingleError(self.sid, error);
  10176. },
  10177. 10000);
  10178. }
  10179. sdp.sdp = this.localSDP.raw;
  10180. this.peerconnection.setLocalDescription(sdp,
  10181. function () {
  10182. if(self.usetrickle)
  10183. {
  10184. sendJingle();
  10185. }
  10186. self.setLocalDescription();
  10187. //console.log('setLocalDescription success');
  10188. },
  10189. function (e) {
  10190. console.error('setLocalDescription failed', e);
  10191. }
  10192. );
  10193. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10194. for (var i = 0; i < cands.length; i++) {
  10195. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10196. if (cand.type == 'srflx') {
  10197. this.hadstuncandidate = true;
  10198. } else if (cand.type == 'relay') {
  10199. this.hadturncandidate = true;
  10200. }
  10201. }
  10202. };
  10203. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10204. //console.log('setting remote description... ', desctype);
  10205. this.remoteSDP = new SDP('');
  10206. this.remoteSDP.fromJingle(elem);
  10207. if (this.peerconnection.remoteDescription !== null) {
  10208. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10209. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10210. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10211. for (var i = 0; i < pranswer.media.length; i++) {
  10212. // make sure we have ice ufrag and pwd
  10213. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10214. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10215. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10216. } else {
  10217. console.warn('no ice ufrag?');
  10218. }
  10219. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10220. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10221. } else {
  10222. console.warn('no ice pwd?');
  10223. }
  10224. }
  10225. // copy over candidates
  10226. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10227. for (var j = 0; j < lines.length; j++) {
  10228. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10229. }
  10230. }
  10231. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10232. }
  10233. }
  10234. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10235. this.peerconnection.setRemoteDescription(remotedesc,
  10236. function () {
  10237. //console.log('setRemoteDescription success');
  10238. },
  10239. function (e) {
  10240. console.error('setRemoteDescription error', e);
  10241. JingleSession.onJingleFatalError(self, e);
  10242. }
  10243. );
  10244. };
  10245. JingleSession.prototype.addIceCandidate = function (elem) {
  10246. var self = this;
  10247. if (this.peerconnection.signalingState == 'closed') {
  10248. return;
  10249. }
  10250. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10251. console.log('trickle ice candidate arriving before session accept...');
  10252. // create a PRANSWER for setRemoteDescription
  10253. if (!this.remoteSDP) {
  10254. var cobbled = 'v=0\r\n' +
  10255. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10256. 's=-\r\n' +
  10257. 't=0 0\r\n';
  10258. // first, take some things from the local description
  10259. for (var i = 0; i < this.localSDP.media.length; i++) {
  10260. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10261. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10262. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10263. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10264. }
  10265. cobbled += 'a=inactive\r\n';
  10266. }
  10267. this.remoteSDP = new SDP(cobbled);
  10268. }
  10269. // then add things like ice and dtls from remote candidate
  10270. elem.each(function () {
  10271. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10272. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10273. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10274. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10275. var tmp = $(this).find('transport');
  10276. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10277. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10278. tmp = $(this).find('transport>fingerprint');
  10279. if (tmp.length) {
  10280. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10281. } else {
  10282. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10283. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10284. }
  10285. break;
  10286. }
  10287. }
  10288. }
  10289. });
  10290. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10291. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10292. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10293. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10294. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10295. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10296. }).length == this.remoteSDP.media.length;
  10297. if (iscomplete) {
  10298. console.log('setting pranswer');
  10299. try {
  10300. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10301. function() {
  10302. },
  10303. function(e) {
  10304. console.log('setRemoteDescription pranswer failed', e.toString());
  10305. });
  10306. } catch (e) {
  10307. console.error('setting pranswer failed', e);
  10308. }
  10309. } else {
  10310. //console.log('not yet setting pranswer');
  10311. }
  10312. }
  10313. // operate on each content element
  10314. elem.each(function () {
  10315. // would love to deactivate this, but firefox still requires it
  10316. var idx = -1;
  10317. var i;
  10318. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10319. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10320. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10321. idx = i;
  10322. break;
  10323. }
  10324. }
  10325. if (idx == -1) { // fall back to localdescription
  10326. for (i = 0; i < self.localSDP.media.length; i++) {
  10327. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10328. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10329. idx = i;
  10330. break;
  10331. }
  10332. }
  10333. }
  10334. var name = $(this).attr('name');
  10335. // TODO: check ice-pwd and ice-ufrag?
  10336. $(this).find('transport>candidate').each(function () {
  10337. var line, candidate;
  10338. line = SDPUtil.candidateFromJingle(this);
  10339. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10340. sdpMid: name,
  10341. candidate: line});
  10342. try {
  10343. self.peerconnection.addIceCandidate(candidate);
  10344. } catch (e) {
  10345. console.error('addIceCandidate failed', e.toString(), line);
  10346. }
  10347. });
  10348. });
  10349. };
  10350. JingleSession.prototype.sendAnswer = function (provisional) {
  10351. //console.log('createAnswer', provisional);
  10352. var self = this;
  10353. this.peerconnection.createAnswer(
  10354. function (sdp) {
  10355. self.createdAnswer(sdp, provisional);
  10356. },
  10357. function (e) {
  10358. console.error('createAnswer failed', e);
  10359. },
  10360. this.media_constraints
  10361. );
  10362. };
  10363. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10364. //console.log('createAnswer callback');
  10365. var self = this;
  10366. this.localSDP = new SDP(sdp.sdp);
  10367. //this.localSDP.mangle();
  10368. this.usepranswer = provisional === true;
  10369. if (this.usetrickle) {
  10370. if (this.usepranswer) {
  10371. sdp.type = 'pranswer';
  10372. for (var i = 0; i < this.localSDP.media.length; i++) {
  10373. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10374. }
  10375. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10376. }
  10377. }
  10378. var self = this;
  10379. var sendJingle = function (ssrcs) {
  10380. var accept = $iq({to: self.peerjid,
  10381. type: 'set'})
  10382. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10383. action: 'session-accept',
  10384. initiator: self.initiator,
  10385. responder: self.responder,
  10386. sid: self.sid });
  10387. self.localSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10388. self.connection.sendIQ(accept,
  10389. function () {
  10390. var ack = {};
  10391. ack.source = 'answer';
  10392. $(document).trigger('ack.jingle', [self.sid, ack]);
  10393. },
  10394. function (stanza) {
  10395. var error = ($(stanza).find('error').length) ? {
  10396. code: $(stanza).find('error').attr('code'),
  10397. reason: $(stanza).find('error :first')[0].tagName,
  10398. }:{};
  10399. error.source = 'answer';
  10400. JingleSession.onJingleError(self.sid, error);
  10401. },
  10402. 10000);
  10403. }
  10404. sdp.sdp = this.localSDP.raw;
  10405. this.peerconnection.setLocalDescription(sdp,
  10406. function () {
  10407. //console.log('setLocalDescription success');
  10408. if (self.usetrickle && !self.usepranswer) {
  10409. sendJingle();
  10410. }
  10411. self.setLocalDescription();
  10412. },
  10413. function (e) {
  10414. console.error('setLocalDescription failed', e);
  10415. }
  10416. );
  10417. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10418. for (var j = 0; j < cands.length; j++) {
  10419. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10420. if (cand.type == 'srflx') {
  10421. this.hadstuncandidate = true;
  10422. } else if (cand.type == 'relay') {
  10423. this.hadturncandidate = true;
  10424. }
  10425. }
  10426. };
  10427. JingleSession.prototype.sendTerminate = function (reason, text) {
  10428. var self = this,
  10429. term = $iq({to: this.peerjid,
  10430. type: 'set'})
  10431. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10432. action: 'session-terminate',
  10433. initiator: this.initiator,
  10434. sid: this.sid})
  10435. .c('reason')
  10436. .c(reason || 'success');
  10437. if (text) {
  10438. term.up().c('text').t(text);
  10439. }
  10440. this.connection.sendIQ(term,
  10441. function () {
  10442. self.peerconnection.close();
  10443. self.peerconnection = null;
  10444. self.terminate();
  10445. var ack = {};
  10446. ack.source = 'terminate';
  10447. $(document).trigger('ack.jingle', [self.sid, ack]);
  10448. },
  10449. function (stanza) {
  10450. var error = ($(stanza).find('error').length) ? {
  10451. code: $(stanza).find('error').attr('code'),
  10452. reason: $(stanza).find('error :first')[0].tagName,
  10453. }:{};
  10454. $(document).trigger('ack.jingle', [self.sid, error]);
  10455. },
  10456. 10000);
  10457. if (this.statsinterval !== null) {
  10458. window.clearInterval(this.statsinterval);
  10459. this.statsinterval = null;
  10460. }
  10461. };
  10462. JingleSession.prototype.addSource = function (elem, fromJid) {
  10463. var self = this;
  10464. // FIXME: dirty waiting
  10465. if (!this.peerconnection.localDescription)
  10466. {
  10467. console.warn("addSource - localDescription not ready yet")
  10468. setTimeout(function()
  10469. {
  10470. self.addSource(elem, fromJid);
  10471. },
  10472. 200
  10473. );
  10474. return;
  10475. }
  10476. console.log('addssrc', new Date().getTime());
  10477. console.log('ice', this.peerconnection.iceConnectionState);
  10478. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10479. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10480. $(elem).each(function (idx, content) {
  10481. var name = $(content).attr('name');
  10482. var lines = '';
  10483. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10484. var semantics = this.getAttribute('semantics');
  10485. var ssrcs = $(this).find('>source').map(function () {
  10486. return this.getAttribute('ssrc');
  10487. }).get();
  10488. if (ssrcs.length != 0) {
  10489. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10490. }
  10491. });
  10492. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10493. tmp.each(function () {
  10494. var ssrc = $(this).attr('ssrc');
  10495. if(mySdp.containsSSRC(ssrc)){
  10496. /**
  10497. * This happens when multiple participants change their streams at the same time and
  10498. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10499. * addssrc are scheduled for update IQ. See
  10500. */
  10501. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10502. return;
  10503. }
  10504. $(this).find('>parameter').each(function () {
  10505. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10506. if ($(this).attr('value') && $(this).attr('value').length)
  10507. lines += ':' + $(this).attr('value');
  10508. lines += '\r\n';
  10509. });
  10510. });
  10511. sdp.media.forEach(function(media, idx) {
  10512. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10513. return;
  10514. sdp.media[idx] += lines;
  10515. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10516. self.addssrc[idx] += lines;
  10517. });
  10518. sdp.raw = sdp.session + sdp.media.join('');
  10519. });
  10520. this.modifySourcesQueue.push(function() {
  10521. // When a source is added and if this is FF, a new channel is allocated
  10522. // for receiving the added source. We need to diffuse the SSRC of this
  10523. // new recvonly channel to the rest of the peers.
  10524. console.log('modify sources done');
  10525. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  10526. console.log("SDPs", mySdp, newSdp);
  10527. self.notifyMySSRCUpdate(mySdp, newSdp);
  10528. });
  10529. };
  10530. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10531. var self = this;
  10532. // FIXME: dirty waiting
  10533. if (!this.peerconnection.localDescription)
  10534. {
  10535. console.warn("removeSource - localDescription not ready yet")
  10536. setTimeout(function()
  10537. {
  10538. self.removeSource(elem, fromJid);
  10539. },
  10540. 200
  10541. );
  10542. return;
  10543. }
  10544. console.log('removessrc', new Date().getTime());
  10545. console.log('ice', this.peerconnection.iceConnectionState);
  10546. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10547. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10548. $(elem).each(function (idx, content) {
  10549. var name = $(content).attr('name');
  10550. var lines = '';
  10551. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10552. var semantics = this.getAttribute('semantics');
  10553. var ssrcs = $(this).find('>source').map(function () {
  10554. return this.getAttribute('ssrc');
  10555. }).get();
  10556. if (ssrcs.length != 0) {
  10557. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10558. }
  10559. });
  10560. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10561. tmp.each(function () {
  10562. var ssrc = $(this).attr('ssrc');
  10563. // This should never happen, but can be useful for bug detection
  10564. if(mySdp.containsSSRC(ssrc)){
  10565. console.error("Got remove stream request for my own ssrc: "+ssrc);
  10566. return;
  10567. }
  10568. $(this).find('>parameter').each(function () {
  10569. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10570. if ($(this).attr('value') && $(this).attr('value').length)
  10571. lines += ':' + $(this).attr('value');
  10572. lines += '\r\n';
  10573. });
  10574. });
  10575. sdp.media.forEach(function(media, idx) {
  10576. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10577. return;
  10578. sdp.media[idx] += lines;
  10579. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  10580. self.removessrc[idx] += lines;
  10581. });
  10582. sdp.raw = sdp.session + sdp.media.join('');
  10583. });
  10584. this.modifySourcesQueue.push(function() {
  10585. // When a source is removed and if this is FF, the recvonly channel that
  10586. // receives the remote stream is deactivated . We need to diffuse the
  10587. // recvonly SSRC removal to the rest of the peers.
  10588. console.log('modify sources done');
  10589. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  10590. console.log("SDPs", mySdp, newSdp);
  10591. self.notifyMySSRCUpdate(mySdp, newSdp);
  10592. });
  10593. };
  10594. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  10595. var self = this;
  10596. if (this.peerconnection.signalingState == 'closed') return;
  10597. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  10598. // There is nothing to do since scheduled job might have been executed by another succeeding call
  10599. this.setLocalDescription();
  10600. if(successCallback){
  10601. successCallback();
  10602. }
  10603. queueCallback();
  10604. return;
  10605. }
  10606. // Reset switch streams flag
  10607. this.switchstreams = false;
  10608. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10609. // add sources
  10610. this.addssrc.forEach(function(lines, idx) {
  10611. sdp.media[idx] += lines;
  10612. });
  10613. this.addssrc = [];
  10614. // remove sources
  10615. this.removessrc.forEach(function(lines, idx) {
  10616. lines = lines.split('\r\n');
  10617. lines.pop(); // remove empty last element;
  10618. lines.forEach(function(line) {
  10619. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  10620. });
  10621. });
  10622. this.removessrc = [];
  10623. // FIXME:
  10624. // this was a hack for the situation when only one peer exists
  10625. // in the conference.
  10626. // check if still required and remove
  10627. if (sdp.media[0])
  10628. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  10629. if (sdp.media[1])
  10630. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10631. sdp.raw = sdp.session + sdp.media.join('');
  10632. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  10633. function() {
  10634. if(self.signalingState == 'closed') {
  10635. console.error("createAnswer attempt on closed state");
  10636. queueCallback("createAnswer attempt on closed state");
  10637. return;
  10638. }
  10639. self.peerconnection.createAnswer(
  10640. function(modifiedAnswer) {
  10641. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  10642. if (self.pendingop !== null) {
  10643. var sdp = new SDP(modifiedAnswer.sdp);
  10644. if (sdp.media.length > 1) {
  10645. switch(self.pendingop) {
  10646. case 'mute':
  10647. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  10648. break;
  10649. case 'unmute':
  10650. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10651. break;
  10652. }
  10653. sdp.raw = sdp.session + sdp.media.join('');
  10654. modifiedAnswer.sdp = sdp.raw;
  10655. }
  10656. self.pendingop = null;
  10657. }
  10658. // FIXME: pushing down an answer while ice connection state
  10659. // is still checking is bad...
  10660. //console.log(self.peerconnection.iceConnectionState);
  10661. // trying to work around another chrome bug
  10662. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  10663. self.peerconnection.setLocalDescription(modifiedAnswer,
  10664. function() {
  10665. //console.log('modified setLocalDescription ok');
  10666. self.setLocalDescription();
  10667. if(successCallback){
  10668. successCallback();
  10669. }
  10670. queueCallback();
  10671. },
  10672. function(error) {
  10673. console.error('modified setLocalDescription failed', error);
  10674. queueCallback(error);
  10675. }
  10676. );
  10677. },
  10678. function(error) {
  10679. console.error('modified answer failed', error);
  10680. queueCallback(error);
  10681. }
  10682. );
  10683. },
  10684. function(error) {
  10685. console.error('modify failed', error);
  10686. queueCallback(error);
  10687. }
  10688. );
  10689. };
  10690. /**
  10691. * Switches video streams.
  10692. * @param new_stream new stream that will be used as video of this session.
  10693. * @param oldStream old video stream of this session.
  10694. * @param success_callback callback executed after successful stream switch.
  10695. */
  10696. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  10697. var self = this;
  10698. // Remember SDP to figure out added/removed SSRCs
  10699. var oldSdp = null;
  10700. if(self.peerconnection) {
  10701. if(self.peerconnection.localDescription) {
  10702. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  10703. }
  10704. self.peerconnection.removeStream(oldStream, true);
  10705. if(new_stream)
  10706. self.peerconnection.addStream(new_stream);
  10707. }
  10708. if(!isAudio)
  10709. APP.RTC.switchVideoStreams(new_stream, oldStream);
  10710. // Conference is not active
  10711. if(!oldSdp || !self.peerconnection) {
  10712. success_callback();
  10713. return;
  10714. }
  10715. self.switchstreams = true;
  10716. self.modifySourcesQueue.push(function() {
  10717. console.log('modify sources done');
  10718. success_callback();
  10719. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  10720. console.log("SDPs", oldSdp, newSdp);
  10721. self.notifyMySSRCUpdate(oldSdp, newSdp);
  10722. });
  10723. };
  10724. /**
  10725. * Figures out added/removed ssrcs and send update IQs.
  10726. * @param old_sdp SDP object for old description.
  10727. * @param new_sdp SDP object for new description.
  10728. */
  10729. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  10730. if (!(this.peerconnection.signalingState == 'stable' &&
  10731. this.peerconnection.iceConnectionState == 'connected')){
  10732. console.log("Too early to send updates");
  10733. return;
  10734. }
  10735. // send source-remove IQ.
  10736. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  10737. var remove = $iq({to: this.peerjid, type: 'set'})
  10738. .c('jingle', {
  10739. xmlns: 'urn:xmpp:jingle:1',
  10740. action: 'source-remove',
  10741. initiator: this.initiator,
  10742. sid: this.sid
  10743. }
  10744. );
  10745. var removed = sdpDiffer.toJingle(remove);
  10746. if (removed) {
  10747. this.connection.sendIQ(remove,
  10748. function (res) {
  10749. console.info('got remove result', res);
  10750. },
  10751. function (err) {
  10752. console.error('got remove error', err);
  10753. }
  10754. );
  10755. } else {
  10756. console.log('removal not necessary');
  10757. }
  10758. // send source-add IQ.
  10759. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  10760. var add = $iq({to: this.peerjid, type: 'set'})
  10761. .c('jingle', {
  10762. xmlns: 'urn:xmpp:jingle:1',
  10763. action: 'source-add',
  10764. initiator: this.initiator,
  10765. sid: this.sid
  10766. }
  10767. );
  10768. var added = sdpDiffer.toJingle(add);
  10769. if (added) {
  10770. this.connection.sendIQ(add,
  10771. function (res) {
  10772. console.info('got add result', res);
  10773. },
  10774. function (err) {
  10775. console.error('got add error', err);
  10776. }
  10777. );
  10778. } else {
  10779. console.log('addition not necessary');
  10780. }
  10781. };
  10782. /**
  10783. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  10784. *
  10785. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  10786. * tracks; otherwise, <tt>false</tt>
  10787. * @param callback a function to be invoked with <tt>mute</tt> after all video
  10788. * tracks have been enabled/disabled. The function may, optionally, return
  10789. * another function which is to be invoked after the whole mute/unmute operation
  10790. * has completed successfully.
  10791. * @param options an object which specifies optional arguments such as the
  10792. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  10793. * specifies whether the method was initiated in response to a user command (in
  10794. * contrast to an automatic decision made by the application logic)
  10795. */
  10796. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  10797. var byUser;
  10798. if (options) {
  10799. byUser = options.byUser;
  10800. if (typeof byUser === 'undefined') {
  10801. byUser = true;
  10802. }
  10803. } else {
  10804. byUser = true;
  10805. }
  10806. // The user's command to mute the (local) video takes precedence over any
  10807. // automatic decision made by the application logic.
  10808. if (byUser) {
  10809. this.videoMuteByUser = mute;
  10810. } else if (this.videoMuteByUser) {
  10811. return;
  10812. }
  10813. this.hardMuteVideo(mute);
  10814. var self = this;
  10815. var oldSdp = null;
  10816. if(self.peerconnection) {
  10817. if(self.peerconnection.localDescription) {
  10818. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  10819. }
  10820. }
  10821. this.modifySourcesQueue.push(function() {
  10822. console.log('modify sources done');
  10823. callback(mute);
  10824. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  10825. console.log("SDPs", oldSdp, newSdp);
  10826. self.notifyMySSRCUpdate(oldSdp, newSdp);
  10827. });
  10828. };
  10829. JingleSession.prototype.hardMuteVideo = function (muted) {
  10830. this.pendingop = muted ? 'mute' : 'unmute';
  10831. };
  10832. JingleSession.prototype.sendMute = function (muted, content) {
  10833. var info = $iq({to: this.peerjid,
  10834. type: 'set'})
  10835. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10836. action: 'session-info',
  10837. initiator: this.initiator,
  10838. sid: this.sid });
  10839. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  10840. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  10841. if (content) {
  10842. info.attrs({'name': content});
  10843. }
  10844. this.connection.send(info);
  10845. };
  10846. JingleSession.prototype.sendRinging = function () {
  10847. var info = $iq({to: this.peerjid,
  10848. type: 'set'})
  10849. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10850. action: 'session-info',
  10851. initiator: this.initiator,
  10852. sid: this.sid });
  10853. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  10854. this.connection.send(info);
  10855. };
  10856. JingleSession.prototype.getStats = function (interval) {
  10857. var self = this;
  10858. var recv = {audio: 0, video: 0};
  10859. var lost = {audio: 0, video: 0};
  10860. var lastrecv = {audio: 0, video: 0};
  10861. var lastlost = {audio: 0, video: 0};
  10862. var loss = {audio: 0, video: 0};
  10863. var delta = {audio: 0, video: 0};
  10864. this.statsinterval = window.setInterval(function () {
  10865. if (self && self.peerconnection && self.peerconnection.getStats) {
  10866. self.peerconnection.getStats(function (stats) {
  10867. var results = stats.result();
  10868. // TODO: there are so much statistics you can get from this..
  10869. for (var i = 0; i < results.length; ++i) {
  10870. if (results[i].type == 'ssrc') {
  10871. var packetsrecv = results[i].stat('packetsReceived');
  10872. var packetslost = results[i].stat('packetsLost');
  10873. if (packetsrecv && packetslost) {
  10874. packetsrecv = parseInt(packetsrecv, 10);
  10875. packetslost = parseInt(packetslost, 10);
  10876. if (results[i].stat('googFrameRateReceived')) {
  10877. lastlost.video = lost.video;
  10878. lastrecv.video = recv.video;
  10879. recv.video = packetsrecv;
  10880. lost.video = packetslost;
  10881. } else {
  10882. lastlost.audio = lost.audio;
  10883. lastrecv.audio = recv.audio;
  10884. recv.audio = packetsrecv;
  10885. lost.audio = packetslost;
  10886. }
  10887. }
  10888. }
  10889. }
  10890. delta.audio = recv.audio - lastrecv.audio;
  10891. delta.video = recv.video - lastrecv.video;
  10892. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  10893. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  10894. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  10895. });
  10896. }
  10897. }, interval || 3000);
  10898. return this.statsinterval;
  10899. };
  10900. JingleSession.onJingleError = function (session, error)
  10901. {
  10902. console.error("Jingle error", error);
  10903. }
  10904. JingleSession.onJingleFatalError = function (session, error)
  10905. {
  10906. this.service.sessionTerminated = true;
  10907. this.connection.emuc.doLeave();
  10908. APP.UI.messageHandler.showError("dialog.sorry",
  10909. "dialog.internalError");
  10910. }
  10911. JingleSession.prototype.setLocalDescription = function () {
  10912. // put our ssrcs into presence so other clients can identify our stream
  10913. var newssrcs = [];
  10914. var session = transform.parse(this.peerconnection.localDescription.sdp);
  10915. session.media.forEach(function (media) {
  10916. if (media.ssrcs != null && media.ssrcs.length > 0) {
  10917. // TODO(gp) maybe exclude FID streams?
  10918. media.ssrcs.forEach(function (ssrc) {
  10919. if (ssrc.attribute !== 'cname') {
  10920. return;
  10921. }
  10922. newssrcs.push({
  10923. 'ssrc': ssrc.id,
  10924. 'type': media.type,
  10925. 'direction': media.direction
  10926. });
  10927. });
  10928. }
  10929. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  10930. {
  10931. newssrcs.push({
  10932. 'ssrc': this.localStreamsSSRC[media.type],
  10933. 'type': media.type,
  10934. 'direction': media.direction
  10935. });
  10936. }
  10937. });
  10938. console.log('new ssrcs', newssrcs);
  10939. // Have to clear presence map to get rid of removed streams
  10940. this.connection.emuc.clearPresenceMedia();
  10941. if (newssrcs.length > 0) {
  10942. for (var i = 1; i <= newssrcs.length; i ++) {
  10943. // Change video type to screen
  10944. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  10945. newssrcs[i-1].type = 'screen';
  10946. }
  10947. this.connection.emuc.addMediaToPresence(i,
  10948. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  10949. }
  10950. this.connection.emuc.sendPresence();
  10951. }
  10952. }
  10953. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  10954. function sendKeyframe(pc) {
  10955. console.log('sendkeyframe', pc.iceConnectionState);
  10956. if (pc.iceConnectionState !== 'connected') return; // safe...
  10957. pc.setRemoteDescription(
  10958. pc.remoteDescription,
  10959. function () {
  10960. pc.createAnswer(
  10961. function (modifiedAnswer) {
  10962. pc.setLocalDescription(
  10963. modifiedAnswer,
  10964. function () {
  10965. // noop
  10966. },
  10967. function (error) {
  10968. console.log('triggerKeyframe setLocalDescription failed', error);
  10969. APP.UI.messageHandler.showError();
  10970. }
  10971. );
  10972. },
  10973. function (error) {
  10974. console.log('triggerKeyframe createAnswer failed', error);
  10975. APP.UI.messageHandler.showError();
  10976. }
  10977. );
  10978. },
  10979. function (error) {
  10980. console.log('triggerKeyframe setRemoteDescription failed', error);
  10981. APP.UI.messageHandler.showError();
  10982. }
  10983. );
  10984. }
  10985. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  10986. var self = this;
  10987. var thessrc;
  10988. var ssrc2jid = this.connection.emuc.ssrc2jid;
  10989. // look up an associated JID for a stream id
  10990. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  10991. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  10992. var ssrclines
  10993. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  10994. ssrclines = ssrclines.filter(function (line) {
  10995. // NOTE(gp) previously we filtered on the mslabel, but that property
  10996. // is not always present.
  10997. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  10998. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  10999. });
  11000. if (ssrclines.length) {
  11001. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11002. // We signal our streams (through Jingle to the focus) before we set
  11003. // our presence (through which peers associate remote streams to
  11004. // jids). So, it might arrive that a remote stream is added but
  11005. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11006. // successfully set. Here we wait for up to a second for the
  11007. // presence to arrive.
  11008. if (!ssrc2jid[thessrc]) {
  11009. if (typeof times === 'undefined')
  11010. {
  11011. times = 0;
  11012. }
  11013. if (times > 10)
  11014. {
  11015. console.warning('Waiting for jid timed out', thessrc);
  11016. }
  11017. else
  11018. {
  11019. setTimeout(function(d) {
  11020. return function() {
  11021. self.remoteStreamAdded(d, times++);
  11022. }
  11023. }(data), 250);
  11024. }
  11025. return;
  11026. }
  11027. // ok to overwrite the one from focus? might save work in colibri.js
  11028. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11029. if (ssrc2jid[thessrc]) {
  11030. data.peerjid = ssrc2jid[thessrc];
  11031. }
  11032. }
  11033. }
  11034. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11035. var isVideo = data.stream.getVideoTracks().length > 0;
  11036. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11037. if (isVideo &&
  11038. data.peerjid && this.peerjid === data.peerjid &&
  11039. data.stream.getVideoTracks().length === 0 &&
  11040. APP.RTC.localVideo.getTracks().length > 0) {
  11041. window.setTimeout(function () {
  11042. sendKeyframe(self.peerconnection);
  11043. }, 3000);
  11044. }
  11045. }
  11046. module.exports = JingleSession;
  11047. },{"../../service/RTC/RTCBrowserType":102,"./SDP":47,"./SDPDiffer":48,"./SDPUtil":49,"./TraceablePeerConnection":50,"async":60,"sdp-transform":98}],47:[function(require,module,exports){
  11048. /* jshint -W117 */
  11049. var SDPUtil = require("./SDPUtil");
  11050. // SDP STUFF
  11051. function SDP(sdp) {
  11052. this.media = sdp.split('\r\nm=');
  11053. for (var i = 1; i < this.media.length; i++) {
  11054. this.media[i] = 'm=' + this.media[i];
  11055. if (i != this.media.length - 1) {
  11056. this.media[i] += '\r\n';
  11057. }
  11058. }
  11059. this.session = this.media.shift() + '\r\n';
  11060. this.raw = this.session + this.media.join('');
  11061. }
  11062. /**
  11063. * Returns map of MediaChannel mapped per channel idx.
  11064. */
  11065. SDP.prototype.getMediaSsrcMap = function() {
  11066. var self = this;
  11067. var media_ssrcs = {};
  11068. var tmp;
  11069. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11070. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11071. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11072. var media = {
  11073. mediaindex: mediaindex,
  11074. mid: mid,
  11075. ssrcs: {},
  11076. ssrcGroups: []
  11077. };
  11078. media_ssrcs[mediaindex] = media;
  11079. tmp.forEach(function (line) {
  11080. var linessrc = line.substring(7).split(' ')[0];
  11081. // allocate new ChannelSsrc
  11082. if(!media.ssrcs[linessrc]) {
  11083. media.ssrcs[linessrc] = {
  11084. ssrc: linessrc,
  11085. lines: []
  11086. };
  11087. }
  11088. media.ssrcs[linessrc].lines.push(line);
  11089. });
  11090. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11091. tmp.forEach(function(line){
  11092. var semantics = line.substr(0, idx).substr(13);
  11093. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11094. if (ssrcs.length != 0) {
  11095. media.ssrcGroups.push({
  11096. semantics: semantics,
  11097. ssrcs: ssrcs
  11098. });
  11099. }
  11100. });
  11101. }
  11102. return media_ssrcs;
  11103. };
  11104. /**
  11105. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11106. * @param ssrc the ssrc to check.
  11107. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11108. */
  11109. SDP.prototype.containsSSRC = function(ssrc) {
  11110. var medias = this.getMediaSsrcMap();
  11111. var contains = false;
  11112. Object.keys(medias).forEach(function(mediaindex){
  11113. var media = medias[mediaindex];
  11114. //console.log("Check", channel, ssrc);
  11115. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11116. contains = true;
  11117. }
  11118. });
  11119. return contains;
  11120. };
  11121. // remove iSAC and CN from SDP
  11122. SDP.prototype.mangle = function () {
  11123. var i, j, mline, lines, rtpmap, newdesc;
  11124. for (i = 0; i < this.media.length; i++) {
  11125. lines = this.media[i].split('\r\n');
  11126. lines.pop(); // remove empty last element
  11127. mline = SDPUtil.parse_mline(lines.shift());
  11128. if (mline.media != 'audio')
  11129. continue;
  11130. newdesc = '';
  11131. mline.fmt.length = 0;
  11132. for (j = 0; j < lines.length; j++) {
  11133. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11134. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11135. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11136. continue;
  11137. mline.fmt.push(rtpmap.id);
  11138. newdesc += lines[j] + '\r\n';
  11139. } else {
  11140. newdesc += lines[j] + '\r\n';
  11141. }
  11142. }
  11143. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11144. this.media[i] += newdesc;
  11145. }
  11146. this.raw = this.session + this.media.join('');
  11147. };
  11148. // remove lines matching prefix from session section
  11149. SDP.prototype.removeSessionLines = function(prefix) {
  11150. var self = this;
  11151. var lines = SDPUtil.find_lines(this.session, prefix);
  11152. lines.forEach(function(line) {
  11153. self.session = self.session.replace(line + '\r\n', '');
  11154. });
  11155. this.raw = this.session + this.media.join('');
  11156. return lines;
  11157. }
  11158. // remove lines matching prefix from a media section specified by mediaindex
  11159. // TODO: non-numeric mediaindex could match mid
  11160. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11161. var self = this;
  11162. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11163. lines.forEach(function(line) {
  11164. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11165. });
  11166. this.raw = this.session + this.media.join('');
  11167. return lines;
  11168. }
  11169. // add content's to a jingle element
  11170. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11171. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11172. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11173. var self = this;
  11174. // new bundle plan
  11175. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11176. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11177. for (i = 0; i < lines.length; i++) {
  11178. tmp = lines[i].split(' ');
  11179. var semantics = tmp.shift().substr(8);
  11180. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11181. for (j = 0; j < tmp.length; j++) {
  11182. elem.c('content', {name: tmp[j]}).up();
  11183. }
  11184. elem.up();
  11185. }
  11186. }
  11187. for (i = 0; i < this.media.length; i++) {
  11188. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11189. if (!(mline.media === 'audio' ||
  11190. mline.media === 'video' ||
  11191. mline.media === 'application'))
  11192. {
  11193. continue;
  11194. }
  11195. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11196. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11197. } else {
  11198. if(ssrcs && ssrcs[mline.media])
  11199. {
  11200. ssrc = ssrcs[mline.media];
  11201. }
  11202. else
  11203. ssrc = false;
  11204. }
  11205. elem.c('content', {creator: thecreator, name: mline.media});
  11206. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11207. // prefer identifier from a=mid if present
  11208. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11209. elem.attrs({ name: mid });
  11210. }
  11211. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11212. {
  11213. elem.c('description',
  11214. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11215. media: mline.media });
  11216. if (ssrc) {
  11217. elem.attrs({ssrc: ssrc});
  11218. }
  11219. for (j = 0; j < mline.fmt.length; j++) {
  11220. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11221. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11222. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11223. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11224. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11225. for (k = 0; k < tmp.length; k++) {
  11226. elem.c('parameter', tmp[k]).up();
  11227. }
  11228. }
  11229. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11230. elem.up();
  11231. }
  11232. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11233. elem.c('encryption', {required: 1});
  11234. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11235. crypto.forEach(function(line) {
  11236. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11237. });
  11238. elem.up(); // end of encryption
  11239. }
  11240. if (ssrc) {
  11241. // new style mapping
  11242. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11243. // FIXME: group by ssrc and support multiple different ssrcs
  11244. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11245. if(ssrclines.length > 0) {
  11246. ssrclines.forEach(function (line) {
  11247. idx = line.indexOf(' ');
  11248. var linessrc = line.substr(0, idx).substr(7);
  11249. if (linessrc != ssrc) {
  11250. elem.up();
  11251. ssrc = linessrc;
  11252. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11253. }
  11254. var kv = line.substr(idx + 1);
  11255. elem.c('parameter');
  11256. if (kv.indexOf(':') == -1) {
  11257. elem.attrs({ name: kv });
  11258. } else {
  11259. elem.attrs({ name: kv.split(':', 2)[0] });
  11260. elem.attrs({ value: kv.split(':', 2)[1] });
  11261. }
  11262. elem.up();
  11263. });
  11264. elem.up();
  11265. }
  11266. else
  11267. {
  11268. elem.up();
  11269. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11270. elem.c('parameter');
  11271. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11272. elem.up();
  11273. var msid = null;
  11274. if(mline.media == "audio")
  11275. {
  11276. msid = APP.RTC.localAudio.getId();
  11277. }
  11278. else
  11279. {
  11280. msid = APP.RTC.localVideo.getId();
  11281. }
  11282. if(msid != null)
  11283. {
  11284. msid = msid.replace(/[\{,\}]/g,"");
  11285. elem.c('parameter');
  11286. elem.attrs({name: "msid", value:msid});
  11287. elem.up();
  11288. elem.c('parameter');
  11289. elem.attrs({name: "mslabel", value:msid});
  11290. elem.up();
  11291. elem.c('parameter');
  11292. elem.attrs({name: "label", value:msid});
  11293. elem.up();
  11294. elem.up();
  11295. }
  11296. }
  11297. // XEP-0339 handle ssrc-group attributes
  11298. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11299. ssrc_group_lines.forEach(function(line) {
  11300. idx = line.indexOf(' ');
  11301. var semantics = line.substr(0, idx).substr(13);
  11302. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11303. if (ssrcs.length != 0) {
  11304. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11305. ssrcs.forEach(function(ssrc) {
  11306. elem.c('source', { ssrc: ssrc })
  11307. .up();
  11308. });
  11309. elem.up();
  11310. }
  11311. });
  11312. }
  11313. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11314. elem.c('rtcp-mux').up();
  11315. }
  11316. // XEP-0293 -- map a=rtcp-fb:*
  11317. this.RtcpFbToJingle(i, elem, '*');
  11318. // XEP-0294
  11319. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11320. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11321. for (j = 0; j < lines.length; j++) {
  11322. tmp = SDPUtil.parse_extmap(lines[j]);
  11323. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11324. uri: tmp.uri,
  11325. id: tmp.value });
  11326. if (tmp.hasOwnProperty('direction')) {
  11327. switch (tmp.direction) {
  11328. case 'sendonly':
  11329. elem.attrs({senders: 'responder'});
  11330. break;
  11331. case 'recvonly':
  11332. elem.attrs({senders: 'initiator'});
  11333. break;
  11334. case 'sendrecv':
  11335. elem.attrs({senders: 'both'});
  11336. break;
  11337. case 'inactive':
  11338. elem.attrs({senders: 'none'});
  11339. break;
  11340. }
  11341. }
  11342. // TODO: handle params
  11343. elem.up();
  11344. }
  11345. }
  11346. elem.up(); // end of description
  11347. }
  11348. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11349. this.TransportToJingle(i, elem);
  11350. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11351. elem.attrs({senders: 'both'});
  11352. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11353. elem.attrs({senders: 'initiator'});
  11354. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11355. elem.attrs({senders: 'responder'});
  11356. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11357. elem.attrs({senders: 'none'});
  11358. }
  11359. if (mline.port == '0') {
  11360. // estos hack to reject an m-line
  11361. elem.attrs({senders: 'rejected'});
  11362. }
  11363. elem.up(); // end of content
  11364. }
  11365. elem.up();
  11366. return elem;
  11367. };
  11368. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11369. var i = mediaindex;
  11370. var tmp;
  11371. var self = this;
  11372. elem.c('transport');
  11373. // XEP-0343 DTLS/SCTP
  11374. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11375. {
  11376. var sctpmap = SDPUtil.find_line(
  11377. this.media[i], 'a=sctpmap:', self.session);
  11378. if (sctpmap)
  11379. {
  11380. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11381. elem.c('sctpmap',
  11382. {
  11383. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11384. number: sctpAttrs[0], /* SCTP port */
  11385. protocol: sctpAttrs[1], /* protocol */
  11386. });
  11387. // Optional stream count attribute
  11388. if (sctpAttrs.length > 2)
  11389. elem.attrs({ streams: sctpAttrs[2]});
  11390. elem.up();
  11391. }
  11392. }
  11393. // XEP-0320
  11394. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11395. fingerprints.forEach(function(line) {
  11396. tmp = SDPUtil.parse_fingerprint(line);
  11397. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11398. elem.c('fingerprint').t(tmp.fingerprint);
  11399. delete tmp.fingerprint;
  11400. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11401. if (line) {
  11402. tmp.setup = line.substr(8);
  11403. }
  11404. elem.attrs(tmp);
  11405. elem.up(); // end of fingerprint
  11406. });
  11407. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11408. if (tmp) {
  11409. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11410. elem.attrs(tmp);
  11411. // XEP-0176
  11412. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11413. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11414. lines.forEach(function (line) {
  11415. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11416. });
  11417. }
  11418. }
  11419. elem.up(); // end of transport
  11420. }
  11421. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11422. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11423. lines.forEach(function (line) {
  11424. var tmp = SDPUtil.parse_rtcpfb(line);
  11425. if (tmp.type == 'trr-int') {
  11426. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11427. elem.up();
  11428. } else {
  11429. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11430. if (tmp.params.length > 0) {
  11431. elem.attrs({'subtype': tmp.params[0]});
  11432. }
  11433. elem.up();
  11434. }
  11435. });
  11436. };
  11437. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11438. var media = '';
  11439. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11440. if (tmp.length) {
  11441. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11442. if (tmp.attr('value')) {
  11443. media += tmp.attr('value');
  11444. } else {
  11445. media += '0';
  11446. }
  11447. media += '\r\n';
  11448. }
  11449. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11450. tmp.each(function () {
  11451. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11452. if ($(this).attr('subtype')) {
  11453. media += ' ' + $(this).attr('subtype');
  11454. }
  11455. media += '\r\n';
  11456. });
  11457. return media;
  11458. };
  11459. // construct an SDP from a jingle stanza
  11460. SDP.prototype.fromJingle = function (jingle) {
  11461. var self = this;
  11462. this.raw = 'v=0\r\n' +
  11463. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11464. 's=-\r\n' +
  11465. 't=0 0\r\n';
  11466. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11467. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11468. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11469. var contents = $(group).find('>content').map(function (idx, content) {
  11470. return content.getAttribute('name');
  11471. }).get();
  11472. if (contents.length > 0) {
  11473. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11474. }
  11475. });
  11476. }
  11477. this.session = this.raw;
  11478. jingle.find('>content').each(function () {
  11479. var m = self.jingle2media($(this));
  11480. self.media.push(m);
  11481. });
  11482. // reconstruct msid-semantic -- apparently not necessary
  11483. /*
  11484. var msid = SDPUtil.parse_ssrc(this.raw);
  11485. if (msid.hasOwnProperty('mslabel')) {
  11486. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11487. }
  11488. */
  11489. this.raw = this.session + this.media.join('');
  11490. };
  11491. // translate a jingle content element into an an SDP media part
  11492. SDP.prototype.jingle2media = function (content) {
  11493. var media = '',
  11494. desc = content.find('description'),
  11495. ssrc = desc.attr('ssrc'),
  11496. self = this,
  11497. tmp;
  11498. var sctp = content.find(
  11499. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11500. tmp = { media: desc.attr('media') };
  11501. tmp.port = '1';
  11502. if (content.attr('senders') == 'rejected') {
  11503. // estos hack to reject an m-line.
  11504. tmp.port = '0';
  11505. }
  11506. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11507. if (sctp.length)
  11508. tmp.proto = 'DTLS/SCTP';
  11509. else
  11510. tmp.proto = 'RTP/SAVPF';
  11511. } else {
  11512. tmp.proto = 'RTP/AVPF';
  11513. }
  11514. if (!sctp.length)
  11515. {
  11516. tmp.fmt = desc.find('payload-type').map(
  11517. function () { return this.getAttribute('id'); }).get();
  11518. media += SDPUtil.build_mline(tmp) + '\r\n';
  11519. }
  11520. else
  11521. {
  11522. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11523. media += 'a=sctpmap:' + sctp.attr('number') +
  11524. ' ' + sctp.attr('protocol');
  11525. var streamCount = sctp.attr('streams');
  11526. if (streamCount)
  11527. media += ' ' + streamCount + '\r\n';
  11528. else
  11529. media += '\r\n';
  11530. }
  11531. media += 'c=IN IP4 0.0.0.0\r\n';
  11532. if (!sctp.length)
  11533. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  11534. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  11535. if (tmp.length) {
  11536. if (tmp.attr('ufrag')) {
  11537. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  11538. }
  11539. if (tmp.attr('pwd')) {
  11540. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  11541. }
  11542. tmp.find('>fingerprint').each(function () {
  11543. // FIXME: check namespace at some point
  11544. media += 'a=fingerprint:' + this.getAttribute('hash');
  11545. media += ' ' + $(this).text();
  11546. media += '\r\n';
  11547. if (this.getAttribute('setup')) {
  11548. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  11549. }
  11550. });
  11551. }
  11552. switch (content.attr('senders')) {
  11553. case 'initiator':
  11554. media += 'a=sendonly\r\n';
  11555. break;
  11556. case 'responder':
  11557. media += 'a=recvonly\r\n';
  11558. break;
  11559. case 'none':
  11560. media += 'a=inactive\r\n';
  11561. break;
  11562. case 'both':
  11563. media += 'a=sendrecv\r\n';
  11564. break;
  11565. }
  11566. media += 'a=mid:' + content.attr('name') + '\r\n';
  11567. // <description><rtcp-mux/></description>
  11568. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  11569. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  11570. if (desc.find('rtcp-mux').length) {
  11571. media += 'a=rtcp-mux\r\n';
  11572. }
  11573. if (desc.find('encryption').length) {
  11574. desc.find('encryption>crypto').each(function () {
  11575. media += 'a=crypto:' + this.getAttribute('tag');
  11576. media += ' ' + this.getAttribute('crypto-suite');
  11577. media += ' ' + this.getAttribute('key-params');
  11578. if (this.getAttribute('session-params')) {
  11579. media += ' ' + this.getAttribute('session-params');
  11580. }
  11581. media += '\r\n';
  11582. });
  11583. }
  11584. desc.find('payload-type').each(function () {
  11585. media += SDPUtil.build_rtpmap(this) + '\r\n';
  11586. if ($(this).find('>parameter').length) {
  11587. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  11588. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  11589. media += '\r\n';
  11590. }
  11591. // xep-0293
  11592. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  11593. });
  11594. // xep-0293
  11595. media += self.RtcpFbFromJingle(desc, '*');
  11596. // xep-0294
  11597. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  11598. tmp.each(function () {
  11599. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  11600. });
  11601. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  11602. media += SDPUtil.candidateFromJingle(this);
  11603. });
  11604. // XEP-0339 handle ssrc-group attributes
  11605. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11606. var semantics = this.getAttribute('semantics');
  11607. var ssrcs = $(this).find('>source').map(function() {
  11608. return this.getAttribute('ssrc');
  11609. }).get();
  11610. if (ssrcs.length != 0) {
  11611. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11612. }
  11613. });
  11614. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11615. tmp.each(function () {
  11616. var ssrc = this.getAttribute('ssrc');
  11617. $(this).find('>parameter').each(function () {
  11618. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  11619. if (this.getAttribute('value') && this.getAttribute('value').length)
  11620. media += ':' + this.getAttribute('value');
  11621. media += '\r\n';
  11622. });
  11623. });
  11624. return media;
  11625. };
  11626. module.exports = SDP;
  11627. },{"./SDPUtil":49}],48:[function(require,module,exports){
  11628. function SDPDiffer(mySDP, otherSDP) {
  11629. this.mySDP = mySDP;
  11630. this.otherSDP = otherSDP;
  11631. }
  11632. /**
  11633. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  11634. * @param otherSdp the other SDP to check ssrc with.
  11635. */
  11636. SDPDiffer.prototype.getNewMedia = function() {
  11637. // this could be useful in Array.prototype.
  11638. function arrayEquals(array) {
  11639. // if the other array is a falsy value, return
  11640. if (!array)
  11641. return false;
  11642. // compare lengths - can save a lot of time
  11643. if (this.length != array.length)
  11644. return false;
  11645. for (var i = 0, l=this.length; i < l; i++) {
  11646. // Check if we have nested arrays
  11647. if (this[i] instanceof Array && array[i] instanceof Array) {
  11648. // recurse into the nested arrays
  11649. if (!this[i].equals(array[i]))
  11650. return false;
  11651. }
  11652. else if (this[i] != array[i]) {
  11653. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  11654. return false;
  11655. }
  11656. }
  11657. return true;
  11658. }
  11659. var myMedias = this.mySDP.getMediaSsrcMap();
  11660. var othersMedias = this.otherSDP.getMediaSsrcMap();
  11661. var newMedia = {};
  11662. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  11663. var myMedia = myMedias[othersMediaIdx];
  11664. var othersMedia = othersMedias[othersMediaIdx];
  11665. if(!myMedia && othersMedia) {
  11666. // Add whole channel
  11667. newMedia[othersMediaIdx] = othersMedia;
  11668. return;
  11669. }
  11670. // Look for new ssrcs accross the channel
  11671. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  11672. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  11673. // Allocate channel if we've found ssrc that doesn't exist in our channel
  11674. if(!newMedia[othersMediaIdx]){
  11675. newMedia[othersMediaIdx] = {
  11676. mediaindex: othersMedia.mediaindex,
  11677. mid: othersMedia.mid,
  11678. ssrcs: {},
  11679. ssrcGroups: []
  11680. };
  11681. }
  11682. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  11683. }
  11684. });
  11685. // Look for new ssrc groups across the channels
  11686. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  11687. // try to match the other ssrc-group with an ssrc-group of ours
  11688. var matched = false;
  11689. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  11690. var mySsrcGroup = myMedia.ssrcGroups[i];
  11691. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  11692. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  11693. matched = true;
  11694. break;
  11695. }
  11696. }
  11697. if (!matched) {
  11698. // Allocate channel if we've found an ssrc-group that doesn't
  11699. // exist in our channel
  11700. if(!newMedia[othersMediaIdx]){
  11701. newMedia[othersMediaIdx] = {
  11702. mediaindex: othersMedia.mediaindex,
  11703. mid: othersMedia.mid,
  11704. ssrcs: {},
  11705. ssrcGroups: []
  11706. };
  11707. }
  11708. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  11709. }
  11710. });
  11711. });
  11712. return newMedia;
  11713. };
  11714. /**
  11715. * Sends SSRC update IQ.
  11716. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  11717. * @param sid session identifier that will be put into the IQ.
  11718. * @param initiator initiator identifier.
  11719. * @param toJid destination Jid
  11720. * @param isAdd indicates if this is remove or add operation.
  11721. */
  11722. SDPDiffer.prototype.toJingle = function(modify) {
  11723. var sdpMediaSsrcs = this.getNewMedia();
  11724. var self = this;
  11725. // FIXME: only announce video ssrcs since we mix audio and dont need
  11726. // the audio ssrcs therefore
  11727. var modified = false;
  11728. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  11729. modified = true;
  11730. var media = sdpMediaSsrcs[mediaindex];
  11731. modify.c('content', {name: media.mid});
  11732. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  11733. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  11734. // generate sources from lines
  11735. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  11736. var mediaSsrc = media.ssrcs[ssrcNum];
  11737. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11738. modify.attrs({ssrc: mediaSsrc.ssrc});
  11739. // iterate over ssrc lines
  11740. mediaSsrc.lines.forEach(function (line) {
  11741. var idx = line.indexOf(' ');
  11742. var kv = line.substr(idx + 1);
  11743. modify.c('parameter');
  11744. if (kv.indexOf(':') == -1) {
  11745. modify.attrs({ name: kv });
  11746. } else {
  11747. modify.attrs({ name: kv.split(':', 2)[0] });
  11748. modify.attrs({ value: kv.split(':', 2)[1] });
  11749. }
  11750. modify.up(); // end of parameter
  11751. });
  11752. modify.up(); // end of source
  11753. });
  11754. // generate source groups from lines
  11755. media.ssrcGroups.forEach(function(ssrcGroup) {
  11756. if (ssrcGroup.ssrcs.length != 0) {
  11757. modify.c('ssrc-group', {
  11758. semantics: ssrcGroup.semantics,
  11759. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  11760. });
  11761. ssrcGroup.ssrcs.forEach(function (ssrc) {
  11762. modify.c('source', { ssrc: ssrc })
  11763. .up(); // end of source
  11764. });
  11765. modify.up(); // end of ssrc-group
  11766. }
  11767. });
  11768. modify.up(); // end of description
  11769. modify.up(); // end of content
  11770. });
  11771. return modified;
  11772. };
  11773. module.exports = SDPDiffer;
  11774. },{}],49:[function(require,module,exports){
  11775. SDPUtil = {
  11776. iceparams: function (mediadesc, sessiondesc) {
  11777. var data = null;
  11778. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  11779. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  11780. data = {
  11781. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  11782. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  11783. };
  11784. }
  11785. return data;
  11786. },
  11787. parse_iceufrag: function (line) {
  11788. return line.substring(12);
  11789. },
  11790. build_iceufrag: function (frag) {
  11791. return 'a=ice-ufrag:' + frag;
  11792. },
  11793. parse_icepwd: function (line) {
  11794. return line.substring(10);
  11795. },
  11796. build_icepwd: function (pwd) {
  11797. return 'a=ice-pwd:' + pwd;
  11798. },
  11799. parse_mid: function (line) {
  11800. return line.substring(6);
  11801. },
  11802. parse_mline: function (line) {
  11803. var parts = line.substring(2).split(' '),
  11804. data = {};
  11805. data.media = parts.shift();
  11806. data.port = parts.shift();
  11807. data.proto = parts.shift();
  11808. if (parts[parts.length - 1] === '') { // trailing whitespace
  11809. parts.pop();
  11810. }
  11811. data.fmt = parts;
  11812. return data;
  11813. },
  11814. build_mline: function (mline) {
  11815. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  11816. },
  11817. parse_rtpmap: function (line) {
  11818. var parts = line.substring(9).split(' '),
  11819. data = {};
  11820. data.id = parts.shift();
  11821. parts = parts[0].split('/');
  11822. data.name = parts.shift();
  11823. data.clockrate = parts.shift();
  11824. data.channels = parts.length ? parts.shift() : '1';
  11825. return data;
  11826. },
  11827. /**
  11828. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  11829. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  11830. * @returns [SCTP port number, protocol, streams]
  11831. */
  11832. parse_sctpmap: function (line)
  11833. {
  11834. var parts = line.substring(10).split(' ');
  11835. var sctpPort = parts[0];
  11836. var protocol = parts[1];
  11837. // Stream count is optional
  11838. var streamCount = parts.length > 2 ? parts[2] : null;
  11839. return [sctpPort, protocol, streamCount];// SCTP port
  11840. },
  11841. build_rtpmap: function (el) {
  11842. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  11843. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  11844. line += '/' + el.getAttribute('channels');
  11845. }
  11846. return line;
  11847. },
  11848. parse_crypto: function (line) {
  11849. var parts = line.substring(9).split(' '),
  11850. data = {};
  11851. data.tag = parts.shift();
  11852. data['crypto-suite'] = parts.shift();
  11853. data['key-params'] = parts.shift();
  11854. if (parts.length) {
  11855. data['session-params'] = parts.join(' ');
  11856. }
  11857. return data;
  11858. },
  11859. parse_fingerprint: function (line) { // RFC 4572
  11860. var parts = line.substring(14).split(' '),
  11861. data = {};
  11862. data.hash = parts.shift();
  11863. data.fingerprint = parts.shift();
  11864. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  11865. return data;
  11866. },
  11867. parse_fmtp: function (line) {
  11868. var parts = line.split(' '),
  11869. i, key, value,
  11870. data = [];
  11871. parts.shift();
  11872. parts = parts.join(' ').split(';');
  11873. for (i = 0; i < parts.length; i++) {
  11874. key = parts[i].split('=')[0];
  11875. while (key.length && key[0] == ' ') {
  11876. key = key.substring(1);
  11877. }
  11878. value = parts[i].split('=')[1];
  11879. if (key && value) {
  11880. data.push({name: key, value: value});
  11881. } else if (key) {
  11882. // rfc 4733 (DTMF) style stuff
  11883. data.push({name: '', value: key});
  11884. }
  11885. }
  11886. return data;
  11887. },
  11888. parse_icecandidate: function (line) {
  11889. var candidate = {},
  11890. elems = line.split(' ');
  11891. candidate.foundation = elems[0].substring(12);
  11892. candidate.component = elems[1];
  11893. candidate.protocol = elems[2].toLowerCase();
  11894. candidate.priority = elems[3];
  11895. candidate.ip = elems[4];
  11896. candidate.port = elems[5];
  11897. // elems[6] => "typ"
  11898. candidate.type = elems[7];
  11899. candidate.generation = 0; // default value, may be overwritten below
  11900. for (var i = 8; i < elems.length; i += 2) {
  11901. switch (elems[i]) {
  11902. case 'raddr':
  11903. candidate['rel-addr'] = elems[i + 1];
  11904. break;
  11905. case 'rport':
  11906. candidate['rel-port'] = elems[i + 1];
  11907. break;
  11908. case 'generation':
  11909. candidate.generation = elems[i + 1];
  11910. break;
  11911. case 'tcptype':
  11912. candidate.tcptype = elems[i + 1];
  11913. break;
  11914. default: // TODO
  11915. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  11916. }
  11917. }
  11918. candidate.network = '1';
  11919. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  11920. return candidate;
  11921. },
  11922. build_icecandidate: function (cand) {
  11923. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  11924. line += ' ';
  11925. switch (cand.type) {
  11926. case 'srflx':
  11927. case 'prflx':
  11928. case 'relay':
  11929. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  11930. line += 'raddr';
  11931. line += ' ';
  11932. line += cand['rel-addr'];
  11933. line += ' ';
  11934. line += 'rport';
  11935. line += ' ';
  11936. line += cand['rel-port'];
  11937. line += ' ';
  11938. }
  11939. break;
  11940. }
  11941. if (cand.hasOwnAttribute('tcptype')) {
  11942. line += 'tcptype';
  11943. line += ' ';
  11944. line += cand.tcptype;
  11945. line += ' ';
  11946. }
  11947. line += 'generation';
  11948. line += ' ';
  11949. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  11950. return line;
  11951. },
  11952. parse_ssrc: function (desc) {
  11953. // proprietary mapping of a=ssrc lines
  11954. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  11955. // and parse according to that
  11956. var lines = desc.split('\r\n'),
  11957. data = {};
  11958. for (var i = 0; i < lines.length; i++) {
  11959. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  11960. var idx = lines[i].indexOf(' ');
  11961. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  11962. }
  11963. }
  11964. return data;
  11965. },
  11966. parse_rtcpfb: function (line) {
  11967. var parts = line.substr(10).split(' ');
  11968. var data = {};
  11969. data.pt = parts.shift();
  11970. data.type = parts.shift();
  11971. data.params = parts;
  11972. return data;
  11973. },
  11974. parse_extmap: function (line) {
  11975. var parts = line.substr(9).split(' ');
  11976. var data = {};
  11977. data.value = parts.shift();
  11978. if (data.value.indexOf('/') != -1) {
  11979. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  11980. data.value = data.value.substr(0, data.value.indexOf('/'));
  11981. } else {
  11982. data.direction = 'both';
  11983. }
  11984. data.uri = parts.shift();
  11985. data.params = parts;
  11986. return data;
  11987. },
  11988. find_line: function (haystack, needle, sessionpart) {
  11989. var lines = haystack.split('\r\n');
  11990. for (var i = 0; i < lines.length; i++) {
  11991. if (lines[i].substring(0, needle.length) == needle) {
  11992. return lines[i];
  11993. }
  11994. }
  11995. if (!sessionpart) {
  11996. return false;
  11997. }
  11998. // search session part
  11999. lines = sessionpart.split('\r\n');
  12000. for (var j = 0; j < lines.length; j++) {
  12001. if (lines[j].substring(0, needle.length) == needle) {
  12002. return lines[j];
  12003. }
  12004. }
  12005. return false;
  12006. },
  12007. find_lines: function (haystack, needle, sessionpart) {
  12008. var lines = haystack.split('\r\n'),
  12009. needles = [];
  12010. for (var i = 0; i < lines.length; i++) {
  12011. if (lines[i].substring(0, needle.length) == needle)
  12012. needles.push(lines[i]);
  12013. }
  12014. if (needles.length || !sessionpart) {
  12015. return needles;
  12016. }
  12017. // search session part
  12018. lines = sessionpart.split('\r\n');
  12019. for (var j = 0; j < lines.length; j++) {
  12020. if (lines[j].substring(0, needle.length) == needle) {
  12021. needles.push(lines[j]);
  12022. }
  12023. }
  12024. return needles;
  12025. },
  12026. candidateToJingle: function (line) {
  12027. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12028. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12029. if (line.indexOf('candidate:') === 0) {
  12030. line = 'a=' + line;
  12031. } else if (line.substring(0, 12) != 'a=candidate:') {
  12032. console.log('parseCandidate called with a line that is not a candidate line');
  12033. console.log(line);
  12034. return null;
  12035. }
  12036. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12037. line = line.substring(0, line.length - 2);
  12038. var candidate = {},
  12039. elems = line.split(' '),
  12040. i;
  12041. if (elems[6] != 'typ') {
  12042. console.log('did not find typ in the right place');
  12043. console.log(line);
  12044. return null;
  12045. }
  12046. candidate.foundation = elems[0].substring(12);
  12047. candidate.component = elems[1];
  12048. candidate.protocol = elems[2].toLowerCase();
  12049. candidate.priority = elems[3];
  12050. candidate.ip = elems[4];
  12051. candidate.port = elems[5];
  12052. // elems[6] => "typ"
  12053. candidate.type = elems[7];
  12054. candidate.generation = '0'; // default, may be overwritten below
  12055. for (i = 8; i < elems.length; i += 2) {
  12056. switch (elems[i]) {
  12057. case 'raddr':
  12058. candidate['rel-addr'] = elems[i + 1];
  12059. break;
  12060. case 'rport':
  12061. candidate['rel-port'] = elems[i + 1];
  12062. break;
  12063. case 'generation':
  12064. candidate.generation = elems[i + 1];
  12065. break;
  12066. case 'tcptype':
  12067. candidate.tcptype = elems[i + 1];
  12068. break;
  12069. default: // TODO
  12070. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12071. }
  12072. }
  12073. candidate.network = '1';
  12074. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12075. return candidate;
  12076. },
  12077. candidateFromJingle: function (cand) {
  12078. var line = 'a=candidate:';
  12079. line += cand.getAttribute('foundation');
  12080. line += ' ';
  12081. line += cand.getAttribute('component');
  12082. line += ' ';
  12083. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12084. line += ' ';
  12085. line += cand.getAttribute('priority');
  12086. line += ' ';
  12087. line += cand.getAttribute('ip');
  12088. line += ' ';
  12089. line += cand.getAttribute('port');
  12090. line += ' ';
  12091. line += 'typ';
  12092. line += ' ' + cand.getAttribute('type');
  12093. line += ' ';
  12094. switch (cand.getAttribute('type')) {
  12095. case 'srflx':
  12096. case 'prflx':
  12097. case 'relay':
  12098. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12099. line += 'raddr';
  12100. line += ' ';
  12101. line += cand.getAttribute('rel-addr');
  12102. line += ' ';
  12103. line += 'rport';
  12104. line += ' ';
  12105. line += cand.getAttribute('rel-port');
  12106. line += ' ';
  12107. }
  12108. break;
  12109. }
  12110. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12111. line += 'tcptype';
  12112. line += ' ';
  12113. line += cand.getAttribute('tcptype');
  12114. line += ' ';
  12115. }
  12116. line += 'generation';
  12117. line += ' ';
  12118. line += cand.getAttribute('generation') || '0';
  12119. return line + '\r\n';
  12120. }
  12121. };
  12122. module.exports = SDPUtil;
  12123. },{}],50:[function(require,module,exports){
  12124. function TraceablePeerConnection(ice_config, constraints) {
  12125. var self = this;
  12126. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12127. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12128. this.updateLog = [];
  12129. this.stats = {};
  12130. this.statsinterval = null;
  12131. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12132. var Interop = require('sdp-interop').Interop;
  12133. this.interop = new Interop();
  12134. var Simulcast = require('sdp-simulcast');
  12135. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  12136. // override as desired
  12137. this.trace = function (what, info) {
  12138. //console.warn('WTRACE', what, info);
  12139. self.updateLog.push({
  12140. time: new Date(),
  12141. type: what,
  12142. value: info || ""
  12143. });
  12144. };
  12145. this.onicecandidate = null;
  12146. this.peerconnection.onicecandidate = function (event) {
  12147. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12148. if (self.onicecandidate !== null) {
  12149. self.onicecandidate(event);
  12150. }
  12151. };
  12152. this.onaddstream = null;
  12153. this.peerconnection.onaddstream = function (event) {
  12154. self.trace('onaddstream', event.stream.id);
  12155. if (self.onaddstream !== null) {
  12156. self.onaddstream(event);
  12157. }
  12158. };
  12159. this.onremovestream = null;
  12160. this.peerconnection.onremovestream = function (event) {
  12161. self.trace('onremovestream', event.stream.id);
  12162. if (self.onremovestream !== null) {
  12163. self.onremovestream(event);
  12164. }
  12165. };
  12166. this.onsignalingstatechange = null;
  12167. this.peerconnection.onsignalingstatechange = function (event) {
  12168. self.trace('onsignalingstatechange', self.signalingState);
  12169. if (self.onsignalingstatechange !== null) {
  12170. self.onsignalingstatechange(event);
  12171. }
  12172. };
  12173. this.oniceconnectionstatechange = null;
  12174. this.peerconnection.oniceconnectionstatechange = function (event) {
  12175. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12176. if (self.oniceconnectionstatechange !== null) {
  12177. self.oniceconnectionstatechange(event);
  12178. }
  12179. };
  12180. this.onnegotiationneeded = null;
  12181. this.peerconnection.onnegotiationneeded = function (event) {
  12182. self.trace('onnegotiationneeded');
  12183. if (self.onnegotiationneeded !== null) {
  12184. self.onnegotiationneeded(event);
  12185. }
  12186. };
  12187. self.ondatachannel = null;
  12188. this.peerconnection.ondatachannel = function (event) {
  12189. self.trace('ondatachannel', event);
  12190. if (self.ondatachannel !== null) {
  12191. self.ondatachannel(event);
  12192. }
  12193. };
  12194. if (!navigator.mozGetUserMedia && this.maxstats) {
  12195. this.statsinterval = window.setInterval(function() {
  12196. self.peerconnection.getStats(function(stats) {
  12197. var results = stats.result();
  12198. for (var i = 0; i < results.length; ++i) {
  12199. //console.log(results[i].type, results[i].id, results[i].names())
  12200. var now = new Date();
  12201. results[i].names().forEach(function (name) {
  12202. var id = results[i].id + '-' + name;
  12203. if (!self.stats[id]) {
  12204. self.stats[id] = {
  12205. startTime: now,
  12206. endTime: now,
  12207. values: [],
  12208. times: []
  12209. };
  12210. }
  12211. self.stats[id].values.push(results[i].stat(name));
  12212. self.stats[id].times.push(now.getTime());
  12213. if (self.stats[id].values.length > self.maxstats) {
  12214. self.stats[id].values.shift();
  12215. self.stats[id].times.shift();
  12216. }
  12217. self.stats[id].endTime = now;
  12218. });
  12219. }
  12220. });
  12221. }, 1000);
  12222. }
  12223. };
  12224. dumpSDP = function(description) {
  12225. if (typeof description === 'undefined' || description == null) {
  12226. return '';
  12227. }
  12228. return 'type: ' + description.type + '\r\n' + description.sdp;
  12229. };
  12230. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12231. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12232. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12233. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12234. var desc = this.peerconnection.localDescription;
  12235. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  12236. // if we're running on FF, transform to Plan B first.
  12237. if (navigator.mozGetUserMedia) {
  12238. desc = this.interop.toPlanB(desc);
  12239. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12240. }
  12241. return desc;
  12242. });
  12243. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12244. var desc = this.peerconnection.remoteDescription;
  12245. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  12246. // if we're running on FF, transform to Plan B first.
  12247. if (navigator.mozGetUserMedia) {
  12248. desc = this.interop.toPlanB(desc);
  12249. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  12250. }
  12251. return desc;
  12252. });
  12253. }
  12254. TraceablePeerConnection.prototype.addStream = function (stream) {
  12255. this.trace('addStream', stream.id);
  12256. try
  12257. {
  12258. this.peerconnection.addStream(stream);
  12259. }
  12260. catch (e)
  12261. {
  12262. console.error(e);
  12263. return;
  12264. }
  12265. };
  12266. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12267. this.trace('removeStream', stream.id);
  12268. if(stopStreams) {
  12269. stream.getAudioTracks().forEach(function (track) {
  12270. track.stop();
  12271. });
  12272. stream.getVideoTracks().forEach(function (track) {
  12273. track.stop();
  12274. });
  12275. }
  12276. try {
  12277. // FF doesn't support this yet.
  12278. this.peerconnection.removeStream(stream);
  12279. } catch (e) {
  12280. console.error(e);
  12281. }
  12282. };
  12283. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12284. this.trace('createDataChannel', label, opts);
  12285. return this.peerconnection.createDataChannel(label, opts);
  12286. };
  12287. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12288. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  12289. // if we're running on FF, transform to Plan A first.
  12290. if (navigator.mozGetUserMedia) {
  12291. description = this.interop.toUnifiedPlan(description);
  12292. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  12293. }
  12294. var self = this;
  12295. this.peerconnection.setLocalDescription(description,
  12296. function () {
  12297. self.trace('setLocalDescriptionOnSuccess');
  12298. successCallback();
  12299. },
  12300. function (err) {
  12301. self.trace('setLocalDescriptionOnFailure', err);
  12302. failureCallback(err);
  12303. }
  12304. );
  12305. /*
  12306. if (this.statsinterval === null && this.maxstats > 0) {
  12307. // start gathering stats
  12308. }
  12309. */
  12310. };
  12311. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12312. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  12313. // TODO the focus should squeze or explode the remote simulcast
  12314. description = this.simulcast.mungeRemoteDescription(description);
  12315. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  12316. // if we're running on FF, transform to Plan A first.
  12317. if (navigator.mozGetUserMedia) {
  12318. description = this.interop.toUnifiedPlan(description);
  12319. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  12320. }
  12321. var self = this;
  12322. this.peerconnection.setRemoteDescription(description,
  12323. function () {
  12324. self.trace('setRemoteDescriptionOnSuccess');
  12325. successCallback();
  12326. },
  12327. function (err) {
  12328. self.trace('setRemoteDescriptionOnFailure', err);
  12329. failureCallback(err);
  12330. }
  12331. );
  12332. /*
  12333. if (this.statsinterval === null && this.maxstats > 0) {
  12334. // start gathering stats
  12335. }
  12336. */
  12337. };
  12338. TraceablePeerConnection.prototype.close = function () {
  12339. this.trace('stop');
  12340. if (this.statsinterval !== null) {
  12341. window.clearInterval(this.statsinterval);
  12342. this.statsinterval = null;
  12343. }
  12344. this.peerconnection.close();
  12345. };
  12346. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12347. var self = this;
  12348. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12349. this.peerconnection.createOffer(
  12350. function (offer) {
  12351. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  12352. // if we're running on FF, transform to Plan B first.
  12353. // NOTE this is not tested because in meet the focus generates the
  12354. // offer.
  12355. if (navigator.mozGetUserMedia) {
  12356. offer = self.interop.toPlanB(offer);
  12357. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  12358. }
  12359. if (config.enableSimulcast && self.simulcast.isSupported()) {
  12360. offer = self.simulcast.mungeLocalDescription(offer);
  12361. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  12362. }
  12363. successCallback(offer);
  12364. },
  12365. function(err) {
  12366. self.trace('createOfferOnFailure', err);
  12367. failureCallback(err);
  12368. },
  12369. constraints
  12370. );
  12371. };
  12372. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12373. var self = this;
  12374. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12375. this.peerconnection.createAnswer(
  12376. function (answer) {
  12377. self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
  12378. // if we're running on FF, transform to Plan A first.
  12379. if (navigator.mozGetUserMedia) {
  12380. answer = self.interop.toPlanB(answer);
  12381. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  12382. }
  12383. if (config.enableSimulcast && self.simulcast.isSupported()) {
  12384. answer = self.simulcast.mungeLocalDescription(answer);
  12385. self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
  12386. }
  12387. successCallback(answer);
  12388. },
  12389. function(err) {
  12390. self.trace('createAnswerOnFailure', err);
  12391. failureCallback(err);
  12392. },
  12393. constraints
  12394. );
  12395. };
  12396. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12397. var self = this;
  12398. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12399. this.peerconnection.addIceCandidate(candidate);
  12400. /* maybe later
  12401. this.peerconnection.addIceCandidate(candidate,
  12402. function () {
  12403. self.trace('addIceCandidateOnSuccess');
  12404. successCallback();
  12405. },
  12406. function (err) {
  12407. self.trace('addIceCandidateOnFailure', err);
  12408. failureCallback(err);
  12409. }
  12410. );
  12411. */
  12412. };
  12413. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12414. if (navigator.mozGetUserMedia) {
  12415. // ignore for now...
  12416. if(!errback)
  12417. errback = function () {
  12418. }
  12419. this.peerconnection.getStats(null,callback,errback);
  12420. } else {
  12421. this.peerconnection.getStats(callback);
  12422. }
  12423. };
  12424. module.exports = TraceablePeerConnection;
  12425. },{"sdp-interop":84,"sdp-simulcast":91}],51:[function(require,module,exports){
  12426. /* global $, $iq, APP, config, connection, UI, messageHandler,
  12427. roomName, sessionTerminated, Strophe, Util */
  12428. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12429. var Settings = require("../settings/Settings");
  12430. var AuthenticationEvents
  12431. = require("../../service/authentication/AuthenticationEvents");
  12432. /**
  12433. * Contains logic responsible for enabling/disabling functionality available
  12434. * only to moderator users.
  12435. */
  12436. var connection = null;
  12437. var focusUserJid;
  12438. function createExpBackoffTimer(step) {
  12439. var count = 1;
  12440. return function (reset) {
  12441. // Reset call
  12442. if (reset) {
  12443. count = 1;
  12444. return;
  12445. }
  12446. // Calculate next timeout
  12447. var timeout = Math.pow(2, count - 1);
  12448. count += 1;
  12449. return timeout * step;
  12450. };
  12451. }
  12452. var getNextTimeout = createExpBackoffTimer(1000);
  12453. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12454. // External authentication stuff
  12455. var externalAuthEnabled = false;
  12456. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12457. // it will be enabled automatically if focus detects the component through
  12458. // service discovery.
  12459. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12460. var eventEmitter = null;
  12461. var Moderator = {
  12462. isModerator: function () {
  12463. return connection && connection.emuc.isModerator();
  12464. },
  12465. isPeerModerator: function (peerJid) {
  12466. return connection &&
  12467. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12468. },
  12469. isExternalAuthEnabled: function () {
  12470. return externalAuthEnabled;
  12471. },
  12472. isSipGatewayEnabled: function () {
  12473. return sipGatewayEnabled;
  12474. },
  12475. setConnection: function (con) {
  12476. connection = con;
  12477. },
  12478. init: function (xmpp, emitter) {
  12479. this.xmppService = xmpp;
  12480. eventEmitter = emitter;
  12481. // Message listener that talks to POPUP window
  12482. function listener(event) {
  12483. if (event.data && event.data.sessionId) {
  12484. if (event.origin !== window.location.origin) {
  12485. console.warn(
  12486. "Ignoring sessionId from different origin: " + event.origin);
  12487. return;
  12488. }
  12489. localStorage.setItem('sessionId', event.data.sessionId);
  12490. // After popup is closed we will authenticate
  12491. }
  12492. }
  12493. // Register
  12494. if (window.addEventListener) {
  12495. window.addEventListener("message", listener, false);
  12496. } else {
  12497. window.attachEvent("onmessage", listener);
  12498. }
  12499. },
  12500. onMucMemberLeft: function (jid) {
  12501. console.info("Someone left is it focus ? " + jid);
  12502. var resource = Strophe.getResourceFromJid(jid);
  12503. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12504. console.info(
  12505. "Focus has left the room - leaving conference");
  12506. //hangUp();
  12507. // We'd rather reload to have everything re-initialized
  12508. // FIXME: show some message before reload
  12509. location.reload();
  12510. }
  12511. },
  12512. setFocusUserJid: function (focusJid) {
  12513. if (!focusUserJid) {
  12514. focusUserJid = focusJid;
  12515. console.info("Focus jid set to: " + focusUserJid);
  12516. }
  12517. },
  12518. getFocusUserJid: function () {
  12519. return focusUserJid;
  12520. },
  12521. getFocusComponent: function () {
  12522. // Get focus component address
  12523. var focusComponent = config.hosts.focus;
  12524. // If not specified use default: 'focus.domain'
  12525. if (!focusComponent) {
  12526. focusComponent = 'focus.' + config.hosts.domain;
  12527. }
  12528. return focusComponent;
  12529. },
  12530. createConferenceIq: function (roomName) {
  12531. // Generate create conference IQ
  12532. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12533. // Session Id used for authentication
  12534. var sessionId = localStorage.getItem('sessionId');
  12535. var machineUID = Settings.getSettings().uid;
  12536. console.info(
  12537. "Session ID: " + sessionId + " machine UID: " + machineUID);
  12538. elem.c('conference', {
  12539. xmlns: 'http://jitsi.org/protocol/focus',
  12540. room: roomName,
  12541. 'machine-uid': machineUID
  12542. });
  12543. if (sessionId) {
  12544. elem.attrs({ 'session-id': sessionId});
  12545. }
  12546. if (config.hosts.bridge !== undefined) {
  12547. elem.c(
  12548. 'property',
  12549. { name: 'bridge', value: config.hosts.bridge})
  12550. .up();
  12551. }
  12552. // Tell the focus we have Jigasi configured
  12553. if (config.hosts.call_control !== undefined) {
  12554. elem.c(
  12555. 'property',
  12556. { name: 'call_control', value: config.hosts.call_control})
  12557. .up();
  12558. }
  12559. if (config.channelLastN !== undefined) {
  12560. elem.c(
  12561. 'property',
  12562. { name: 'channelLastN', value: config.channelLastN})
  12563. .up();
  12564. }
  12565. if (config.adaptiveLastN !== undefined) {
  12566. elem.c(
  12567. 'property',
  12568. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12569. .up();
  12570. }
  12571. if (config.adaptiveSimulcast !== undefined) {
  12572. elem.c(
  12573. 'property',
  12574. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12575. .up();
  12576. }
  12577. if (config.openSctp !== undefined) {
  12578. elem.c(
  12579. 'property',
  12580. { name: 'openSctp', value: config.openSctp})
  12581. .up();
  12582. }
  12583. if(config.startAudioMuted !== undefined)
  12584. {
  12585. elem.c(
  12586. 'property',
  12587. { name: 'startAudioMuted', value: config.startAudioMuted})
  12588. .up();
  12589. }
  12590. if(config.startVideoMuted !== undefined)
  12591. {
  12592. elem.c(
  12593. 'property',
  12594. { name: 'startVideoMuted', value: config.startVideoMuted})
  12595. .up();
  12596. }
  12597. elem.c(
  12598. 'property',
  12599. { name: 'simulcastMode', value: 'rewriting'})
  12600. .up();
  12601. elem.up();
  12602. return elem;
  12603. },
  12604. parseSessionId: function (resultIq) {
  12605. var sessionId = $(resultIq).find('conference').attr('session-id');
  12606. if (sessionId) {
  12607. console.info('Received sessionId: ' + sessionId);
  12608. localStorage.setItem('sessionId', sessionId);
  12609. }
  12610. },
  12611. parseConfigOptions: function (resultIq) {
  12612. Moderator.setFocusUserJid(
  12613. $(resultIq).find('conference').attr('focusjid'));
  12614. var authenticationEnabled
  12615. = $(resultIq).find(
  12616. '>conference>property' +
  12617. '[name=\'authentication\'][value=\'true\']').length > 0;
  12618. console.info("Authentication enabled: " + authenticationEnabled);
  12619. externalAuthEnabled
  12620. = $(resultIq).find(
  12621. '>conference>property' +
  12622. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  12623. console.info('External authentication enabled: ' + externalAuthEnabled);
  12624. if (!externalAuthEnabled) {
  12625. // We expect to receive sessionId in 'internal' authentication mode
  12626. Moderator.parseSessionId(resultIq);
  12627. }
  12628. var authIdentity = $(resultIq).find('>conference').attr('identity');
  12629. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  12630. authenticationEnabled, authIdentity);
  12631. // Check if focus has auto-detected Jigasi component(this will be also
  12632. // included if we have passed our host from the config)
  12633. if ($(resultIq).find(
  12634. '>conference>property' +
  12635. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  12636. sipGatewayEnabled = true;
  12637. }
  12638. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  12639. },
  12640. // FIXME: we need to show the fact that we're waiting for the focus
  12641. // to the user(or that focus is not available)
  12642. allocateConferenceFocus: function (roomName, callback) {
  12643. // Try to use focus user JID from the config
  12644. Moderator.setFocusUserJid(config.focusUserJid);
  12645. // Send create conference IQ
  12646. var iq = Moderator.createConferenceIq(roomName);
  12647. var self = this;
  12648. connection.sendIQ(
  12649. iq,
  12650. function (result) {
  12651. // Setup config options
  12652. Moderator.parseConfigOptions(result);
  12653. if ('true' === $(result).find('conference').attr('ready')) {
  12654. // Reset both timers
  12655. getNextTimeout(true);
  12656. getNextErrorTimeout(true);
  12657. // Exec callback
  12658. callback();
  12659. } else {
  12660. var waitMs = getNextTimeout();
  12661. console.info("Waiting for the focus... " + waitMs);
  12662. // Reset error timeout
  12663. getNextErrorTimeout(true);
  12664. window.setTimeout(
  12665. function () {
  12666. Moderator.allocateConferenceFocus(
  12667. roomName, callback);
  12668. }, waitMs);
  12669. }
  12670. },
  12671. function (error) {
  12672. // Invalid session ? remove and try again
  12673. // without session ID to get a new one
  12674. var invalidSession
  12675. = $(error).find('>error>session-invalid').length;
  12676. if (invalidSession) {
  12677. console.info("Session expired! - removing");
  12678. localStorage.removeItem("sessionId");
  12679. }
  12680. if ($(error).find('>error>graceful-shutdown').length) {
  12681. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  12682. return;
  12683. }
  12684. // Check for error returned by the reservation system
  12685. var reservationErr = $(error).find('>error>reservation-error');
  12686. if (reservationErr.length) {
  12687. // Trigger error event
  12688. var errorCode = reservationErr.attr('error-code');
  12689. var errorMsg;
  12690. if ($(error).find('>error>text')) {
  12691. errorMsg = $(error).find('>error>text').text();
  12692. }
  12693. eventEmitter.emit(
  12694. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  12695. return;
  12696. }
  12697. // Not authorized to create new room
  12698. if ($(error).find('>error>not-authorized').length) {
  12699. console.warn("Unauthorized to start the conference", error);
  12700. var toDomain
  12701. = Strophe.getDomainFromJid(error.getAttribute('to'));
  12702. if (toDomain !== config.hosts.anonymousdomain) {
  12703. // FIXME: "is external" should come either from
  12704. // the focus or config.js
  12705. externalAuthEnabled = true;
  12706. }
  12707. eventEmitter.emit(
  12708. XMPPEvents.AUTHENTICATION_REQUIRED,
  12709. function () {
  12710. Moderator.allocateConferenceFocus(
  12711. roomName, callback);
  12712. });
  12713. return;
  12714. }
  12715. var waitMs = getNextErrorTimeout();
  12716. console.error("Focus error, retry after " + waitMs, error);
  12717. // Show message
  12718. var focusComponent = Moderator.getFocusComponent();
  12719. var retrySec = waitMs / 1000;
  12720. // FIXME: message is duplicated ?
  12721. // Do not show in case of session invalid
  12722. // which means just a retry
  12723. if (!invalidSession) {
  12724. APP.UI.messageHandler.notify(
  12725. null, "notify.focus",
  12726. 'disconnected', "notify.focusFail",
  12727. {component: focusComponent, ms: retrySec});
  12728. }
  12729. // Reset response timeout
  12730. getNextTimeout(true);
  12731. window.setTimeout(
  12732. function () {
  12733. Moderator.allocateConferenceFocus(roomName, callback);
  12734. }, waitMs);
  12735. }
  12736. );
  12737. },
  12738. getLoginUrl: function (roomName, urlCallback) {
  12739. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  12740. iq.c('login-url', {
  12741. xmlns: 'http://jitsi.org/protocol/focus',
  12742. room: roomName,
  12743. 'machine-uid': Settings.getSettings().uid
  12744. });
  12745. connection.sendIQ(
  12746. iq,
  12747. function (result) {
  12748. var url = $(result).find('login-url').attr('url');
  12749. url = url = decodeURIComponent(url);
  12750. if (url) {
  12751. console.info("Got auth url: " + url);
  12752. urlCallback(url);
  12753. } else {
  12754. console.error(
  12755. "Failed to get auth url from the focus", result);
  12756. }
  12757. },
  12758. function (error) {
  12759. console.error("Get auth url error", error);
  12760. }
  12761. );
  12762. },
  12763. getPopupLoginUrl: function (roomName, urlCallback) {
  12764. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  12765. iq.c('login-url', {
  12766. xmlns: 'http://jitsi.org/protocol/focus',
  12767. room: roomName,
  12768. 'machine-uid': Settings.getSettings().uid,
  12769. popup: true
  12770. });
  12771. connection.sendIQ(
  12772. iq,
  12773. function (result) {
  12774. var url = $(result).find('login-url').attr('url');
  12775. url = url = decodeURIComponent(url);
  12776. if (url) {
  12777. console.info("Got POPUP auth url: " + url);
  12778. urlCallback(url);
  12779. } else {
  12780. console.error(
  12781. "Failed to get POPUP auth url from the focus", result);
  12782. }
  12783. },
  12784. function (error) {
  12785. console.error('Get POPUP auth url error', error);
  12786. }
  12787. );
  12788. },
  12789. logout: function (callback) {
  12790. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12791. var sessionId = localStorage.getItem('sessionId');
  12792. if (!sessionId) {
  12793. callback();
  12794. return;
  12795. }
  12796. iq.c('logout', {
  12797. xmlns: 'http://jitsi.org/protocol/focus',
  12798. 'session-id': sessionId
  12799. });
  12800. connection.sendIQ(
  12801. iq,
  12802. function (result) {
  12803. var logoutUrl = $(result).find('logout').attr('logout-url');
  12804. if (logoutUrl) {
  12805. logoutUrl = decodeURIComponent(logoutUrl);
  12806. }
  12807. console.info("Log out OK, url: " + logoutUrl, result);
  12808. localStorage.removeItem('sessionId');
  12809. callback(logoutUrl);
  12810. },
  12811. function (error) {
  12812. console.error("Logout error", error);
  12813. }
  12814. );
  12815. }
  12816. };
  12817. module.exports = Moderator;
  12818. },{"../../service/authentication/AuthenticationEvents":107,"../../service/xmpp/XMPPEvents":112,"../settings/Settings":41}],52:[function(require,module,exports){
  12819. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  12820. Toolbar, Util */
  12821. var Moderator = require("./moderator");
  12822. var recordingToken = null;
  12823. var recordingEnabled;
  12824. /**
  12825. * Whether to use a jirecon component for recording, or use the videobridge
  12826. * through COLIBRI.
  12827. */
  12828. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  12829. /**
  12830. * The ID of the jirecon recording session. Jirecon generates it when we
  12831. * initially start recording, and it needs to be used in subsequent requests
  12832. * to jirecon.
  12833. */
  12834. var jireconRid = null;
  12835. function setRecordingToken(token) {
  12836. recordingToken = token;
  12837. }
  12838. function setRecording(state, token, callback, connection) {
  12839. if (useJirecon){
  12840. setRecordingJirecon(state, token, callback, connection);
  12841. } else {
  12842. setRecordingColibri(state, token, callback, connection);
  12843. }
  12844. }
  12845. function setRecordingJirecon(state, token, callback, connection) {
  12846. if (state == recordingEnabled){
  12847. return;
  12848. }
  12849. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  12850. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  12851. action: state ? 'start' : 'stop',
  12852. mucjid: connection.emuc.roomjid});
  12853. if (!state){
  12854. iq.attrs({rid: jireconRid});
  12855. }
  12856. console.log('Start recording');
  12857. connection.sendIQ(
  12858. iq,
  12859. function (result) {
  12860. // TODO wait for an IQ with the real status, since this is
  12861. // provisional?
  12862. jireconRid = $(result).find('recording').attr('rid');
  12863. console.log('Recording ' + (state ? 'started' : 'stopped') +
  12864. '(jirecon)' + result);
  12865. recordingEnabled = state;
  12866. if (!state){
  12867. jireconRid = null;
  12868. }
  12869. callback(state);
  12870. },
  12871. function (error) {
  12872. console.log('Failed to start recording, error: ', error);
  12873. callback(recordingEnabled);
  12874. });
  12875. }
  12876. // Sends a COLIBRI message which enables or disables (according to 'state')
  12877. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  12878. // with the new recording state, according to the IQ.
  12879. function setRecordingColibri(state, token, callback, connection) {
  12880. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  12881. elem.c('conference', {
  12882. xmlns: 'http://jitsi.org/protocol/colibri'
  12883. });
  12884. elem.c('recording', {state: state, token: token});
  12885. connection.sendIQ(elem,
  12886. function (result) {
  12887. console.log('Set recording "', state, '". Result:', result);
  12888. var recordingElem = $(result).find('>conference>recording');
  12889. var newState = ('true' === recordingElem.attr('state'));
  12890. recordingEnabled = newState;
  12891. callback(newState);
  12892. },
  12893. function (error) {
  12894. console.warn(error);
  12895. callback(recordingEnabled);
  12896. }
  12897. );
  12898. }
  12899. var Recording = {
  12900. toggleRecording: function (tokenEmptyCallback,
  12901. startingCallback, startedCallback, connection) {
  12902. if (!Moderator.isModerator()) {
  12903. console.log(
  12904. 'non-focus, or conference not yet organized:' +
  12905. ' not enabling recording');
  12906. return;
  12907. }
  12908. var self = this;
  12909. // Jirecon does not (currently) support a token.
  12910. if (!recordingToken && !useJirecon) {
  12911. tokenEmptyCallback(function (value) {
  12912. setRecordingToken(value);
  12913. self.toggleRecording(tokenEmptyCallback,
  12914. startingCallback, startedCallback, connection);
  12915. });
  12916. return;
  12917. }
  12918. var oldState = recordingEnabled;
  12919. startingCallback(!oldState);
  12920. setRecording(!oldState,
  12921. recordingToken,
  12922. function (state) {
  12923. console.log("New recording state: ", state);
  12924. if (state === oldState) {
  12925. // FIXME: new focus:
  12926. // this will not work when moderator changes
  12927. // during active session. Then it will assume that
  12928. // recording status has changed to true, but it might have
  12929. // been already true(and we only received actual status from
  12930. // the focus).
  12931. //
  12932. // SO we start with status null, so that it is initialized
  12933. // here and will fail only after second click, so if invalid
  12934. // token was used we have to press the button twice before
  12935. // current status will be fetched and token will be reset.
  12936. //
  12937. // Reliable way would be to return authentication error.
  12938. // Or status update when moderator connects.
  12939. // Or we have to stop recording session when current
  12940. // moderator leaves the room.
  12941. // Failed to change, reset the token because it might
  12942. // have been wrong
  12943. setRecordingToken(null);
  12944. }
  12945. startedCallback(state);
  12946. },
  12947. connection
  12948. );
  12949. }
  12950. }
  12951. module.exports = Recording;
  12952. },{"./moderator":51}],53:[function(require,module,exports){
  12953. /* jshint -W117 */
  12954. /* a simple MUC connection plugin
  12955. * can only handle a single MUC room
  12956. */
  12957. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12958. var Moderator = require("./moderator");
  12959. var JingleSession = require("./JingleSession");
  12960. var bridgeIsDown = false;
  12961. module.exports = function(XMPP, eventEmitter) {
  12962. Strophe.addConnectionPlugin('emuc', {
  12963. connection: null,
  12964. roomjid: null,
  12965. myroomjid: null,
  12966. members: {},
  12967. list_members: [], // so we can elect a new focus
  12968. presMap: {},
  12969. preziMap: {},
  12970. joined: false,
  12971. isOwner: false,
  12972. role: null,
  12973. focusMucJid: null,
  12974. ssrc2jid: {},
  12975. init: function (conn) {
  12976. this.connection = conn;
  12977. },
  12978. initPresenceMap: function (myroomjid) {
  12979. this.presMap['to'] = myroomjid;
  12980. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  12981. if(APP.RTC.localAudio.isMuted())
  12982. {
  12983. this.addAudioInfoToPresence(true);
  12984. }
  12985. if(APP.RTC.localVideo.isMuted())
  12986. {
  12987. this.addVideoInfoToPresence(true);
  12988. }
  12989. },
  12990. doJoin: function (jid, password) {
  12991. this.myroomjid = jid;
  12992. console.info("Joined MUC as " + this.myroomjid);
  12993. this.initPresenceMap(this.myroomjid);
  12994. if (!this.roomjid) {
  12995. this.roomjid = Strophe.getBareJidFromJid(jid);
  12996. // add handlers (just once)
  12997. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  12998. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  12999. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13000. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13001. }
  13002. if (password !== undefined) {
  13003. this.presMap['password'] = password;
  13004. }
  13005. this.sendPresence();
  13006. },
  13007. doLeave: function () {
  13008. console.log("do leave", this.myroomjid);
  13009. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13010. this.presMap.length = 0;
  13011. this.connection.send(pres);
  13012. },
  13013. createNonAnonymousRoom: function () {
  13014. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13015. var getForm = $iq({type: 'get', to: this.roomjid})
  13016. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13017. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13018. var self = this;
  13019. this.connection.sendIQ(getForm, function (form) {
  13020. if (!$(form).find(
  13021. '>query>x[xmlns="jabber:x:data"]' +
  13022. '>field[var="muc#roomconfig_whois"]').length) {
  13023. console.error('non-anonymous rooms not supported');
  13024. return;
  13025. }
  13026. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13027. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13028. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13029. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13030. .c('value')
  13031. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13032. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13033. .c('value').t('anyone').up().up();
  13034. self.connection.sendIQ(formSubmit);
  13035. }, function (error) {
  13036. console.error("Error getting room configuration form");
  13037. });
  13038. },
  13039. onPresence: function (pres) {
  13040. var from = pres.getAttribute('from');
  13041. // What is this for? A workaround for something?
  13042. if (pres.getAttribute('type')) {
  13043. return true;
  13044. }
  13045. // Parse etherpad tag.
  13046. var etherpad = $(pres).find('>etherpad');
  13047. if (etherpad.length) {
  13048. if (config.etherpad_base && !Moderator.isModerator()) {
  13049. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13050. }
  13051. }
  13052. // Parse prezi tag.
  13053. var presentation = $(pres).find('>prezi');
  13054. if (presentation.length) {
  13055. var url = presentation.attr('url');
  13056. var current = presentation.find('>current').text();
  13057. console.log('presentation info received from', from, url);
  13058. if (this.preziMap[from] == null) {
  13059. this.preziMap[from] = url;
  13060. $(document).trigger('presentationadded.muc', [from, url, current]);
  13061. }
  13062. else {
  13063. $(document).trigger('gotoslide.muc', [from, url, current]);
  13064. }
  13065. }
  13066. else if (this.preziMap[from] != null) {
  13067. var url = this.preziMap[from];
  13068. delete this.preziMap[from];
  13069. $(document).trigger('presentationremoved.muc', [from, url]);
  13070. }
  13071. // Parse audio info tag.
  13072. var audioMuted = $(pres).find('>audiomuted');
  13073. if (audioMuted.length) {
  13074. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13075. }
  13076. // Parse video info tag.
  13077. var videoMuted = $(pres).find('>videomuted');
  13078. if (videoMuted.length) {
  13079. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13080. }
  13081. var startMuted = $(pres).find('>startmuted');
  13082. if (startMuted.length)
  13083. {
  13084. eventEmitter.emit(XMPPEvents.START_MUTED,
  13085. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  13086. }
  13087. var devices = $(pres).find('>devices');
  13088. if(devices.length)
  13089. {
  13090. var audio = devices.find('>audio');
  13091. var video = devices.find('>video');
  13092. var devicesValues = {audio: false, video: false};
  13093. if(audio.length && audio.text() === "true")
  13094. {
  13095. devicesValues.audio = true;
  13096. }
  13097. if(video.length && video.text() === "true")
  13098. {
  13099. devicesValues.video = true;
  13100. }
  13101. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  13102. Strophe.getResourceFromJid(from), devicesValues);
  13103. }
  13104. var stats = $(pres).find('>stats');
  13105. if (stats.length) {
  13106. var statsObj = {};
  13107. Strophe.forEachChild(stats[0], "stat", function (el) {
  13108. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13109. });
  13110. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13111. }
  13112. // Parse status.
  13113. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13114. this.isOwner = true;
  13115. this.createNonAnonymousRoom();
  13116. }
  13117. // Parse roles.
  13118. var member = {};
  13119. member.show = $(pres).find('>show').text();
  13120. member.status = $(pres).find('>status').text();
  13121. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13122. member.affiliation = tmp.attr('affiliation');
  13123. member.role = tmp.attr('role');
  13124. // Focus recognition
  13125. member.jid = tmp.attr('jid');
  13126. member.isFocus = false;
  13127. if (member.jid
  13128. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13129. member.isFocus = true;
  13130. }
  13131. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13132. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13133. if (from == this.myroomjid) {
  13134. if (member.affiliation == 'owner') this.isOwner = true;
  13135. if (this.role !== member.role) {
  13136. this.role = member.role;
  13137. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  13138. from, member, pres, Moderator.isModerator());
  13139. }
  13140. if (!this.joined) {
  13141. this.joined = true;
  13142. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13143. this.list_members.push(from);
  13144. }
  13145. } else if (this.members[from] === undefined) {
  13146. // new participant
  13147. this.members[from] = member;
  13148. this.list_members.push(from);
  13149. console.log('entered', from, member);
  13150. if (member.isFocus) {
  13151. this.focusMucJid = from;
  13152. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13153. }
  13154. else {
  13155. var id = $(pres).find('>userId').text();
  13156. var email = $(pres).find('>email');
  13157. if (email.length > 0) {
  13158. id = email.text();
  13159. }
  13160. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  13161. }
  13162. } else {
  13163. // Presence update for existing participant
  13164. // Watch role change:
  13165. if (this.members[from].role != member.role) {
  13166. this.members[from].role = member.role;
  13167. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13168. member.role, member.displayName);
  13169. }
  13170. }
  13171. // Always trigger presence to update bindings
  13172. this.parsePresence(from, member, pres);
  13173. // Trigger status message update
  13174. if (member.status) {
  13175. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13176. }
  13177. return true;
  13178. },
  13179. onPresenceUnavailable: function (pres) {
  13180. var from = pres.getAttribute('from');
  13181. // room destroyed ?
  13182. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13183. '>destroy').length) {
  13184. var reason;
  13185. var reasonSelect = $(pres).find(
  13186. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13187. '>destroy>reason');
  13188. if (reasonSelect.length) {
  13189. reason = reasonSelect.text();
  13190. }
  13191. XMPP.disposeConference(false);
  13192. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13193. return true;
  13194. }
  13195. var self = this;
  13196. // Remove old ssrcs coming from the jid
  13197. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13198. if (self.ssrc2jid[ssrc] == from) {
  13199. delete self.ssrc2jid[ssrc];
  13200. }
  13201. });
  13202. // Status code 110 indicates that this notification is "self-presence".
  13203. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13204. delete this.members[from];
  13205. this.list_members.splice(this.list_members.indexOf(from), 1);
  13206. this.onParticipantLeft(from);
  13207. }
  13208. // If the status code is 110 this means we're leaving and we would like
  13209. // to remove everyone else from our view, so we trigger the event.
  13210. else if (this.list_members.length > 1) {
  13211. for (var i = 0; i < this.list_members.length; i++) {
  13212. var member = this.list_members[i];
  13213. delete this.members[i];
  13214. this.list_members.splice(i, 1);
  13215. this.onParticipantLeft(member);
  13216. }
  13217. }
  13218. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13219. $(document).trigger('kicked.muc', [from]);
  13220. if (this.myroomjid === from) {
  13221. XMPP.disposeConference(false);
  13222. eventEmitter.emit(XMPPEvents.KICKED);
  13223. }
  13224. }
  13225. return true;
  13226. },
  13227. onPresenceError: function (pres) {
  13228. var from = pres.getAttribute('from');
  13229. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13230. console.log('on password required', from);
  13231. var self = this;
  13232. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13233. self.doJoin(from, value);
  13234. });
  13235. } else if ($(pres).find(
  13236. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13237. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13238. if (toDomain === config.hosts.anonymousdomain) {
  13239. // enter the room by replying with 'not-authorized'. This would
  13240. // result in reconnection from authorized domain.
  13241. // We're either missing Jicofo/Prosody config for anonymous
  13242. // domains or something is wrong.
  13243. // XMPP.promptLogin();
  13244. APP.UI.messageHandler.openReportDialog(null,
  13245. "dialog.joinError", pres);
  13246. } else {
  13247. console.warn('onPresError ', pres);
  13248. APP.UI.messageHandler.openReportDialog(null,
  13249. "dialog.connectError",
  13250. pres);
  13251. }
  13252. } else {
  13253. console.warn('onPresError ', pres);
  13254. APP.UI.messageHandler.openReportDialog(null,
  13255. "dialog.connectError",
  13256. pres);
  13257. }
  13258. return true;
  13259. },
  13260. sendMessage: function (body, nickname) {
  13261. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13262. msg.c('body', body).up();
  13263. if (nickname) {
  13264. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13265. }
  13266. this.connection.send(msg);
  13267. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13268. },
  13269. setSubject: function (subject) {
  13270. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13271. msg.c('subject', subject);
  13272. this.connection.send(msg);
  13273. console.log("topic changed to " + subject);
  13274. },
  13275. onMessage: function (msg) {
  13276. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13277. var from = msg.getAttribute('from');
  13278. var nick =
  13279. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13280. .text() ||
  13281. Strophe.getResourceFromJid(from);
  13282. var txt = $(msg).find('>body').text();
  13283. var type = msg.getAttribute("type");
  13284. if (type == "error") {
  13285. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13286. $(msg).find('>text').text(), txt);
  13287. return true;
  13288. }
  13289. var subject = $(msg).find('>subject');
  13290. if (subject.length) {
  13291. var subjectText = subject.text();
  13292. if (subjectText || subjectText == "") {
  13293. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13294. console.log("Subject is changed to " + subjectText);
  13295. }
  13296. }
  13297. if (txt) {
  13298. console.log('chat', nick, txt);
  13299. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13300. from, nick, txt, this.myroomjid);
  13301. }
  13302. return true;
  13303. },
  13304. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13305. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13306. var ob = this;
  13307. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13308. function (res) {
  13309. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13310. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13311. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13312. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13313. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13314. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13315. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13316. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13317. ob.connection.sendIQ(formsubmit,
  13318. onSuccess,
  13319. onError);
  13320. } else {
  13321. onNotSupported();
  13322. }
  13323. }, onError);
  13324. },
  13325. kick: function (jid) {
  13326. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13327. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13328. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13329. .c('reason').t('You have been kicked.').up().up().up();
  13330. this.connection.sendIQ(
  13331. kickIQ,
  13332. function (result) {
  13333. console.log('Kick participant with jid: ', jid, result);
  13334. },
  13335. function (error) {
  13336. console.log('Kick participant error: ', error);
  13337. });
  13338. },
  13339. sendPresence: function () {
  13340. if (!this.presMap['to']) {
  13341. // Too early to send presence - not initialized
  13342. return;
  13343. }
  13344. var pres = $pres({to: this.presMap['to'] });
  13345. pres.c('x', {xmlns: this.presMap['xns']});
  13346. if (this.presMap['password']) {
  13347. pres.c('password').t(this.presMap['password']).up();
  13348. }
  13349. pres.up();
  13350. // Send XEP-0115 'c' stanza that contains our capabilities info
  13351. if (this.connection.caps) {
  13352. this.connection.caps.node = config.clientNode;
  13353. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13354. }
  13355. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13356. .t(navigator.userAgent).up();
  13357. if (this.presMap['bridgeIsDown']) {
  13358. pres.c('bridgeIsDown').up();
  13359. }
  13360. if (this.presMap['email']) {
  13361. pres.c('email').t(this.presMap['email']).up();
  13362. }
  13363. if (this.presMap['userId']) {
  13364. pres.c('userId').t(this.presMap['userId']).up();
  13365. }
  13366. if (this.presMap['displayName']) {
  13367. // XEP-0172
  13368. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13369. .t(this.presMap['displayName']).up();
  13370. }
  13371. if(this.presMap["devices"])
  13372. {
  13373. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  13374. .c('video').t(this.presMap['devices'].video).up().up();
  13375. }
  13376. if (this.presMap['audions']) {
  13377. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13378. .t(this.presMap['audiomuted']).up();
  13379. }
  13380. if (this.presMap['videons']) {
  13381. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13382. .t(this.presMap['videomuted']).up();
  13383. }
  13384. if (this.presMap['statsns']) {
  13385. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13386. for (var stat in this.presMap["stats"])
  13387. if (this.presMap["stats"][stat] != null)
  13388. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13389. pres.up();
  13390. }
  13391. if (this.presMap['prezins']) {
  13392. pres.c('prezi',
  13393. {xmlns: this.presMap['prezins'],
  13394. 'url': this.presMap['preziurl']})
  13395. .c('current').t(this.presMap['prezicurrent']).up().up();
  13396. }
  13397. if (this.presMap['etherpadns']) {
  13398. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13399. .t(this.presMap['etherpadname']).up();
  13400. }
  13401. if (this.presMap['medians']) {
  13402. pres.c('media', {xmlns: this.presMap['medians']});
  13403. var sourceNumber = 0;
  13404. Object.keys(this.presMap).forEach(function (key) {
  13405. if (key.indexOf('source') >= 0) {
  13406. sourceNumber++;
  13407. }
  13408. });
  13409. if (sourceNumber > 0)
  13410. for (var i = 1; i <= sourceNumber / 3; i++) {
  13411. pres.c('source',
  13412. {type: this.presMap['source' + i + '_type'],
  13413. ssrc: this.presMap['source' + i + '_ssrc'],
  13414. direction: this.presMap['source' + i + '_direction']
  13415. || 'sendrecv' }
  13416. ).up();
  13417. }
  13418. pres.up();
  13419. }
  13420. if(this.presMap["startMuted"] !== undefined)
  13421. {
  13422. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  13423. video: this.presMap["startMuted"].video,
  13424. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  13425. delete this.presMap["startMuted"];
  13426. }
  13427. pres.up();
  13428. this.connection.send(pres);
  13429. },
  13430. addDisplayNameToPresence: function (displayName) {
  13431. this.presMap['displayName'] = displayName;
  13432. },
  13433. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13434. if (!this.presMap['medians'])
  13435. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13436. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13437. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13438. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13439. },
  13440. addDevicesToPresence: function (devices) {
  13441. this.presMap['devices'] = devices;
  13442. },
  13443. clearPresenceMedia: function () {
  13444. var self = this;
  13445. Object.keys(this.presMap).forEach(function (key) {
  13446. if (key.indexOf('source') != -1) {
  13447. delete self.presMap[key];
  13448. }
  13449. });
  13450. },
  13451. addPreziToPresence: function (url, currentSlide) {
  13452. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13453. this.presMap['preziurl'] = url;
  13454. this.presMap['prezicurrent'] = currentSlide;
  13455. },
  13456. removePreziFromPresence: function () {
  13457. delete this.presMap['prezins'];
  13458. delete this.presMap['preziurl'];
  13459. delete this.presMap['prezicurrent'];
  13460. },
  13461. addCurrentSlideToPresence: function (currentSlide) {
  13462. this.presMap['prezicurrent'] = currentSlide;
  13463. },
  13464. getPrezi: function (roomjid) {
  13465. return this.preziMap[roomjid];
  13466. },
  13467. addEtherpadToPresence: function (etherpadName) {
  13468. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13469. this.presMap['etherpadname'] = etherpadName;
  13470. },
  13471. addAudioInfoToPresence: function (isMuted) {
  13472. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13473. this.presMap['audiomuted'] = isMuted.toString();
  13474. },
  13475. addVideoInfoToPresence: function (isMuted) {
  13476. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13477. this.presMap['videomuted'] = isMuted.toString();
  13478. },
  13479. addConnectionInfoToPresence: function (stats) {
  13480. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13481. this.presMap['stats'] = stats;
  13482. },
  13483. findJidFromResource: function (resourceJid) {
  13484. if (resourceJid &&
  13485. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13486. return this.myroomjid;
  13487. }
  13488. var peerJid = null;
  13489. Object.keys(this.members).some(function (jid) {
  13490. peerJid = jid;
  13491. return Strophe.getResourceFromJid(jid) === resourceJid;
  13492. });
  13493. return peerJid;
  13494. },
  13495. addBridgeIsDownToPresence: function () {
  13496. this.presMap['bridgeIsDown'] = true;
  13497. },
  13498. addEmailToPresence: function (email) {
  13499. this.presMap['email'] = email;
  13500. },
  13501. addUserIdToPresence: function (userId) {
  13502. this.presMap['userId'] = userId;
  13503. },
  13504. addStartMutedToPresence: function (audio, video) {
  13505. this.presMap["startMuted"] = {audio: audio, video: video};
  13506. },
  13507. isModerator: function () {
  13508. return this.role === 'moderator';
  13509. },
  13510. getMemberRole: function (peerJid) {
  13511. if (this.members[peerJid]) {
  13512. return this.members[peerJid].role;
  13513. }
  13514. return null;
  13515. },
  13516. onParticipantLeft: function (jid) {
  13517. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  13518. this.connection.jingle.terminateByJid(jid);
  13519. if (this.getPrezi(jid)) {
  13520. $(document).trigger('presentationremoved.muc',
  13521. [jid, this.getPrezi(jid)]);
  13522. }
  13523. Moderator.onMucMemberLeft(jid);
  13524. },
  13525. parsePresence: function (from, memeber, pres) {
  13526. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13527. bridgeIsDown = true;
  13528. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13529. }
  13530. if(memeber.isFocus)
  13531. return;
  13532. var self = this;
  13533. // Remove old ssrcs coming from the jid
  13534. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13535. if (self.ssrc2jid[ssrc] == from) {
  13536. delete self.ssrc2jid[ssrc];
  13537. }
  13538. });
  13539. var changedStreams = [];
  13540. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13541. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13542. var ssrcV = ssrc.getAttribute('ssrc');
  13543. self.ssrc2jid[ssrcV] = from;
  13544. var type = ssrc.getAttribute('type');
  13545. var direction = ssrc.getAttribute('direction');
  13546. changedStreams.push({type: type, direction: direction});
  13547. });
  13548. eventEmitter.emit(XMPPEvents.STREAMS_CHANGED, from, changedStreams);
  13549. var displayName = !config.displayJids
  13550. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13551. if (displayName && displayName.length > 0)
  13552. {
  13553. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13554. }
  13555. var id = $(pres).find('>userID').text();
  13556. var email = $(pres).find('>email');
  13557. if(email.length > 0) {
  13558. id = email.text();
  13559. }
  13560. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13561. }
  13562. });
  13563. };
  13564. },{"../../service/xmpp/XMPPEvents":112,"./JingleSession":46,"./moderator":51}],54:[function(require,module,exports){
  13565. /* jshint -W117 */
  13566. var JingleSession = require("./JingleSession");
  13567. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13568. module.exports = function(XMPP, eventEmitter)
  13569. {
  13570. function CallIncomingJingle(sid, connection) {
  13571. var sess = connection.jingle.sessions[sid];
  13572. // TODO: do we check activecall == null?
  13573. connection.jingle.activecall = sess;
  13574. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13575. // TODO: check affiliation and/or role
  13576. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13577. sess.usedrip = true; // not-so-naive trickle ice
  13578. sess.sendAnswer();
  13579. sess.accept();
  13580. };
  13581. Strophe.addConnectionPlugin('jingle', {
  13582. connection: null,
  13583. sessions: {},
  13584. jid2session: {},
  13585. ice_config: {iceServers: []},
  13586. pc_constraints: {},
  13587. activecall: null,
  13588. media_constraints: {
  13589. mandatory: {
  13590. 'OfferToReceiveAudio': true,
  13591. 'OfferToReceiveVideo': true
  13592. }
  13593. // MozDontOfferDataChannel: true when this is firefox
  13594. },
  13595. init: function (conn) {
  13596. this.connection = conn;
  13597. if (this.connection.disco) {
  13598. // http://xmpp.org/extensions/xep-0167.html#support
  13599. // http://xmpp.org/extensions/xep-0176.html#support
  13600. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  13601. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  13602. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  13603. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  13604. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  13605. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  13606. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  13607. // this is dealt with by SDP O/A so we don't need to annouce this
  13608. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  13609. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  13610. if (config.useRtcpMux) {
  13611. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  13612. }
  13613. if (config.useBundle) {
  13614. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  13615. }
  13616. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  13617. }
  13618. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  13619. },
  13620. onJingle: function (iq) {
  13621. var sid = $(iq).find('jingle').attr('sid');
  13622. var action = $(iq).find('jingle').attr('action');
  13623. var fromJid = iq.getAttribute('from');
  13624. // send ack first
  13625. var ack = $iq({type: 'result',
  13626. to: fromJid,
  13627. id: iq.getAttribute('id')
  13628. });
  13629. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  13630. var sess = this.sessions[sid];
  13631. if ('session-initiate' != action) {
  13632. if (sess === null) {
  13633. ack.type = 'error';
  13634. ack.c('error', {type: 'cancel'})
  13635. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13636. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13637. this.connection.send(ack);
  13638. return true;
  13639. }
  13640. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  13641. // local jid is not checked
  13642. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  13643. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  13644. ack.type = 'error';
  13645. ack.c('error', {type: 'cancel'})
  13646. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13647. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13648. this.connection.send(ack);
  13649. return true;
  13650. }
  13651. } else if (sess !== undefined) {
  13652. // existing session with same session id
  13653. // this might be out-of-order if the sess.peerjid is the same as from
  13654. ack.type = 'error';
  13655. ack.c('error', {type: 'cancel'})
  13656. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  13657. console.warn('duplicate session id', sid);
  13658. this.connection.send(ack);
  13659. return true;
  13660. }
  13661. // FIXME: check for a defined action
  13662. this.connection.send(ack);
  13663. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  13664. switch (action) {
  13665. case 'session-initiate':
  13666. var startMuted = $(iq).find('jingle>startmuted');
  13667. if(startMuted && startMuted.length > 0)
  13668. {
  13669. var audioMuted = startMuted.attr("audio");
  13670. var videoMuted = startMuted.attr("video");
  13671. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  13672. (videoMuted === "true"));
  13673. }
  13674. sess = new JingleSession(
  13675. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  13676. this.connection, XMPP);
  13677. // configure session
  13678. sess.media_constraints = this.media_constraints;
  13679. sess.pc_constraints = this.pc_constraints;
  13680. sess.ice_config = this.ice_config;
  13681. sess.initiate(fromJid, false);
  13682. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  13683. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  13684. this.sessions[sess.sid] = sess;
  13685. this.jid2session[sess.peerjid] = sess;
  13686. // the callback should either
  13687. // .sendAnswer and .accept
  13688. // or .sendTerminate -- not necessarily synchronus
  13689. CallIncomingJingle(sess.sid, this.connection);
  13690. break;
  13691. case 'session-accept':
  13692. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  13693. sess.accept();
  13694. $(document).trigger('callaccepted.jingle', [sess.sid]);
  13695. break;
  13696. case 'session-terminate':
  13697. // If this is not the focus sending the terminate, we have
  13698. // nothing more to do here.
  13699. if (Object.keys(this.sessions).length < 1
  13700. || !(this.sessions[Object.keys(this.sessions)[0]]
  13701. instanceof JingleSession))
  13702. {
  13703. break;
  13704. }
  13705. console.log('terminating...', sess.sid);
  13706. sess.terminate();
  13707. this.terminate(sess.sid);
  13708. if ($(iq).find('>jingle>reason').length) {
  13709. $(document).trigger('callterminated.jingle', [
  13710. sess.sid,
  13711. sess.peerjid,
  13712. $(iq).find('>jingle>reason>:first')[0].tagName,
  13713. $(iq).find('>jingle>reason>text').text()
  13714. ]);
  13715. } else {
  13716. $(document).trigger('callterminated.jingle',
  13717. [sess.sid, sess.peerjid]);
  13718. }
  13719. break;
  13720. case 'transport-info':
  13721. sess.addIceCandidate($(iq).find('>jingle>content'));
  13722. break;
  13723. case 'session-info':
  13724. var affected;
  13725. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13726. $(document).trigger('ringing.jingle', [sess.sid]);
  13727. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13728. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13729. $(document).trigger('mute.jingle', [sess.sid, affected]);
  13730. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13731. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13732. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  13733. }
  13734. break;
  13735. case 'addsource': // FIXME: proprietary, un-jingleish
  13736. case 'source-add': // FIXME: proprietary
  13737. sess.addSource($(iq).find('>jingle>content'), fromJid);
  13738. break;
  13739. case 'removesource': // FIXME: proprietary, un-jingleish
  13740. case 'source-remove': // FIXME: proprietary
  13741. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  13742. break;
  13743. default:
  13744. console.warn('jingle action not implemented', action);
  13745. break;
  13746. }
  13747. return true;
  13748. },
  13749. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  13750. var sess = new JingleSession(myjid || this.connection.jid,
  13751. Math.random().toString(36).substr(2, 12), // random string
  13752. this.connection, XMPP);
  13753. // configure session
  13754. sess.media_constraints = this.media_constraints;
  13755. sess.pc_constraints = this.pc_constraints;
  13756. sess.ice_config = this.ice_config;
  13757. sess.initiate(peerjid, true);
  13758. this.sessions[sess.sid] = sess;
  13759. this.jid2session[sess.peerjid] = sess;
  13760. sess.sendOffer();
  13761. return sess;
  13762. },
  13763. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  13764. if (sid === null || sid === undefined) {
  13765. for (sid in this.sessions) {
  13766. if (this.sessions[sid].state != 'ended') {
  13767. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  13768. this.sessions[sid].terminate();
  13769. }
  13770. delete this.jid2session[this.sessions[sid].peerjid];
  13771. delete this.sessions[sid];
  13772. }
  13773. } else if (this.sessions.hasOwnProperty(sid)) {
  13774. if (this.sessions[sid].state != 'ended') {
  13775. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  13776. this.sessions[sid].terminate();
  13777. }
  13778. delete this.jid2session[this.sessions[sid].peerjid];
  13779. delete this.sessions[sid];
  13780. }
  13781. },
  13782. // Used to terminate a session when an unavailable presence is received.
  13783. terminateByJid: function (jid) {
  13784. if (this.jid2session.hasOwnProperty(jid)) {
  13785. var sess = this.jid2session[jid];
  13786. if (sess) {
  13787. sess.terminate();
  13788. console.log('peer went away silently', jid);
  13789. delete this.sessions[sess.sid];
  13790. delete this.jid2session[jid];
  13791. $(document).trigger('callterminated.jingle',
  13792. [sess.sid, jid], 'gone');
  13793. }
  13794. }
  13795. },
  13796. terminateRemoteByJid: function (jid, reason) {
  13797. if (this.jid2session.hasOwnProperty(jid)) {
  13798. var sess = this.jid2session[jid];
  13799. if (sess) {
  13800. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  13801. sess.terminate();
  13802. console.log('terminate peer with jid', sess.sid, jid);
  13803. delete this.sessions[sess.sid];
  13804. delete this.jid2session[jid];
  13805. $(document).trigger('callterminated.jingle',
  13806. [sess.sid, jid, 'kicked']);
  13807. }
  13808. }
  13809. },
  13810. getStunAndTurnCredentials: function () {
  13811. // get stun and turn configuration from server via xep-0215
  13812. // uses time-limited credentials as described in
  13813. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  13814. //
  13815. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  13816. // for a prosody module which implements this
  13817. //
  13818. // currently, this doesn't work with updateIce and therefore credentials with a long
  13819. // validity have to be fetched before creating the peerconnection
  13820. // TODO: implement refresh via updateIce as described in
  13821. // https://code.google.com/p/webrtc/issues/detail?id=1650
  13822. var self = this;
  13823. this.connection.sendIQ(
  13824. $iq({type: 'get', to: this.connection.domain})
  13825. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  13826. function (res) {
  13827. var iceservers = [];
  13828. $(res).find('>services>service').each(function (idx, el) {
  13829. el = $(el);
  13830. var dict = {};
  13831. var type = el.attr('type');
  13832. switch (type) {
  13833. case 'stun':
  13834. dict.url = 'stun:' + el.attr('host');
  13835. if (el.attr('port')) {
  13836. dict.url += ':' + el.attr('port');
  13837. }
  13838. iceservers.push(dict);
  13839. break;
  13840. case 'turn':
  13841. case 'turns':
  13842. dict.url = type + ':';
  13843. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  13844. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  13845. dict.url += el.attr('username') + '@';
  13846. } else {
  13847. dict.username = el.attr('username'); // only works in M28
  13848. }
  13849. }
  13850. dict.url += el.attr('host');
  13851. if (el.attr('port') && el.attr('port') != '3478') {
  13852. dict.url += ':' + el.attr('port');
  13853. }
  13854. if (el.attr('transport') && el.attr('transport') != 'udp') {
  13855. dict.url += '?transport=' + el.attr('transport');
  13856. }
  13857. if (el.attr('password')) {
  13858. dict.credential = el.attr('password');
  13859. }
  13860. iceservers.push(dict);
  13861. break;
  13862. }
  13863. });
  13864. self.ice_config.iceServers = iceservers;
  13865. },
  13866. function (err) {
  13867. console.warn('getting turn credentials failed', err);
  13868. console.warn('is mod_turncredentials or similar installed?');
  13869. }
  13870. );
  13871. // implement push?
  13872. },
  13873. /**
  13874. * Populates the log data
  13875. */
  13876. populateData: function () {
  13877. var data = {};
  13878. Object.keys(this.sessions).forEach(function (sid) {
  13879. var session = this.sessions[sid];
  13880. if (session.peerconnection && session.peerconnection.updateLog) {
  13881. // FIXME: should probably be a .dump call
  13882. data["jingle_" + session.sid] = {
  13883. updateLog: session.peerconnection.updateLog,
  13884. stats: session.peerconnection.stats,
  13885. url: window.location.href
  13886. };
  13887. }
  13888. });
  13889. return data;
  13890. }
  13891. });
  13892. };
  13893. },{"../../service/xmpp/XMPPEvents":112,"./JingleSession":46}],55:[function(require,module,exports){
  13894. /* global Strophe */
  13895. module.exports = function () {
  13896. Strophe.addConnectionPlugin('logger', {
  13897. // logs raw stanzas and makes them available for download as JSON
  13898. connection: null,
  13899. log: [],
  13900. init: function (conn) {
  13901. this.connection = conn;
  13902. this.connection.rawInput = this.log_incoming.bind(this);
  13903. this.connection.rawOutput = this.log_outgoing.bind(this);
  13904. },
  13905. log_incoming: function (stanza) {
  13906. this.log.push([new Date().getTime(), 'incoming', stanza]);
  13907. },
  13908. log_outgoing: function (stanza) {
  13909. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  13910. }
  13911. });
  13912. };
  13913. },{}],56:[function(require,module,exports){
  13914. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  13915. setAudioMuted, Strophe */
  13916. /**
  13917. * Moderate connection plugin.
  13918. */
  13919. module.exports = function (XMPP) {
  13920. Strophe.addConnectionPlugin('moderate', {
  13921. connection: null,
  13922. init: function (conn) {
  13923. this.connection = conn;
  13924. this.connection.addHandler(this.onMute.bind(this),
  13925. 'http://jitsi.org/jitmeet/audio',
  13926. 'iq',
  13927. 'set',
  13928. null,
  13929. null);
  13930. },
  13931. setMute: function (jid, mute) {
  13932. console.info("set mute", mute);
  13933. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  13934. .c('mute', {
  13935. xmlns: 'http://jitsi.org/jitmeet/audio',
  13936. jid: jid
  13937. })
  13938. .t(mute.toString())
  13939. .up();
  13940. this.connection.sendIQ(
  13941. iqToFocus,
  13942. function (result) {
  13943. console.log('set mute', result);
  13944. },
  13945. function (error) {
  13946. console.log('set mute error', error);
  13947. });
  13948. },
  13949. onMute: function (iq) {
  13950. var from = iq.getAttribute('from');
  13951. if (from !== this.connection.emuc.focusMucJid) {
  13952. console.warn("Ignored mute from non focus peer");
  13953. return false;
  13954. }
  13955. var mute = $(iq).find('mute');
  13956. if (mute.length) {
  13957. var doMuteAudio = mute.text() === "true";
  13958. APP.UI.setAudioMuted(doMuteAudio);
  13959. XMPP.forceMuted = doMuteAudio;
  13960. }
  13961. return true;
  13962. },
  13963. eject: function (jid) {
  13964. // We're not the focus, so can't terminate
  13965. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  13966. this.connection.emuc.kick(jid);
  13967. }
  13968. });
  13969. }
  13970. },{}],57:[function(require,module,exports){
  13971. /* jshint -W117 */
  13972. module.exports = function() {
  13973. Strophe.addConnectionPlugin('rayo',
  13974. {
  13975. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  13976. connection: null,
  13977. init: function (conn) {
  13978. this.connection = conn;
  13979. if (this.connection.disco) {
  13980. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  13981. }
  13982. this.connection.addHandler(
  13983. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  13984. },
  13985. onRayo: function (iq) {
  13986. console.info("Rayo IQ", iq);
  13987. },
  13988. dial: function (to, from, roomName, roomPass) {
  13989. var self = this;
  13990. var req = $iq(
  13991. {
  13992. type: 'set',
  13993. to: this.connection.emuc.focusMucJid
  13994. }
  13995. );
  13996. req.c('dial',
  13997. {
  13998. xmlns: this.RAYO_XMLNS,
  13999. to: to,
  14000. from: from
  14001. });
  14002. req.c('header',
  14003. {
  14004. name: 'JvbRoomName',
  14005. value: roomName
  14006. }).up();
  14007. if (roomPass !== null && roomPass.length) {
  14008. req.c('header',
  14009. {
  14010. name: 'JvbRoomPassword',
  14011. value: roomPass
  14012. }).up();
  14013. }
  14014. this.connection.sendIQ(
  14015. req,
  14016. function (result) {
  14017. console.info('Dial result ', result);
  14018. var resource = $(result).find('ref').attr('uri');
  14019. this.call_resource = resource.substr('xmpp:'.length);
  14020. console.info(
  14021. "Received call resource: " + this.call_resource);
  14022. },
  14023. function (error) {
  14024. console.info('Dial error ', error);
  14025. }
  14026. );
  14027. },
  14028. hang_up: function () {
  14029. if (!this.call_resource) {
  14030. console.warn("No call in progress");
  14031. return;
  14032. }
  14033. var self = this;
  14034. var req = $iq(
  14035. {
  14036. type: 'set',
  14037. to: this.call_resource
  14038. }
  14039. );
  14040. req.c('hangup',
  14041. {
  14042. xmlns: this.RAYO_XMLNS
  14043. });
  14044. this.connection.sendIQ(
  14045. req,
  14046. function (result) {
  14047. console.info('Hangup result ', result);
  14048. self.call_resource = null;
  14049. },
  14050. function (error) {
  14051. console.info('Hangup error ', error);
  14052. self.call_resource = null;
  14053. }
  14054. );
  14055. }
  14056. }
  14057. );
  14058. };
  14059. },{}],58:[function(require,module,exports){
  14060. /**
  14061. * Strophe logger implementation. Logs from level WARN and above.
  14062. */
  14063. module.exports = function () {
  14064. Strophe.log = function (level, msg) {
  14065. switch (level) {
  14066. case Strophe.LogLevel.WARN:
  14067. console.warn("Strophe: " + msg);
  14068. break;
  14069. case Strophe.LogLevel.ERROR:
  14070. case Strophe.LogLevel.FATAL:
  14071. console.error("Strophe: " + msg);
  14072. break;
  14073. }
  14074. };
  14075. Strophe.getStatusString = function (status) {
  14076. switch (status) {
  14077. case Strophe.Status.ERROR:
  14078. return "ERROR";
  14079. case Strophe.Status.CONNECTING:
  14080. return "CONNECTING";
  14081. case Strophe.Status.CONNFAIL:
  14082. return "CONNFAIL";
  14083. case Strophe.Status.AUTHENTICATING:
  14084. return "AUTHENTICATING";
  14085. case Strophe.Status.AUTHFAIL:
  14086. return "AUTHFAIL";
  14087. case Strophe.Status.CONNECTED:
  14088. return "CONNECTED";
  14089. case Strophe.Status.DISCONNECTED:
  14090. return "DISCONNECTED";
  14091. case Strophe.Status.DISCONNECTING:
  14092. return "DISCONNECTING";
  14093. case Strophe.Status.ATTACHED:
  14094. return "ATTACHED";
  14095. default:
  14096. return "unknown";
  14097. }
  14098. };
  14099. };
  14100. },{}],59:[function(require,module,exports){
  14101. /* global $, APP, config, Strophe*/
  14102. var Moderator = require("./moderator");
  14103. var EventEmitter = require("events");
  14104. var Recording = require("./recording");
  14105. var SDP = require("./SDP");
  14106. var Settings = require("../settings/Settings");
  14107. var Pako = require("pako");
  14108. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14109. var RTCEvents = require("../../service/RTC/RTCEvents");
  14110. var UIEvents = require("../../service/UI/UIEvents");
  14111. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14112. var retry = require('retry');
  14113. var eventEmitter = new EventEmitter();
  14114. var connection = null;
  14115. var authenticatedUser = false;
  14116. function connect(jid, password) {
  14117. var faultTolerantConnect = retry.operation({
  14118. retries: 3
  14119. });
  14120. // fault tolerant connect
  14121. faultTolerantConnect.attempt(function () {
  14122. connection = XMPP.createConnection();
  14123. Moderator.setConnection(connection);
  14124. if (connection.disco) {
  14125. // for chrome, add multistream cap
  14126. }
  14127. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14128. if (config.useIPv6) {
  14129. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14130. if (!connection.jingle.pc_constraints.optional)
  14131. connection.jingle.pc_constraints.optional = [];
  14132. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14133. }
  14134. // Include user info in MUC presence
  14135. var settings = Settings.getSettings();
  14136. if (settings.email) {
  14137. connection.emuc.addEmailToPresence(settings.email);
  14138. }
  14139. if (settings.uid) {
  14140. connection.emuc.addUserIdToPresence(settings.uid);
  14141. }
  14142. if (settings.displayName) {
  14143. connection.emuc.addDisplayNameToPresence(settings.displayName);
  14144. }
  14145. // connection.connect() starts the connection process.
  14146. //
  14147. // As the connection process proceeds, the user supplied callback will
  14148. // be triggered multiple times with status updates. The callback should
  14149. // take two arguments - the status code and the error condition.
  14150. //
  14151. // The status code will be one of the values in the Strophe.Status
  14152. // constants. The error condition will be one of the conditions defined
  14153. // in RFC 3920 or the condition ‘strophe-parsererror’.
  14154. //
  14155. // The Parameters wait, hold and route are optional and only relevant
  14156. // for BOSH connections. Please see XEP 124 for a more detailed
  14157. // explanation of the optional parameters.
  14158. //
  14159. // Connection status constants for use by the connection handler
  14160. // callback.
  14161. //
  14162. // Status.ERROR - An error has occurred (websockets specific)
  14163. // Status.CONNECTING - The connection is currently being made
  14164. // Status.CONNFAIL - The connection attempt failed
  14165. // Status.AUTHENTICATING - The connection is authenticating
  14166. // Status.AUTHFAIL - The authentication attempt failed
  14167. // Status.CONNECTED - The connection has succeeded
  14168. // Status.DISCONNECTED - The connection has been terminated
  14169. // Status.DISCONNECTING - The connection is currently being terminated
  14170. // Status.ATTACHED - The connection has been attached
  14171. var anonymousConnectionFailed = false;
  14172. var connectionFailed = false;
  14173. var lastErrorMsg;
  14174. connection.connect(jid, password, function (status, msg) {
  14175. console.log('Strophe status changed to',
  14176. Strophe.getStatusString(status), msg);
  14177. if (status === Strophe.Status.CONNECTED) {
  14178. if (config.useStunTurn) {
  14179. connection.jingle.getStunAndTurnCredentials();
  14180. }
  14181. console.info("My Jabber ID: " + connection.jid);
  14182. if (password)
  14183. authenticatedUser = true;
  14184. maybeDoJoin();
  14185. } else if (status === Strophe.Status.CONNFAIL) {
  14186. if (msg === 'x-strophe-bad-non-anon-jid') {
  14187. anonymousConnectionFailed = true;
  14188. } else {
  14189. connectionFailed = true;
  14190. }
  14191. lastErrorMsg = msg;
  14192. } else if (status === Strophe.Status.DISCONNECTED) {
  14193. if (anonymousConnectionFailed) {
  14194. // prompt user for username and password
  14195. XMPP.promptLogin();
  14196. } else {
  14197. // Strophe already has built-in HTTP/BOSH error handling and
  14198. // request retry logic. Requests are resent automatically
  14199. // until their error count reaches 5. Strophe.js disconnects
  14200. // if the error count is > 5. We are not replicating this
  14201. // here.
  14202. //
  14203. // The "problem" is that failed HTTP/BOSH requests don't
  14204. // trigger a callback with a status update, so when a
  14205. // callback with status Strophe.Status.DISCONNECTED arrives,
  14206. // we can't be sure if it's a graceful disconnect or if it's
  14207. // triggered by some HTTP/BOSH error.
  14208. //
  14209. // But that's a minor issue in Jitsi Meet as we never
  14210. // disconnect anyway, not even when the user closes the
  14211. // browser window (which is kind of wrong, but the point is
  14212. // that we should never ever get disconnected).
  14213. //
  14214. // On the other hand, failed connections due to XMPP layer
  14215. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  14216. //
  14217. // Here we implement retry logic for failed connections due
  14218. // to XMPP layer errors and we display an error to the user
  14219. // if we get disconnected from the XMPP server permanently.
  14220. // If the connection failed, retry.
  14221. if (connectionFailed
  14222. && faultTolerantConnect.retry("connection-failed")) {
  14223. return;
  14224. }
  14225. // If we failed to connect to the XMPP server, fire an event
  14226. // to let all the interested module now about it.
  14227. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  14228. msg ? msg : lastErrorMsg);
  14229. }
  14230. } else if (status === Strophe.Status.AUTHFAIL) {
  14231. // wrong password or username, prompt user
  14232. XMPP.promptLogin();
  14233. }
  14234. });
  14235. });
  14236. }
  14237. function maybeDoJoin() {
  14238. if (connection && connection.connected &&
  14239. Strophe.getResourceFromJid(connection.jid)
  14240. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14241. // .connected is true while connecting?
  14242. doJoin();
  14243. }
  14244. }
  14245. function doJoin() {
  14246. var roomName = APP.UI.generateRoomName();
  14247. Moderator.allocateConferenceFocus(
  14248. roomName, APP.UI.checkForNicknameAndJoin);
  14249. }
  14250. function initStrophePlugins()
  14251. {
  14252. require("./strophe.emuc")(XMPP, eventEmitter);
  14253. require("./strophe.jingle")(XMPP, eventEmitter);
  14254. require("./strophe.moderate")(XMPP);
  14255. require("./strophe.util")();
  14256. require("./strophe.rayo")();
  14257. require("./strophe.logger")();
  14258. }
  14259. function registerListeners() {
  14260. APP.RTC.addStreamListener(maybeDoJoin,
  14261. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14262. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  14263. XMPP.addToPresence("devices", devices);
  14264. })
  14265. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14266. XMPP.addToPresence("displayName", nickname);
  14267. });
  14268. }
  14269. var unload = (function () {
  14270. var unloaded = false;
  14271. return function () {
  14272. if (unloaded) { return; }
  14273. unloaded = true;
  14274. if (connection && connection.connected) {
  14275. // ensure signout
  14276. $.ajax({
  14277. type: 'POST',
  14278. url: config.bosh,
  14279. async: false,
  14280. cache: false,
  14281. contentType: 'application/xml',
  14282. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  14283. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  14284. (connection.sid || connection._proto.sid) +
  14285. "' type='terminate'>" +
  14286. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14287. "</body>",
  14288. success: function (data) {
  14289. console.log('signed out');
  14290. console.log(data);
  14291. },
  14292. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14293. console.log('signout error',
  14294. textStatus + ' (' + errorThrown + ')');
  14295. }
  14296. });
  14297. }
  14298. XMPP.disposeConference(true);
  14299. };
  14300. })();
  14301. function setupEvents() {
  14302. // In recent versions of FF the 'beforeunload' event is not fired when the
  14303. // window or the tab is closed. It is only fired when we leave the page
  14304. // (change URL). If this participant doesn't unload properly, then it
  14305. // becomes a ghost for the rest of the participants that stay in the
  14306. // conference. Thankfully handling the 'unload' event in addition to the
  14307. // 'beforeunload' event seems to garante the execution of the 'unload'
  14308. // method at least once.
  14309. //
  14310. // The 'unload' method can safely be run multiple times, it will actually do
  14311. // something only the first time that it's run, so we're don't have to worry
  14312. // about browsers that fire both events.
  14313. $(window).bind('beforeunload', unload);
  14314. $(window).bind('unload', unload);
  14315. }
  14316. var XMPP = {
  14317. getConnection: function(){ return connection; },
  14318. sessionTerminated: false,
  14319. /**
  14320. * XMPP connection status
  14321. */
  14322. Status: Strophe.Status,
  14323. /**
  14324. * Remembers if we were muted by the focus.
  14325. * @type {boolean}
  14326. */
  14327. forceMuted: false,
  14328. start: function () {
  14329. setupEvents();
  14330. initStrophePlugins();
  14331. registerListeners();
  14332. Moderator.init(this, eventEmitter);
  14333. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14334. // Force authenticated domain if room is appended with '?login=true'
  14335. if (config.hosts.anonymousdomain &&
  14336. window.location.search.indexOf("login=true") !== -1) {
  14337. configDomain = config.hosts.domain;
  14338. }
  14339. var jid = configDomain || window.location.hostname;
  14340. connect(jid, null);
  14341. },
  14342. createConnection: function () {
  14343. var bosh = config.bosh || '/http-bind';
  14344. return new Strophe.Connection(bosh);
  14345. },
  14346. getStatusString: function (status) {
  14347. return Strophe.getStatusString(status);
  14348. },
  14349. promptLogin: function () {
  14350. // FIXME: re-use LoginDialog which supports retries
  14351. APP.UI.showLoginPopup(connect);
  14352. },
  14353. joinRoom: function(roomName, useNicks, nick)
  14354. {
  14355. var roomjid;
  14356. roomjid = roomName;
  14357. if (useNicks) {
  14358. if (nick) {
  14359. roomjid += '/' + nick;
  14360. } else {
  14361. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14362. }
  14363. } else {
  14364. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14365. if(!authenticatedUser)
  14366. tmpJid = tmpJid.substr(0, 8);
  14367. roomjid += '/' + tmpJid;
  14368. }
  14369. connection.emuc.doJoin(roomjid);
  14370. },
  14371. myJid: function () {
  14372. if(!connection)
  14373. return null;
  14374. return connection.emuc.myroomjid;
  14375. },
  14376. myResource: function () {
  14377. if(!connection || ! connection.emuc.myroomjid)
  14378. return null;
  14379. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14380. },
  14381. disposeConference: function (onUnload) {
  14382. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14383. var handler = connection.jingle.activecall;
  14384. if (handler && handler.peerconnection) {
  14385. // FIXME: probably removing streams is not required and close() should
  14386. // be enough
  14387. if (APP.RTC.localAudio) {
  14388. handler.peerconnection.removeStream(
  14389. APP.RTC.localAudio.getOriginalStream(), onUnload);
  14390. }
  14391. if (APP.RTC.localVideo) {
  14392. handler.peerconnection.removeStream(
  14393. APP.RTC.localVideo.getOriginalStream(), onUnload);
  14394. }
  14395. handler.peerconnection.close();
  14396. }
  14397. connection.jingle.activecall = null;
  14398. if(!onUnload)
  14399. {
  14400. this.sessionTerminated = true;
  14401. connection.emuc.doLeave();
  14402. }
  14403. },
  14404. addListener: function(type, listener)
  14405. {
  14406. eventEmitter.on(type, listener);
  14407. },
  14408. removeListener: function (type, listener) {
  14409. eventEmitter.removeListener(type, listener);
  14410. },
  14411. allocateConferenceFocus: function(roomName, callback) {
  14412. Moderator.allocateConferenceFocus(roomName, callback);
  14413. },
  14414. getLoginUrl: function (roomName, callback) {
  14415. Moderator.getLoginUrl(roomName, callback);
  14416. },
  14417. getPopupLoginUrl: function (roomName, callback) {
  14418. Moderator.getPopupLoginUrl(roomName, callback);
  14419. },
  14420. isModerator: function () {
  14421. return Moderator.isModerator();
  14422. },
  14423. isSipGatewayEnabled: function () {
  14424. return Moderator.isSipGatewayEnabled();
  14425. },
  14426. isExternalAuthEnabled: function () {
  14427. return Moderator.isExternalAuthEnabled();
  14428. },
  14429. switchStreams: function (stream, oldStream, callback, isAudio) {
  14430. if (connection && connection.jingle.activecall) {
  14431. // FIXME: will block switchInProgress on true value in case of exception
  14432. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  14433. } else {
  14434. // We are done immediately
  14435. console.warn("No conference handler or conference not started yet");
  14436. callback();
  14437. }
  14438. },
  14439. sendVideoInfoPresence: function (mute) {
  14440. if(!connection)
  14441. return;
  14442. connection.emuc.addVideoInfoToPresence(mute);
  14443. connection.emuc.sendPresence();
  14444. },
  14445. setVideoMute: function (mute, callback, options) {
  14446. if(!connection)
  14447. return;
  14448. var self = this;
  14449. var localCallback = function (mute) {
  14450. self.sendVideoInfoPresence(mute);
  14451. return callback(mute);
  14452. };
  14453. if(connection.jingle.activecall)
  14454. {
  14455. connection.jingle.activecall.setVideoMute(
  14456. mute, localCallback, options);
  14457. }
  14458. else {
  14459. localCallback(mute);
  14460. }
  14461. },
  14462. setAudioMute: function (mute, callback) {
  14463. if (!(connection && APP.RTC.localAudio)) {
  14464. return false;
  14465. }
  14466. if (this.forceMuted && !mute) {
  14467. console.info("Asking focus for unmute");
  14468. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14469. // FIXME: wait for result before resetting muted status
  14470. this.forceMuted = false;
  14471. }
  14472. if (mute == APP.RTC.localAudio.isMuted()) {
  14473. // Nothing to do
  14474. return true;
  14475. }
  14476. // It is not clear what is the right way to handle multiple tracks.
  14477. // So at least make sure that they are all muted or all unmuted and
  14478. // that we send presence just once.
  14479. APP.RTC.localAudio.setMute(!mute);
  14480. // isMuted is the opposite of audioEnabled
  14481. this.sendAudioInfoPresence(mute, callback);
  14482. return true;
  14483. },
  14484. sendAudioInfoPresence: function(mute, callback)
  14485. {
  14486. if(connection) {
  14487. connection.emuc.addAudioInfoToPresence(mute);
  14488. connection.emuc.sendPresence();
  14489. }
  14490. callback();
  14491. return true;
  14492. },
  14493. // Really mute video, i.e. dont even send black frames
  14494. muteVideo: function (pc, unmute) {
  14495. // FIXME: this probably needs another of those lovely state safeguards...
  14496. // which checks for iceconn == connected and sigstate == stable
  14497. pc.setRemoteDescription(pc.remoteDescription,
  14498. function () {
  14499. pc.createAnswer(
  14500. function (answer) {
  14501. var sdp = new SDP(answer.sdp);
  14502. if (sdp.media.length > 1) {
  14503. if (unmute)
  14504. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14505. else
  14506. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14507. sdp.raw = sdp.session + sdp.media.join('');
  14508. answer.sdp = sdp.raw;
  14509. }
  14510. pc.setLocalDescription(answer,
  14511. function () {
  14512. console.log('mute SLD ok');
  14513. },
  14514. function (error) {
  14515. console.log('mute SLD error');
  14516. APP.UI.messageHandler.showError("dialog.error",
  14517. "dialog.SLDFailure");
  14518. }
  14519. );
  14520. },
  14521. function (error) {
  14522. console.log(error);
  14523. APP.UI.messageHandler.showError();
  14524. }
  14525. );
  14526. },
  14527. function (error) {
  14528. console.log('muteVideo SRD error');
  14529. APP.UI.messageHandler.showError("dialog.error",
  14530. "dialog.SRDFailure");
  14531. }
  14532. );
  14533. },
  14534. toggleRecording: function (tokenEmptyCallback,
  14535. startingCallback, startedCallback) {
  14536. Recording.toggleRecording(tokenEmptyCallback,
  14537. startingCallback, startedCallback, connection);
  14538. },
  14539. addToPresence: function (name, value, dontSend) {
  14540. switch (name)
  14541. {
  14542. case "displayName":
  14543. connection.emuc.addDisplayNameToPresence(value);
  14544. break;
  14545. case "etherpad":
  14546. connection.emuc.addEtherpadToPresence(value);
  14547. break;
  14548. case "prezi":
  14549. connection.emuc.addPreziToPresence(value, 0);
  14550. break;
  14551. case "preziSlide":
  14552. connection.emuc.addCurrentSlideToPresence(value);
  14553. break;
  14554. case "connectionQuality":
  14555. connection.emuc.addConnectionInfoToPresence(value);
  14556. break;
  14557. case "email":
  14558. connection.emuc.addEmailToPresence(value);
  14559. break;
  14560. case "devices":
  14561. connection.emuc.addDevicesToPresence(value);
  14562. break;
  14563. case "startMuted":
  14564. if(!Moderator.isModerator())
  14565. return;
  14566. connection.emuc.addStartMutedToPresence(value[0],
  14567. value[1]);
  14568. break;
  14569. default :
  14570. console.log("Unknown tag for presence: " + name);
  14571. return;
  14572. }
  14573. if (!dontSend)
  14574. connection.emuc.sendPresence();
  14575. },
  14576. /**
  14577. * Sends 'data' as a log message to the focus. Returns true iff a message
  14578. * was sent.
  14579. * @param data
  14580. * @returns {boolean} true iff a message was sent.
  14581. */
  14582. sendLogs: function (data) {
  14583. if(!connection.emuc.focusMucJid)
  14584. return false;
  14585. var deflate = true;
  14586. var content = JSON.stringify(data);
  14587. if (deflate) {
  14588. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14589. }
  14590. content = Base64.encode(content);
  14591. // XEP-0337-ish
  14592. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14593. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14594. id: 'PeerConnectionStats'});
  14595. message.c('message').t(content).up();
  14596. if (deflate) {
  14597. message.c('tag', {name: "deflated", value: "true"}).up();
  14598. }
  14599. message.up();
  14600. connection.send(message);
  14601. return true;
  14602. },
  14603. populateData: function () {
  14604. var data = {};
  14605. if (connection.jingle) {
  14606. data = connection.jingle.populateData();
  14607. }
  14608. return data;
  14609. },
  14610. getLogger: function () {
  14611. if(connection.logger)
  14612. return connection.logger.log;
  14613. return null;
  14614. },
  14615. getPrezi: function () {
  14616. return connection.emuc.getPrezi(this.myJid());
  14617. },
  14618. removePreziFromPresence: function () {
  14619. connection.emuc.removePreziFromPresence();
  14620. connection.emuc.sendPresence();
  14621. },
  14622. sendChatMessage: function (message, nickname) {
  14623. connection.emuc.sendMessage(message, nickname);
  14624. },
  14625. setSubject: function (topic) {
  14626. connection.emuc.setSubject(topic);
  14627. },
  14628. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14629. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14630. },
  14631. dial: function (to, from, roomName,roomPass) {
  14632. connection.rayo.dial(to, from, roomName,roomPass);
  14633. },
  14634. setMute: function (jid, mute) {
  14635. connection.moderate.setMute(jid, mute);
  14636. },
  14637. eject: function (jid) {
  14638. connection.moderate.eject(jid);
  14639. },
  14640. logout: function (callback) {
  14641. Moderator.logout(callback);
  14642. },
  14643. findJidFromResource: function (resource) {
  14644. return connection.emuc.findJidFromResource(resource);
  14645. },
  14646. getMembers: function () {
  14647. return connection.emuc.members;
  14648. },
  14649. getJidFromSSRC: function (ssrc) {
  14650. if(!connection)
  14651. return null;
  14652. return connection.emuc.ssrc2jid[ssrc];
  14653. },
  14654. getMUCJoined: function () {
  14655. return connection.emuc.joined;
  14656. },
  14657. getSessions: function () {
  14658. return connection.jingle.sessions;
  14659. },
  14660. removeStream: function (stream) {
  14661. if(!connection || !connection.jingle.activecall ||
  14662. !connection.jingle.activecall.peerconnection)
  14663. return;
  14664. connection.jingle.activecall.peerconnection.removeStream(stream);
  14665. }
  14666. };
  14667. module.exports = XMPP;
  14668. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes":105,"../../service/UI/UIEvents":106,"../../service/xmpp/XMPPEvents":112,"../settings/Settings":41,"./SDP":47,"./moderator":51,"./recording":52,"./strophe.emuc":53,"./strophe.jingle":54,"./strophe.logger":55,"./strophe.moderate":56,"./strophe.rayo":57,"./strophe.util":58,"events":62,"pako":64,"retry":80}],60:[function(require,module,exports){
  14669. (function (process){
  14670. /*!
  14671. * async
  14672. * https://github.com/caolan/async
  14673. *
  14674. * Copyright 2010-2014 Caolan McMahon
  14675. * Released under the MIT license
  14676. */
  14677. /*jshint onevar: false, indent:4 */
  14678. /*global setImmediate: false, setTimeout: false, console: false */
  14679. (function () {
  14680. var async = {};
  14681. // global on the server, window in the browser
  14682. var root, previous_async;
  14683. root = this;
  14684. if (root != null) {
  14685. previous_async = root.async;
  14686. }
  14687. async.noConflict = function () {
  14688. root.async = previous_async;
  14689. return async;
  14690. };
  14691. function only_once(fn) {
  14692. var called = false;
  14693. return function() {
  14694. if (called) throw new Error("Callback was already called.");
  14695. called = true;
  14696. fn.apply(root, arguments);
  14697. }
  14698. }
  14699. //// cross-browser compatiblity functions ////
  14700. var _toString = Object.prototype.toString;
  14701. var _isArray = Array.isArray || function (obj) {
  14702. return _toString.call(obj) === '[object Array]';
  14703. };
  14704. var _each = function (arr, iterator) {
  14705. if (arr.forEach) {
  14706. return arr.forEach(iterator);
  14707. }
  14708. for (var i = 0; i < arr.length; i += 1) {
  14709. iterator(arr[i], i, arr);
  14710. }
  14711. };
  14712. var _map = function (arr, iterator) {
  14713. if (arr.map) {
  14714. return arr.map(iterator);
  14715. }
  14716. var results = [];
  14717. _each(arr, function (x, i, a) {
  14718. results.push(iterator(x, i, a));
  14719. });
  14720. return results;
  14721. };
  14722. var _reduce = function (arr, iterator, memo) {
  14723. if (arr.reduce) {
  14724. return arr.reduce(iterator, memo);
  14725. }
  14726. _each(arr, function (x, i, a) {
  14727. memo = iterator(memo, x, i, a);
  14728. });
  14729. return memo;
  14730. };
  14731. var _keys = function (obj) {
  14732. if (Object.keys) {
  14733. return Object.keys(obj);
  14734. }
  14735. var keys = [];
  14736. for (var k in obj) {
  14737. if (obj.hasOwnProperty(k)) {
  14738. keys.push(k);
  14739. }
  14740. }
  14741. return keys;
  14742. };
  14743. //// exported async module functions ////
  14744. //// nextTick implementation with browser-compatible fallback ////
  14745. if (typeof process === 'undefined' || !(process.nextTick)) {
  14746. if (typeof setImmediate === 'function') {
  14747. async.nextTick = function (fn) {
  14748. // not a direct alias for IE10 compatibility
  14749. setImmediate(fn);
  14750. };
  14751. async.setImmediate = async.nextTick;
  14752. }
  14753. else {
  14754. async.nextTick = function (fn) {
  14755. setTimeout(fn, 0);
  14756. };
  14757. async.setImmediate = async.nextTick;
  14758. }
  14759. }
  14760. else {
  14761. async.nextTick = process.nextTick;
  14762. if (typeof setImmediate !== 'undefined') {
  14763. async.setImmediate = function (fn) {
  14764. // not a direct alias for IE10 compatibility
  14765. setImmediate(fn);
  14766. };
  14767. }
  14768. else {
  14769. async.setImmediate = async.nextTick;
  14770. }
  14771. }
  14772. async.each = function (arr, iterator, callback) {
  14773. callback = callback || function () {};
  14774. if (!arr.length) {
  14775. return callback();
  14776. }
  14777. var completed = 0;
  14778. _each(arr, function (x) {
  14779. iterator(x, only_once(done) );
  14780. });
  14781. function done(err) {
  14782. if (err) {
  14783. callback(err);
  14784. callback = function () {};
  14785. }
  14786. else {
  14787. completed += 1;
  14788. if (completed >= arr.length) {
  14789. callback();
  14790. }
  14791. }
  14792. }
  14793. };
  14794. async.forEach = async.each;
  14795. async.eachSeries = function (arr, iterator, callback) {
  14796. callback = callback || function () {};
  14797. if (!arr.length) {
  14798. return callback();
  14799. }
  14800. var completed = 0;
  14801. var iterate = function () {
  14802. iterator(arr[completed], function (err) {
  14803. if (err) {
  14804. callback(err);
  14805. callback = function () {};
  14806. }
  14807. else {
  14808. completed += 1;
  14809. if (completed >= arr.length) {
  14810. callback();
  14811. }
  14812. else {
  14813. iterate();
  14814. }
  14815. }
  14816. });
  14817. };
  14818. iterate();
  14819. };
  14820. async.forEachSeries = async.eachSeries;
  14821. async.eachLimit = function (arr, limit, iterator, callback) {
  14822. var fn = _eachLimit(limit);
  14823. fn.apply(null, [arr, iterator, callback]);
  14824. };
  14825. async.forEachLimit = async.eachLimit;
  14826. var _eachLimit = function (limit) {
  14827. return function (arr, iterator, callback) {
  14828. callback = callback || function () {};
  14829. if (!arr.length || limit <= 0) {
  14830. return callback();
  14831. }
  14832. var completed = 0;
  14833. var started = 0;
  14834. var running = 0;
  14835. (function replenish () {
  14836. if (completed >= arr.length) {
  14837. return callback();
  14838. }
  14839. while (running < limit && started < arr.length) {
  14840. started += 1;
  14841. running += 1;
  14842. iterator(arr[started - 1], function (err) {
  14843. if (err) {
  14844. callback(err);
  14845. callback = function () {};
  14846. }
  14847. else {
  14848. completed += 1;
  14849. running -= 1;
  14850. if (completed >= arr.length) {
  14851. callback();
  14852. }
  14853. else {
  14854. replenish();
  14855. }
  14856. }
  14857. });
  14858. }
  14859. })();
  14860. };
  14861. };
  14862. var doParallel = function (fn) {
  14863. return function () {
  14864. var args = Array.prototype.slice.call(arguments);
  14865. return fn.apply(null, [async.each].concat(args));
  14866. };
  14867. };
  14868. var doParallelLimit = function(limit, fn) {
  14869. return function () {
  14870. var args = Array.prototype.slice.call(arguments);
  14871. return fn.apply(null, [_eachLimit(limit)].concat(args));
  14872. };
  14873. };
  14874. var doSeries = function (fn) {
  14875. return function () {
  14876. var args = Array.prototype.slice.call(arguments);
  14877. return fn.apply(null, [async.eachSeries].concat(args));
  14878. };
  14879. };
  14880. var _asyncMap = function (eachfn, arr, iterator, callback) {
  14881. arr = _map(arr, function (x, i) {
  14882. return {index: i, value: x};
  14883. });
  14884. if (!callback) {
  14885. eachfn(arr, function (x, callback) {
  14886. iterator(x.value, function (err) {
  14887. callback(err);
  14888. });
  14889. });
  14890. } else {
  14891. var results = [];
  14892. eachfn(arr, function (x, callback) {
  14893. iterator(x.value, function (err, v) {
  14894. results[x.index] = v;
  14895. callback(err);
  14896. });
  14897. }, function (err) {
  14898. callback(err, results);
  14899. });
  14900. }
  14901. };
  14902. async.map = doParallel(_asyncMap);
  14903. async.mapSeries = doSeries(_asyncMap);
  14904. async.mapLimit = function (arr, limit, iterator, callback) {
  14905. return _mapLimit(limit)(arr, iterator, callback);
  14906. };
  14907. var _mapLimit = function(limit) {
  14908. return doParallelLimit(limit, _asyncMap);
  14909. };
  14910. // reduce only has a series version, as doing reduce in parallel won't
  14911. // work in many situations.
  14912. async.reduce = function (arr, memo, iterator, callback) {
  14913. async.eachSeries(arr, function (x, callback) {
  14914. iterator(memo, x, function (err, v) {
  14915. memo = v;
  14916. callback(err);
  14917. });
  14918. }, function (err) {
  14919. callback(err, memo);
  14920. });
  14921. };
  14922. // inject alias
  14923. async.inject = async.reduce;
  14924. // foldl alias
  14925. async.foldl = async.reduce;
  14926. async.reduceRight = function (arr, memo, iterator, callback) {
  14927. var reversed = _map(arr, function (x) {
  14928. return x;
  14929. }).reverse();
  14930. async.reduce(reversed, memo, iterator, callback);
  14931. };
  14932. // foldr alias
  14933. async.foldr = async.reduceRight;
  14934. var _filter = function (eachfn, arr, iterator, callback) {
  14935. var results = [];
  14936. arr = _map(arr, function (x, i) {
  14937. return {index: i, value: x};
  14938. });
  14939. eachfn(arr, function (x, callback) {
  14940. iterator(x.value, function (v) {
  14941. if (v) {
  14942. results.push(x);
  14943. }
  14944. callback();
  14945. });
  14946. }, function (err) {
  14947. callback(_map(results.sort(function (a, b) {
  14948. return a.index - b.index;
  14949. }), function (x) {
  14950. return x.value;
  14951. }));
  14952. });
  14953. };
  14954. async.filter = doParallel(_filter);
  14955. async.filterSeries = doSeries(_filter);
  14956. // select alias
  14957. async.select = async.filter;
  14958. async.selectSeries = async.filterSeries;
  14959. var _reject = function (eachfn, arr, iterator, callback) {
  14960. var results = [];
  14961. arr = _map(arr, function (x, i) {
  14962. return {index: i, value: x};
  14963. });
  14964. eachfn(arr, function (x, callback) {
  14965. iterator(x.value, function (v) {
  14966. if (!v) {
  14967. results.push(x);
  14968. }
  14969. callback();
  14970. });
  14971. }, function (err) {
  14972. callback(_map(results.sort(function (a, b) {
  14973. return a.index - b.index;
  14974. }), function (x) {
  14975. return x.value;
  14976. }));
  14977. });
  14978. };
  14979. async.reject = doParallel(_reject);
  14980. async.rejectSeries = doSeries(_reject);
  14981. var _detect = function (eachfn, arr, iterator, main_callback) {
  14982. eachfn(arr, function (x, callback) {
  14983. iterator(x, function (result) {
  14984. if (result) {
  14985. main_callback(x);
  14986. main_callback = function () {};
  14987. }
  14988. else {
  14989. callback();
  14990. }
  14991. });
  14992. }, function (err) {
  14993. main_callback();
  14994. });
  14995. };
  14996. async.detect = doParallel(_detect);
  14997. async.detectSeries = doSeries(_detect);
  14998. async.some = function (arr, iterator, main_callback) {
  14999. async.each(arr, function (x, callback) {
  15000. iterator(x, function (v) {
  15001. if (v) {
  15002. main_callback(true);
  15003. main_callback = function () {};
  15004. }
  15005. callback();
  15006. });
  15007. }, function (err) {
  15008. main_callback(false);
  15009. });
  15010. };
  15011. // any alias
  15012. async.any = async.some;
  15013. async.every = function (arr, iterator, main_callback) {
  15014. async.each(arr, function (x, callback) {
  15015. iterator(x, function (v) {
  15016. if (!v) {
  15017. main_callback(false);
  15018. main_callback = function () {};
  15019. }
  15020. callback();
  15021. });
  15022. }, function (err) {
  15023. main_callback(true);
  15024. });
  15025. };
  15026. // all alias
  15027. async.all = async.every;
  15028. async.sortBy = function (arr, iterator, callback) {
  15029. async.map(arr, function (x, callback) {
  15030. iterator(x, function (err, criteria) {
  15031. if (err) {
  15032. callback(err);
  15033. }
  15034. else {
  15035. callback(null, {value: x, criteria: criteria});
  15036. }
  15037. });
  15038. }, function (err, results) {
  15039. if (err) {
  15040. return callback(err);
  15041. }
  15042. else {
  15043. var fn = function (left, right) {
  15044. var a = left.criteria, b = right.criteria;
  15045. return a < b ? -1 : a > b ? 1 : 0;
  15046. };
  15047. callback(null, _map(results.sort(fn), function (x) {
  15048. return x.value;
  15049. }));
  15050. }
  15051. });
  15052. };
  15053. async.auto = function (tasks, callback) {
  15054. callback = callback || function () {};
  15055. var keys = _keys(tasks);
  15056. var remainingTasks = keys.length
  15057. if (!remainingTasks) {
  15058. return callback();
  15059. }
  15060. var results = {};
  15061. var listeners = [];
  15062. var addListener = function (fn) {
  15063. listeners.unshift(fn);
  15064. };
  15065. var removeListener = function (fn) {
  15066. for (var i = 0; i < listeners.length; i += 1) {
  15067. if (listeners[i] === fn) {
  15068. listeners.splice(i, 1);
  15069. return;
  15070. }
  15071. }
  15072. };
  15073. var taskComplete = function () {
  15074. remainingTasks--
  15075. _each(listeners.slice(0), function (fn) {
  15076. fn();
  15077. });
  15078. };
  15079. addListener(function () {
  15080. if (!remainingTasks) {
  15081. var theCallback = callback;
  15082. // prevent final callback from calling itself if it errors
  15083. callback = function () {};
  15084. theCallback(null, results);
  15085. }
  15086. });
  15087. _each(keys, function (k) {
  15088. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  15089. var taskCallback = function (err) {
  15090. var args = Array.prototype.slice.call(arguments, 1);
  15091. if (args.length <= 1) {
  15092. args = args[0];
  15093. }
  15094. if (err) {
  15095. var safeResults = {};
  15096. _each(_keys(results), function(rkey) {
  15097. safeResults[rkey] = results[rkey];
  15098. });
  15099. safeResults[k] = args;
  15100. callback(err, safeResults);
  15101. // stop subsequent errors hitting callback multiple times
  15102. callback = function () {};
  15103. }
  15104. else {
  15105. results[k] = args;
  15106. async.setImmediate(taskComplete);
  15107. }
  15108. };
  15109. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  15110. var ready = function () {
  15111. return _reduce(requires, function (a, x) {
  15112. return (a && results.hasOwnProperty(x));
  15113. }, true) && !results.hasOwnProperty(k);
  15114. };
  15115. if (ready()) {
  15116. task[task.length - 1](taskCallback, results);
  15117. }
  15118. else {
  15119. var listener = function () {
  15120. if (ready()) {
  15121. removeListener(listener);
  15122. task[task.length - 1](taskCallback, results);
  15123. }
  15124. };
  15125. addListener(listener);
  15126. }
  15127. });
  15128. };
  15129. async.retry = function(times, task, callback) {
  15130. var DEFAULT_TIMES = 5;
  15131. var attempts = [];
  15132. // Use defaults if times not passed
  15133. if (typeof times === 'function') {
  15134. callback = task;
  15135. task = times;
  15136. times = DEFAULT_TIMES;
  15137. }
  15138. // Make sure times is a number
  15139. times = parseInt(times, 10) || DEFAULT_TIMES;
  15140. var wrappedTask = function(wrappedCallback, wrappedResults) {
  15141. var retryAttempt = function(task, finalAttempt) {
  15142. return function(seriesCallback) {
  15143. task(function(err, result){
  15144. seriesCallback(!err || finalAttempt, {err: err, result: result});
  15145. }, wrappedResults);
  15146. };
  15147. };
  15148. while (times) {
  15149. attempts.push(retryAttempt(task, !(times-=1)));
  15150. }
  15151. async.series(attempts, function(done, data){
  15152. data = data[data.length - 1];
  15153. (wrappedCallback || callback)(data.err, data.result);
  15154. });
  15155. }
  15156. // If a callback is passed, run this as a controll flow
  15157. return callback ? wrappedTask() : wrappedTask
  15158. };
  15159. async.waterfall = function (tasks, callback) {
  15160. callback = callback || function () {};
  15161. if (!_isArray(tasks)) {
  15162. var err = new Error('First argument to waterfall must be an array of functions');
  15163. return callback(err);
  15164. }
  15165. if (!tasks.length) {
  15166. return callback();
  15167. }
  15168. var wrapIterator = function (iterator) {
  15169. return function (err) {
  15170. if (err) {
  15171. callback.apply(null, arguments);
  15172. callback = function () {};
  15173. }
  15174. else {
  15175. var args = Array.prototype.slice.call(arguments, 1);
  15176. var next = iterator.next();
  15177. if (next) {
  15178. args.push(wrapIterator(next));
  15179. }
  15180. else {
  15181. args.push(callback);
  15182. }
  15183. async.setImmediate(function () {
  15184. iterator.apply(null, args);
  15185. });
  15186. }
  15187. };
  15188. };
  15189. wrapIterator(async.iterator(tasks))();
  15190. };
  15191. var _parallel = function(eachfn, tasks, callback) {
  15192. callback = callback || function () {};
  15193. if (_isArray(tasks)) {
  15194. eachfn.map(tasks, function (fn, callback) {
  15195. if (fn) {
  15196. fn(function (err) {
  15197. var args = Array.prototype.slice.call(arguments, 1);
  15198. if (args.length <= 1) {
  15199. args = args[0];
  15200. }
  15201. callback.call(null, err, args);
  15202. });
  15203. }
  15204. }, callback);
  15205. }
  15206. else {
  15207. var results = {};
  15208. eachfn.each(_keys(tasks), function (k, callback) {
  15209. tasks[k](function (err) {
  15210. var args = Array.prototype.slice.call(arguments, 1);
  15211. if (args.length <= 1) {
  15212. args = args[0];
  15213. }
  15214. results[k] = args;
  15215. callback(err);
  15216. });
  15217. }, function (err) {
  15218. callback(err, results);
  15219. });
  15220. }
  15221. };
  15222. async.parallel = function (tasks, callback) {
  15223. _parallel({ map: async.map, each: async.each }, tasks, callback);
  15224. };
  15225. async.parallelLimit = function(tasks, limit, callback) {
  15226. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  15227. };
  15228. async.series = function (tasks, callback) {
  15229. callback = callback || function () {};
  15230. if (_isArray(tasks)) {
  15231. async.mapSeries(tasks, function (fn, callback) {
  15232. if (fn) {
  15233. fn(function (err) {
  15234. var args = Array.prototype.slice.call(arguments, 1);
  15235. if (args.length <= 1) {
  15236. args = args[0];
  15237. }
  15238. callback.call(null, err, args);
  15239. });
  15240. }
  15241. }, callback);
  15242. }
  15243. else {
  15244. var results = {};
  15245. async.eachSeries(_keys(tasks), function (k, callback) {
  15246. tasks[k](function (err) {
  15247. var args = Array.prototype.slice.call(arguments, 1);
  15248. if (args.length <= 1) {
  15249. args = args[0];
  15250. }
  15251. results[k] = args;
  15252. callback(err);
  15253. });
  15254. }, function (err) {
  15255. callback(err, results);
  15256. });
  15257. }
  15258. };
  15259. async.iterator = function (tasks) {
  15260. var makeCallback = function (index) {
  15261. var fn = function () {
  15262. if (tasks.length) {
  15263. tasks[index].apply(null, arguments);
  15264. }
  15265. return fn.next();
  15266. };
  15267. fn.next = function () {
  15268. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  15269. };
  15270. return fn;
  15271. };
  15272. return makeCallback(0);
  15273. };
  15274. async.apply = function (fn) {
  15275. var args = Array.prototype.slice.call(arguments, 1);
  15276. return function () {
  15277. return fn.apply(
  15278. null, args.concat(Array.prototype.slice.call(arguments))
  15279. );
  15280. };
  15281. };
  15282. var _concat = function (eachfn, arr, fn, callback) {
  15283. var r = [];
  15284. eachfn(arr, function (x, cb) {
  15285. fn(x, function (err, y) {
  15286. r = r.concat(y || []);
  15287. cb(err);
  15288. });
  15289. }, function (err) {
  15290. callback(err, r);
  15291. });
  15292. };
  15293. async.concat = doParallel(_concat);
  15294. async.concatSeries = doSeries(_concat);
  15295. async.whilst = function (test, iterator, callback) {
  15296. if (test()) {
  15297. iterator(function (err) {
  15298. if (err) {
  15299. return callback(err);
  15300. }
  15301. async.whilst(test, iterator, callback);
  15302. });
  15303. }
  15304. else {
  15305. callback();
  15306. }
  15307. };
  15308. async.doWhilst = function (iterator, test, callback) {
  15309. iterator(function (err) {
  15310. if (err) {
  15311. return callback(err);
  15312. }
  15313. var args = Array.prototype.slice.call(arguments, 1);
  15314. if (test.apply(null, args)) {
  15315. async.doWhilst(iterator, test, callback);
  15316. }
  15317. else {
  15318. callback();
  15319. }
  15320. });
  15321. };
  15322. async.until = function (test, iterator, callback) {
  15323. if (!test()) {
  15324. iterator(function (err) {
  15325. if (err) {
  15326. return callback(err);
  15327. }
  15328. async.until(test, iterator, callback);
  15329. });
  15330. }
  15331. else {
  15332. callback();
  15333. }
  15334. };
  15335. async.doUntil = function (iterator, test, callback) {
  15336. iterator(function (err) {
  15337. if (err) {
  15338. return callback(err);
  15339. }
  15340. var args = Array.prototype.slice.call(arguments, 1);
  15341. if (!test.apply(null, args)) {
  15342. async.doUntil(iterator, test, callback);
  15343. }
  15344. else {
  15345. callback();
  15346. }
  15347. });
  15348. };
  15349. async.queue = function (worker, concurrency) {
  15350. if (concurrency === undefined) {
  15351. concurrency = 1;
  15352. }
  15353. function _insert(q, data, pos, callback) {
  15354. if (!q.started){
  15355. q.started = true;
  15356. }
  15357. if (!_isArray(data)) {
  15358. data = [data];
  15359. }
  15360. if(data.length == 0) {
  15361. // call drain immediately if there are no tasks
  15362. return async.setImmediate(function() {
  15363. if (q.drain) {
  15364. q.drain();
  15365. }
  15366. });
  15367. }
  15368. _each(data, function(task) {
  15369. var item = {
  15370. data: task,
  15371. callback: typeof callback === 'function' ? callback : null
  15372. };
  15373. if (pos) {
  15374. q.tasks.unshift(item);
  15375. } else {
  15376. q.tasks.push(item);
  15377. }
  15378. if (q.saturated && q.tasks.length === q.concurrency) {
  15379. q.saturated();
  15380. }
  15381. async.setImmediate(q.process);
  15382. });
  15383. }
  15384. var workers = 0;
  15385. var q = {
  15386. tasks: [],
  15387. concurrency: concurrency,
  15388. saturated: null,
  15389. empty: null,
  15390. drain: null,
  15391. started: false,
  15392. paused: false,
  15393. push: function (data, callback) {
  15394. _insert(q, data, false, callback);
  15395. },
  15396. kill: function () {
  15397. q.drain = null;
  15398. q.tasks = [];
  15399. },
  15400. unshift: function (data, callback) {
  15401. _insert(q, data, true, callback);
  15402. },
  15403. process: function () {
  15404. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  15405. var task = q.tasks.shift();
  15406. if (q.empty && q.tasks.length === 0) {
  15407. q.empty();
  15408. }
  15409. workers += 1;
  15410. var next = function () {
  15411. workers -= 1;
  15412. if (task.callback) {
  15413. task.callback.apply(task, arguments);
  15414. }
  15415. if (q.drain && q.tasks.length + workers === 0) {
  15416. q.drain();
  15417. }
  15418. q.process();
  15419. };
  15420. var cb = only_once(next);
  15421. worker(task.data, cb);
  15422. }
  15423. },
  15424. length: function () {
  15425. return q.tasks.length;
  15426. },
  15427. running: function () {
  15428. return workers;
  15429. },
  15430. idle: function() {
  15431. return q.tasks.length + workers === 0;
  15432. },
  15433. pause: function () {
  15434. if (q.paused === true) { return; }
  15435. q.paused = true;
  15436. q.process();
  15437. },
  15438. resume: function () {
  15439. if (q.paused === false) { return; }
  15440. q.paused = false;
  15441. q.process();
  15442. }
  15443. };
  15444. return q;
  15445. };
  15446. async.priorityQueue = function (worker, concurrency) {
  15447. function _compareTasks(a, b){
  15448. return a.priority - b.priority;
  15449. };
  15450. function _binarySearch(sequence, item, compare) {
  15451. var beg = -1,
  15452. end = sequence.length - 1;
  15453. while (beg < end) {
  15454. var mid = beg + ((end - beg + 1) >>> 1);
  15455. if (compare(item, sequence[mid]) >= 0) {
  15456. beg = mid;
  15457. } else {
  15458. end = mid - 1;
  15459. }
  15460. }
  15461. return beg;
  15462. }
  15463. function _insert(q, data, priority, callback) {
  15464. if (!q.started){
  15465. q.started = true;
  15466. }
  15467. if (!_isArray(data)) {
  15468. data = [data];
  15469. }
  15470. if(data.length == 0) {
  15471. // call drain immediately if there are no tasks
  15472. return async.setImmediate(function() {
  15473. if (q.drain) {
  15474. q.drain();
  15475. }
  15476. });
  15477. }
  15478. _each(data, function(task) {
  15479. var item = {
  15480. data: task,
  15481. priority: priority,
  15482. callback: typeof callback === 'function' ? callback : null
  15483. };
  15484. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  15485. if (q.saturated && q.tasks.length === q.concurrency) {
  15486. q.saturated();
  15487. }
  15488. async.setImmediate(q.process);
  15489. });
  15490. }
  15491. // Start with a normal queue
  15492. var q = async.queue(worker, concurrency);
  15493. // Override push to accept second parameter representing priority
  15494. q.push = function (data, priority, callback) {
  15495. _insert(q, data, priority, callback);
  15496. };
  15497. // Remove unshift function
  15498. delete q.unshift;
  15499. return q;
  15500. };
  15501. async.cargo = function (worker, payload) {
  15502. var working = false,
  15503. tasks = [];
  15504. var cargo = {
  15505. tasks: tasks,
  15506. payload: payload,
  15507. saturated: null,
  15508. empty: null,
  15509. drain: null,
  15510. drained: true,
  15511. push: function (data, callback) {
  15512. if (!_isArray(data)) {
  15513. data = [data];
  15514. }
  15515. _each(data, function(task) {
  15516. tasks.push({
  15517. data: task,
  15518. callback: typeof callback === 'function' ? callback : null
  15519. });
  15520. cargo.drained = false;
  15521. if (cargo.saturated && tasks.length === payload) {
  15522. cargo.saturated();
  15523. }
  15524. });
  15525. async.setImmediate(cargo.process);
  15526. },
  15527. process: function process() {
  15528. if (working) return;
  15529. if (tasks.length === 0) {
  15530. if(cargo.drain && !cargo.drained) cargo.drain();
  15531. cargo.drained = true;
  15532. return;
  15533. }
  15534. var ts = typeof payload === 'number'
  15535. ? tasks.splice(0, payload)
  15536. : tasks.splice(0, tasks.length);
  15537. var ds = _map(ts, function (task) {
  15538. return task.data;
  15539. });
  15540. if(cargo.empty) cargo.empty();
  15541. working = true;
  15542. worker(ds, function () {
  15543. working = false;
  15544. var args = arguments;
  15545. _each(ts, function (data) {
  15546. if (data.callback) {
  15547. data.callback.apply(null, args);
  15548. }
  15549. });
  15550. process();
  15551. });
  15552. },
  15553. length: function () {
  15554. return tasks.length;
  15555. },
  15556. running: function () {
  15557. return working;
  15558. }
  15559. };
  15560. return cargo;
  15561. };
  15562. var _console_fn = function (name) {
  15563. return function (fn) {
  15564. var args = Array.prototype.slice.call(arguments, 1);
  15565. fn.apply(null, args.concat([function (err) {
  15566. var args = Array.prototype.slice.call(arguments, 1);
  15567. if (typeof console !== 'undefined') {
  15568. if (err) {
  15569. if (console.error) {
  15570. console.error(err);
  15571. }
  15572. }
  15573. else if (console[name]) {
  15574. _each(args, function (x) {
  15575. console[name](x);
  15576. });
  15577. }
  15578. }
  15579. }]));
  15580. };
  15581. };
  15582. async.log = _console_fn('log');
  15583. async.dir = _console_fn('dir');
  15584. /*async.info = _console_fn('info');
  15585. async.warn = _console_fn('warn');
  15586. async.error = _console_fn('error');*/
  15587. async.memoize = function (fn, hasher) {
  15588. var memo = {};
  15589. var queues = {};
  15590. hasher = hasher || function (x) {
  15591. return x;
  15592. };
  15593. var memoized = function () {
  15594. var args = Array.prototype.slice.call(arguments);
  15595. var callback = args.pop();
  15596. var key = hasher.apply(null, args);
  15597. if (key in memo) {
  15598. async.nextTick(function () {
  15599. callback.apply(null, memo[key]);
  15600. });
  15601. }
  15602. else if (key in queues) {
  15603. queues[key].push(callback);
  15604. }
  15605. else {
  15606. queues[key] = [callback];
  15607. fn.apply(null, args.concat([function () {
  15608. memo[key] = arguments;
  15609. var q = queues[key];
  15610. delete queues[key];
  15611. for (var i = 0, l = q.length; i < l; i++) {
  15612. q[i].apply(null, arguments);
  15613. }
  15614. }]));
  15615. }
  15616. };
  15617. memoized.memo = memo;
  15618. memoized.unmemoized = fn;
  15619. return memoized;
  15620. };
  15621. async.unmemoize = function (fn) {
  15622. return function () {
  15623. return (fn.unmemoized || fn).apply(null, arguments);
  15624. };
  15625. };
  15626. async.times = function (count, iterator, callback) {
  15627. var counter = [];
  15628. for (var i = 0; i < count; i++) {
  15629. counter.push(i);
  15630. }
  15631. return async.map(counter, iterator, callback);
  15632. };
  15633. async.timesSeries = function (count, iterator, callback) {
  15634. var counter = [];
  15635. for (var i = 0; i < count; i++) {
  15636. counter.push(i);
  15637. }
  15638. return async.mapSeries(counter, iterator, callback);
  15639. };
  15640. async.seq = function (/* functions... */) {
  15641. var fns = arguments;
  15642. return function () {
  15643. var that = this;
  15644. var args = Array.prototype.slice.call(arguments);
  15645. var callback = args.pop();
  15646. async.reduce(fns, args, function (newargs, fn, cb) {
  15647. fn.apply(that, newargs.concat([function () {
  15648. var err = arguments[0];
  15649. var nextargs = Array.prototype.slice.call(arguments, 1);
  15650. cb(err, nextargs);
  15651. }]))
  15652. },
  15653. function (err, results) {
  15654. callback.apply(that, [err].concat(results));
  15655. });
  15656. };
  15657. };
  15658. async.compose = function (/* functions... */) {
  15659. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  15660. };
  15661. var _applyEach = function (eachfn, fns /*args...*/) {
  15662. var go = function () {
  15663. var that = this;
  15664. var args = Array.prototype.slice.call(arguments);
  15665. var callback = args.pop();
  15666. return eachfn(fns, function (fn, cb) {
  15667. fn.apply(that, args.concat([cb]));
  15668. },
  15669. callback);
  15670. };
  15671. if (arguments.length > 2) {
  15672. var args = Array.prototype.slice.call(arguments, 2);
  15673. return go.apply(this, args);
  15674. }
  15675. else {
  15676. return go;
  15677. }
  15678. };
  15679. async.applyEach = doParallel(_applyEach);
  15680. async.applyEachSeries = doSeries(_applyEach);
  15681. async.forever = function (fn, callback) {
  15682. function next(err) {
  15683. if (err) {
  15684. if (callback) {
  15685. return callback(err);
  15686. }
  15687. throw err;
  15688. }
  15689. fn(next);
  15690. }
  15691. next();
  15692. };
  15693. // Node.js
  15694. if (typeof module !== 'undefined' && module.exports) {
  15695. module.exports = async;
  15696. }
  15697. // AMD / RequireJS
  15698. else if (typeof define !== 'undefined' && define.amd) {
  15699. define([], function () {
  15700. return async;
  15701. });
  15702. }
  15703. // included directly via <script> tag
  15704. else {
  15705. root.async = async;
  15706. }
  15707. }());
  15708. }).call(this,require('_process'))
  15709. },{"_process":61}],61:[function(require,module,exports){
  15710. // shim for using process in browser
  15711. var process = module.exports = {};
  15712. var queue = [];
  15713. var draining = false;
  15714. function drainQueue() {
  15715. if (draining) {
  15716. return;
  15717. }
  15718. draining = true;
  15719. var currentQueue;
  15720. var len = queue.length;
  15721. while(len) {
  15722. currentQueue = queue;
  15723. queue = [];
  15724. var i = -1;
  15725. while (++i < len) {
  15726. currentQueue[i]();
  15727. }
  15728. len = queue.length;
  15729. }
  15730. draining = false;
  15731. }
  15732. process.nextTick = function (fun) {
  15733. queue.push(fun);
  15734. if (!draining) {
  15735. setTimeout(drainQueue, 0);
  15736. }
  15737. };
  15738. process.title = 'browser';
  15739. process.browser = true;
  15740. process.env = {};
  15741. process.argv = [];
  15742. process.version = ''; // empty string to avoid regexp issues
  15743. process.versions = {};
  15744. function noop() {}
  15745. process.on = noop;
  15746. process.addListener = noop;
  15747. process.once = noop;
  15748. process.off = noop;
  15749. process.removeListener = noop;
  15750. process.removeAllListeners = noop;
  15751. process.emit = noop;
  15752. process.binding = function (name) {
  15753. throw new Error('process.binding is not supported');
  15754. };
  15755. // TODO(shtylman)
  15756. process.cwd = function () { return '/' };
  15757. process.chdir = function (dir) {
  15758. throw new Error('process.chdir is not supported');
  15759. };
  15760. process.umask = function() { return 0; };
  15761. },{}],62:[function(require,module,exports){
  15762. // Copyright Joyent, Inc. and other Node contributors.
  15763. //
  15764. // Permission is hereby granted, free of charge, to any person obtaining a
  15765. // copy of this software and associated documentation files (the
  15766. // "Software"), to deal in the Software without restriction, including
  15767. // without limitation the rights to use, copy, modify, merge, publish,
  15768. // distribute, sublicense, and/or sell copies of the Software, and to permit
  15769. // persons to whom the Software is furnished to do so, subject to the
  15770. // following conditions:
  15771. //
  15772. // The above copyright notice and this permission notice shall be included
  15773. // in all copies or substantial portions of the Software.
  15774. //
  15775. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15776. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15777. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  15778. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  15779. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15780. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  15781. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  15782. function EventEmitter() {
  15783. this._events = this._events || {};
  15784. this._maxListeners = this._maxListeners || undefined;
  15785. }
  15786. module.exports = EventEmitter;
  15787. // Backwards-compat with node 0.10.x
  15788. EventEmitter.EventEmitter = EventEmitter;
  15789. EventEmitter.prototype._events = undefined;
  15790. EventEmitter.prototype._maxListeners = undefined;
  15791. // By default EventEmitters will print a warning if more than 10 listeners are
  15792. // added to it. This is a useful default which helps finding memory leaks.
  15793. EventEmitter.defaultMaxListeners = 10;
  15794. // Obviously not all Emitters should be limited to 10. This function allows
  15795. // that to be increased. Set to zero for unlimited.
  15796. EventEmitter.prototype.setMaxListeners = function(n) {
  15797. if (!isNumber(n) || n < 0 || isNaN(n))
  15798. throw TypeError('n must be a positive number');
  15799. this._maxListeners = n;
  15800. return this;
  15801. };
  15802. EventEmitter.prototype.emit = function(type) {
  15803. var er, handler, len, args, i, listeners;
  15804. if (!this._events)
  15805. this._events = {};
  15806. // If there is no 'error' event listener then throw.
  15807. if (type === 'error') {
  15808. if (!this._events.error ||
  15809. (isObject(this._events.error) && !this._events.error.length)) {
  15810. er = arguments[1];
  15811. if (er instanceof Error) {
  15812. throw er; // Unhandled 'error' event
  15813. }
  15814. throw TypeError('Uncaught, unspecified "error" event.');
  15815. }
  15816. }
  15817. handler = this._events[type];
  15818. if (isUndefined(handler))
  15819. return false;
  15820. if (isFunction(handler)) {
  15821. switch (arguments.length) {
  15822. // fast cases
  15823. case 1:
  15824. handler.call(this);
  15825. break;
  15826. case 2:
  15827. handler.call(this, arguments[1]);
  15828. break;
  15829. case 3:
  15830. handler.call(this, arguments[1], arguments[2]);
  15831. break;
  15832. // slower
  15833. default:
  15834. len = arguments.length;
  15835. args = new Array(len - 1);
  15836. for (i = 1; i < len; i++)
  15837. args[i - 1] = arguments[i];
  15838. handler.apply(this, args);
  15839. }
  15840. } else if (isObject(handler)) {
  15841. len = arguments.length;
  15842. args = new Array(len - 1);
  15843. for (i = 1; i < len; i++)
  15844. args[i - 1] = arguments[i];
  15845. listeners = handler.slice();
  15846. len = listeners.length;
  15847. for (i = 0; i < len; i++)
  15848. listeners[i].apply(this, args);
  15849. }
  15850. return true;
  15851. };
  15852. EventEmitter.prototype.addListener = function(type, listener) {
  15853. var m;
  15854. if (!isFunction(listener))
  15855. throw TypeError('listener must be a function');
  15856. if (!this._events)
  15857. this._events = {};
  15858. // To avoid recursion in the case that type === "newListener"! Before
  15859. // adding it to the listeners, first emit "newListener".
  15860. if (this._events.newListener)
  15861. this.emit('newListener', type,
  15862. isFunction(listener.listener) ?
  15863. listener.listener : listener);
  15864. if (!this._events[type])
  15865. // Optimize the case of one listener. Don't need the extra array object.
  15866. this._events[type] = listener;
  15867. else if (isObject(this._events[type]))
  15868. // If we've already got an array, just append.
  15869. this._events[type].push(listener);
  15870. else
  15871. // Adding the second element, need to change to array.
  15872. this._events[type] = [this._events[type], listener];
  15873. // Check for listener leak
  15874. if (isObject(this._events[type]) && !this._events[type].warned) {
  15875. var m;
  15876. if (!isUndefined(this._maxListeners)) {
  15877. m = this._maxListeners;
  15878. } else {
  15879. m = EventEmitter.defaultMaxListeners;
  15880. }
  15881. if (m && m > 0 && this._events[type].length > m) {
  15882. this._events[type].warned = true;
  15883. console.error('(node) warning: possible EventEmitter memory ' +
  15884. 'leak detected. %d listeners added. ' +
  15885. 'Use emitter.setMaxListeners() to increase limit.',
  15886. this._events[type].length);
  15887. if (typeof console.trace === 'function') {
  15888. // not supported in IE 10
  15889. console.trace();
  15890. }
  15891. }
  15892. }
  15893. return this;
  15894. };
  15895. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  15896. EventEmitter.prototype.once = function(type, listener) {
  15897. if (!isFunction(listener))
  15898. throw TypeError('listener must be a function');
  15899. var fired = false;
  15900. function g() {
  15901. this.removeListener(type, g);
  15902. if (!fired) {
  15903. fired = true;
  15904. listener.apply(this, arguments);
  15905. }
  15906. }
  15907. g.listener = listener;
  15908. this.on(type, g);
  15909. return this;
  15910. };
  15911. // emits a 'removeListener' event iff the listener was removed
  15912. EventEmitter.prototype.removeListener = function(type, listener) {
  15913. var list, position, length, i;
  15914. if (!isFunction(listener))
  15915. throw TypeError('listener must be a function');
  15916. if (!this._events || !this._events[type])
  15917. return this;
  15918. list = this._events[type];
  15919. length = list.length;
  15920. position = -1;
  15921. if (list === listener ||
  15922. (isFunction(list.listener) && list.listener === listener)) {
  15923. delete this._events[type];
  15924. if (this._events.removeListener)
  15925. this.emit('removeListener', type, listener);
  15926. } else if (isObject(list)) {
  15927. for (i = length; i-- > 0;) {
  15928. if (list[i] === listener ||
  15929. (list[i].listener && list[i].listener === listener)) {
  15930. position = i;
  15931. break;
  15932. }
  15933. }
  15934. if (position < 0)
  15935. return this;
  15936. if (list.length === 1) {
  15937. list.length = 0;
  15938. delete this._events[type];
  15939. } else {
  15940. list.splice(position, 1);
  15941. }
  15942. if (this._events.removeListener)
  15943. this.emit('removeListener', type, listener);
  15944. }
  15945. return this;
  15946. };
  15947. EventEmitter.prototype.removeAllListeners = function(type) {
  15948. var key, listeners;
  15949. if (!this._events)
  15950. return this;
  15951. // not listening for removeListener, no need to emit
  15952. if (!this._events.removeListener) {
  15953. if (arguments.length === 0)
  15954. this._events = {};
  15955. else if (this._events[type])
  15956. delete this._events[type];
  15957. return this;
  15958. }
  15959. // emit removeListener for all listeners on all events
  15960. if (arguments.length === 0) {
  15961. for (key in this._events) {
  15962. if (key === 'removeListener') continue;
  15963. this.removeAllListeners(key);
  15964. }
  15965. this.removeAllListeners('removeListener');
  15966. this._events = {};
  15967. return this;
  15968. }
  15969. listeners = this._events[type];
  15970. if (isFunction(listeners)) {
  15971. this.removeListener(type, listeners);
  15972. } else {
  15973. // LIFO order
  15974. while (listeners.length)
  15975. this.removeListener(type, listeners[listeners.length - 1]);
  15976. }
  15977. delete this._events[type];
  15978. return this;
  15979. };
  15980. EventEmitter.prototype.listeners = function(type) {
  15981. var ret;
  15982. if (!this._events || !this._events[type])
  15983. ret = [];
  15984. else if (isFunction(this._events[type]))
  15985. ret = [this._events[type]];
  15986. else
  15987. ret = this._events[type].slice();
  15988. return ret;
  15989. };
  15990. EventEmitter.listenerCount = function(emitter, type) {
  15991. var ret;
  15992. if (!emitter._events || !emitter._events[type])
  15993. ret = 0;
  15994. else if (isFunction(emitter._events[type]))
  15995. ret = 1;
  15996. else
  15997. ret = emitter._events[type].length;
  15998. return ret;
  15999. };
  16000. function isFunction(arg) {
  16001. return typeof arg === 'function';
  16002. }
  16003. function isNumber(arg) {
  16004. return typeof arg === 'number';
  16005. }
  16006. function isObject(arg) {
  16007. return typeof arg === 'object' && arg !== null;
  16008. }
  16009. function isUndefined(arg) {
  16010. return arg === void 0;
  16011. }
  16012. },{}],63:[function(require,module,exports){
  16013. // i18next, v1.7.7
  16014. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  16015. // Distributed under MIT license
  16016. // http://i18next.com
  16017. (function() {
  16018. // add indexOf to non ECMA-262 standard compliant browsers
  16019. if (!Array.prototype.indexOf) {
  16020. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  16021. "use strict";
  16022. if (this == null) {
  16023. throw new TypeError();
  16024. }
  16025. var t = Object(this);
  16026. var len = t.length >>> 0;
  16027. if (len === 0) {
  16028. return -1;
  16029. }
  16030. var n = 0;
  16031. if (arguments.length > 0) {
  16032. n = Number(arguments[1]);
  16033. if (n != n) { // shortcut for verifying if it's NaN
  16034. n = 0;
  16035. } else if (n != 0 && n != Infinity && n != -Infinity) {
  16036. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16037. }
  16038. }
  16039. if (n >= len) {
  16040. return -1;
  16041. }
  16042. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  16043. for (; k < len; k++) {
  16044. if (k in t && t[k] === searchElement) {
  16045. return k;
  16046. }
  16047. }
  16048. return -1;
  16049. }
  16050. }
  16051. // add lastIndexOf to non ECMA-262 standard compliant browsers
  16052. if (!Array.prototype.lastIndexOf) {
  16053. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  16054. "use strict";
  16055. if (this == null) {
  16056. throw new TypeError();
  16057. }
  16058. var t = Object(this);
  16059. var len = t.length >>> 0;
  16060. if (len === 0) {
  16061. return -1;
  16062. }
  16063. var n = len;
  16064. if (arguments.length > 1) {
  16065. n = Number(arguments[1]);
  16066. if (n != n) {
  16067. n = 0;
  16068. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  16069. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16070. }
  16071. }
  16072. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  16073. for (; k >= 0; k--) {
  16074. if (k in t && t[k] === searchElement) {
  16075. return k;
  16076. }
  16077. }
  16078. return -1;
  16079. };
  16080. }
  16081. // Add string trim for IE8.
  16082. if (typeof String.prototype.trim !== 'function') {
  16083. String.prototype.trim = function() {
  16084. return this.replace(/^\s+|\s+$/g, '');
  16085. }
  16086. }
  16087. var root = this
  16088. , $ = root.jQuery || root.Zepto
  16089. , i18n = {}
  16090. , resStore = {}
  16091. , currentLng
  16092. , replacementCounter = 0
  16093. , languages = []
  16094. , initialized = false
  16095. , sync = {};
  16096. // Export the i18next object for **CommonJS**.
  16097. // If we're not in CommonJS, add `i18n` to the
  16098. // global object or to jquery.
  16099. if (typeof module !== 'undefined' && module.exports) {
  16100. if (!$) {
  16101. try {
  16102. $ = require('jquery');
  16103. } catch(e) {
  16104. // just ignore
  16105. }
  16106. }
  16107. if ($) {
  16108. $.i18n = $.i18n || i18n;
  16109. }
  16110. module.exports = i18n;
  16111. } else {
  16112. if ($) {
  16113. $.i18n = $.i18n || i18n;
  16114. }
  16115. root.i18n = root.i18n || i18n;
  16116. }
  16117. sync = {
  16118. load: function(lngs, options, cb) {
  16119. if (options.useLocalStorage) {
  16120. sync._loadLocal(lngs, options, function(err, store) {
  16121. var missingLngs = [];
  16122. for (var i = 0, len = lngs.length; i < len; i++) {
  16123. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  16124. }
  16125. if (missingLngs.length > 0) {
  16126. sync._fetch(missingLngs, options, function(err, fetched) {
  16127. f.extend(store, fetched);
  16128. sync._storeLocal(fetched);
  16129. cb(null, store);
  16130. });
  16131. } else {
  16132. cb(null, store);
  16133. }
  16134. });
  16135. } else {
  16136. sync._fetch(lngs, options, function(err, store){
  16137. cb(null, store);
  16138. });
  16139. }
  16140. },
  16141. _loadLocal: function(lngs, options, cb) {
  16142. var store = {}
  16143. , nowMS = new Date().getTime();
  16144. if(window.localStorage) {
  16145. var todo = lngs.length;
  16146. f.each(lngs, function(key, lng) {
  16147. var local = window.localStorage.getItem('res_' + lng);
  16148. if (local) {
  16149. local = JSON.parse(local);
  16150. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  16151. store[lng] = local;
  16152. }
  16153. }
  16154. todo--; // wait for all done befor callback
  16155. if (todo === 0) cb(null, store);
  16156. });
  16157. }
  16158. },
  16159. _storeLocal: function(store) {
  16160. if(window.localStorage) {
  16161. for (var m in store) {
  16162. store[m].i18nStamp = new Date().getTime();
  16163. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  16164. }
  16165. }
  16166. return;
  16167. },
  16168. _fetch: function(lngs, options, cb) {
  16169. var ns = options.ns
  16170. , store = {};
  16171. if (!options.dynamicLoad) {
  16172. var todo = ns.namespaces.length * lngs.length
  16173. , errors;
  16174. // load each file individual
  16175. f.each(ns.namespaces, function(nsIndex, nsValue) {
  16176. f.each(lngs, function(lngIndex, lngValue) {
  16177. // Call this once our translation has returned.
  16178. var loadComplete = function(err, data) {
  16179. if (err) {
  16180. errors = errors || [];
  16181. errors.push(err);
  16182. }
  16183. store[lngValue] = store[lngValue] || {};
  16184. store[lngValue][nsValue] = data;
  16185. todo--; // wait for all done befor callback
  16186. if (todo === 0) cb(errors, store);
  16187. };
  16188. if(typeof options.customLoad == 'function'){
  16189. // Use the specified custom callback.
  16190. options.customLoad(lngValue, nsValue, options, loadComplete);
  16191. } else {
  16192. //~ // Use our inbuilt sync.
  16193. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  16194. }
  16195. });
  16196. });
  16197. } else {
  16198. // Call this once our translation has returned.
  16199. var loadComplete = function(err, data) {
  16200. cb(null, data);
  16201. };
  16202. if(typeof options.customLoad == 'function'){
  16203. // Use the specified custom callback.
  16204. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  16205. } else {
  16206. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  16207. // load all needed stuff once
  16208. f.ajax({
  16209. url: url,
  16210. success: function(data, status, xhr) {
  16211. f.log('loaded: ' + url);
  16212. loadComplete(null, data);
  16213. },
  16214. error : function(xhr, status, error) {
  16215. f.log('failed loading: ' + url);
  16216. loadComplete('failed loading resource.json error: ' + error);
  16217. },
  16218. dataType: "json",
  16219. async : options.getAsync
  16220. });
  16221. }
  16222. }
  16223. },
  16224. _fetchOne: function(lng, ns, options, done) {
  16225. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  16226. f.ajax({
  16227. url: url,
  16228. success: function(data, status, xhr) {
  16229. f.log('loaded: ' + url);
  16230. done(null, data);
  16231. },
  16232. error : function(xhr, status, error) {
  16233. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  16234. // file loaded but invalid json, stop waste time !
  16235. f.error('There is a typo in: ' + url);
  16236. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  16237. f.log('Does not exist: ' + url);
  16238. } else {
  16239. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  16240. f.log(theStatus + ' when loading ' + url);
  16241. }
  16242. done(error, {});
  16243. },
  16244. dataType: "json",
  16245. async : options.getAsync
  16246. });
  16247. },
  16248. postMissing: function(lng, ns, key, defaultValue, lngs) {
  16249. var payload = {};
  16250. payload[key] = defaultValue;
  16251. var urls = [];
  16252. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  16253. for (var i = 0; i < o.fallbackLng.length; i++) {
  16254. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  16255. }
  16256. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  16257. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  16258. } else if (o.sendMissingTo === 'all') {
  16259. for (var i = 0, l = lngs.length; i < l; i++) {
  16260. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  16261. }
  16262. }
  16263. for (var y = 0, len = urls.length; y < len; y++) {
  16264. var item = urls[y];
  16265. f.ajax({
  16266. url: item.url,
  16267. type: o.sendType,
  16268. data: payload,
  16269. success: function(data, status, xhr) {
  16270. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  16271. // add key to resStore
  16272. var keys = key.split('.');
  16273. var x = 0;
  16274. var value = resStore[item.lng][ns];
  16275. while (keys[x]) {
  16276. if (x === keys.length - 1) {
  16277. value = value[keys[x]] = defaultValue;
  16278. } else {
  16279. value = value[keys[x]] = value[keys[x]] || {};
  16280. }
  16281. x++;
  16282. }
  16283. },
  16284. error : function(xhr, status, error) {
  16285. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  16286. },
  16287. dataType: "json",
  16288. async : o.postAsync
  16289. });
  16290. }
  16291. },
  16292. reload: reload
  16293. };
  16294. // defaults
  16295. var o = {
  16296. lng: undefined,
  16297. load: 'all',
  16298. preload: [],
  16299. lowerCaseLng: false,
  16300. returnObjectTrees: false,
  16301. fallbackLng: ['dev'],
  16302. fallbackNS: [],
  16303. detectLngQS: 'setLng',
  16304. detectLngFromLocalStorage: false,
  16305. ns: 'translation',
  16306. fallbackOnNull: true,
  16307. fallbackOnEmpty: false,
  16308. fallbackToDefaultNS: false,
  16309. nsseparator: ':',
  16310. keyseparator: '.',
  16311. selectorAttr: 'data-i18n',
  16312. debug: false,
  16313. resGetPath: 'locales/__lng__/__ns__.json',
  16314. resPostPath: 'locales/add/__lng__/__ns__',
  16315. getAsync: true,
  16316. postAsync: true,
  16317. resStore: undefined,
  16318. useLocalStorage: false,
  16319. localStorageExpirationTime: 7*24*60*60*1000,
  16320. dynamicLoad: false,
  16321. sendMissing: false,
  16322. sendMissingTo: 'fallback', // current | all
  16323. sendType: 'POST',
  16324. interpolationPrefix: '__',
  16325. interpolationSuffix: '__',
  16326. defaultVariables: false,
  16327. reusePrefix: '$t(',
  16328. reuseSuffix: ')',
  16329. pluralSuffix: '_plural',
  16330. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  16331. contextNotFound: ['context_not_found', Math.random()].join(''),
  16332. escapeInterpolation: false,
  16333. indefiniteSuffix: '_indefinite',
  16334. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  16335. setJqueryExt: true,
  16336. defaultValueFromContent: true,
  16337. useDataAttrOptions: false,
  16338. cookieExpirationTime: undefined,
  16339. useCookie: true,
  16340. cookieName: 'i18next',
  16341. cookieDomain: undefined,
  16342. objectTreeKeyHandler: undefined,
  16343. postProcess: undefined,
  16344. parseMissingKey: undefined,
  16345. missingKeyHandler: sync.postMissing,
  16346. shortcutFunction: 'sprintf' // or: defaultValue
  16347. };
  16348. function _extend(target, source) {
  16349. if (!source || typeof source === 'function') {
  16350. return target;
  16351. }
  16352. for (var attr in source) { target[attr] = source[attr]; }
  16353. return target;
  16354. }
  16355. function _deepExtend(target, source) {
  16356. for (var prop in source)
  16357. if (prop in target)
  16358. _deepExtend(target[prop], source[prop]);
  16359. else
  16360. target[prop] = source[prop];
  16361. return target;
  16362. }
  16363. function _each(object, callback, args) {
  16364. var name, i = 0,
  16365. length = object.length,
  16366. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  16367. if (args) {
  16368. if (isObj) {
  16369. for (name in object) {
  16370. if (callback.apply(object[name], args) === false) {
  16371. break;
  16372. }
  16373. }
  16374. } else {
  16375. for ( ; i < length; ) {
  16376. if (callback.apply(object[i++], args) === false) {
  16377. break;
  16378. }
  16379. }
  16380. }
  16381. // A special, fast, case for the most common use of each
  16382. } else {
  16383. if (isObj) {
  16384. for (name in object) {
  16385. if (callback.call(object[name], name, object[name]) === false) {
  16386. break;
  16387. }
  16388. }
  16389. } else {
  16390. for ( ; i < length; ) {
  16391. if (callback.call(object[i], i, object[i++]) === false) {
  16392. break;
  16393. }
  16394. }
  16395. }
  16396. }
  16397. return object;
  16398. }
  16399. var _entityMap = {
  16400. "&": "&amp;",
  16401. "<": "&lt;",
  16402. ">": "&gt;",
  16403. '"': '&quot;',
  16404. "'": '&#39;',
  16405. "/": '&#x2F;'
  16406. };
  16407. function _escape(data) {
  16408. if (typeof data === 'string') {
  16409. return data.replace(/[&<>"'\/]/g, function (s) {
  16410. return _entityMap[s];
  16411. });
  16412. }else{
  16413. return data;
  16414. }
  16415. }
  16416. function _ajax(options) {
  16417. // v0.5.0 of https://github.com/goloroden/http.js
  16418. var getXhr = function (callback) {
  16419. // Use the native XHR object if the browser supports it.
  16420. if (window.XMLHttpRequest) {
  16421. return callback(null, new XMLHttpRequest());
  16422. } else if (window.ActiveXObject) {
  16423. // In Internet Explorer check for ActiveX versions of the XHR object.
  16424. try {
  16425. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  16426. } catch (e) {
  16427. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  16428. }
  16429. }
  16430. // If no XHR support was found, throw an error.
  16431. return callback(new Error());
  16432. };
  16433. var encodeUsingUrlEncoding = function (data) {
  16434. if(typeof data === 'string') {
  16435. return data;
  16436. }
  16437. var result = [];
  16438. for(var dataItem in data) {
  16439. if(data.hasOwnProperty(dataItem)) {
  16440. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  16441. }
  16442. }
  16443. return result.join('&');
  16444. };
  16445. var utf8 = function (text) {
  16446. text = text.replace(/\r\n/g, '\n');
  16447. var result = '';
  16448. for(var i = 0; i < text.length; i++) {
  16449. var c = text.charCodeAt(i);
  16450. if(c < 128) {
  16451. result += String.fromCharCode(c);
  16452. } else if((c > 127) && (c < 2048)) {
  16453. result += String.fromCharCode((c >> 6) | 192);
  16454. result += String.fromCharCode((c & 63) | 128);
  16455. } else {
  16456. result += String.fromCharCode((c >> 12) | 224);
  16457. result += String.fromCharCode(((c >> 6) & 63) | 128);
  16458. result += String.fromCharCode((c & 63) | 128);
  16459. }
  16460. }
  16461. return result;
  16462. };
  16463. var base64 = function (text) {
  16464. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  16465. text = utf8(text);
  16466. var result = '',
  16467. chr1, chr2, chr3,
  16468. enc1, enc2, enc3, enc4,
  16469. i = 0;
  16470. do {
  16471. chr1 = text.charCodeAt(i++);
  16472. chr2 = text.charCodeAt(i++);
  16473. chr3 = text.charCodeAt(i++);
  16474. enc1 = chr1 >> 2;
  16475. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  16476. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  16477. enc4 = chr3 & 63;
  16478. if(isNaN(chr2)) {
  16479. enc3 = enc4 = 64;
  16480. } else if(isNaN(chr3)) {
  16481. enc4 = 64;
  16482. }
  16483. result +=
  16484. keyStr.charAt(enc1) +
  16485. keyStr.charAt(enc2) +
  16486. keyStr.charAt(enc3) +
  16487. keyStr.charAt(enc4);
  16488. chr1 = chr2 = chr3 = '';
  16489. enc1 = enc2 = enc3 = enc4 = '';
  16490. } while(i < text.length);
  16491. return result;
  16492. };
  16493. var mergeHeaders = function () {
  16494. // Use the first header object as base.
  16495. var result = arguments[0];
  16496. // Iterate through the remaining header objects and add them.
  16497. for(var i = 1; i < arguments.length; i++) {
  16498. var currentHeaders = arguments[i];
  16499. for(var header in currentHeaders) {
  16500. if(currentHeaders.hasOwnProperty(header)) {
  16501. result[header] = currentHeaders[header];
  16502. }
  16503. }
  16504. }
  16505. // Return the merged headers.
  16506. return result;
  16507. };
  16508. var ajax = function (method, url, options, callback) {
  16509. // Adjust parameters.
  16510. if(typeof options === 'function') {
  16511. callback = options;
  16512. options = {};
  16513. }
  16514. // Set default parameter values.
  16515. options.cache = options.cache || false;
  16516. options.data = options.data || {};
  16517. options.headers = options.headers || {};
  16518. options.jsonp = options.jsonp || false;
  16519. options.async = options.async === undefined ? true : options.async;
  16520. // Merge the various header objects.
  16521. var headers = mergeHeaders({
  16522. 'accept': '*/*',
  16523. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  16524. }, ajax.headers, options.headers);
  16525. // Encode the data according to the content-type.
  16526. var payload;
  16527. if (headers['content-type'] === 'application/json') {
  16528. payload = JSON.stringify(options.data);
  16529. } else {
  16530. payload = encodeUsingUrlEncoding(options.data);
  16531. }
  16532. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  16533. // if neccessary.
  16534. if(method === 'GET') {
  16535. // Setup the query string.
  16536. var queryString = [];
  16537. if(payload) {
  16538. queryString.push(payload);
  16539. payload = null;
  16540. }
  16541. // Handle caching.
  16542. if(!options.cache) {
  16543. queryString.push('_=' + (new Date()).getTime());
  16544. }
  16545. // If neccessary prepare the query string for a JSONP call.
  16546. if(options.jsonp) {
  16547. queryString.push('callback=' + options.jsonp);
  16548. queryString.push('jsonp=' + options.jsonp);
  16549. }
  16550. // Merge the query string and attach it to the url.
  16551. queryString = queryString.join('&');
  16552. if (queryString.length > 1) {
  16553. if (url.indexOf('?') > -1) {
  16554. url += '&' + queryString;
  16555. } else {
  16556. url += '?' + queryString;
  16557. }
  16558. }
  16559. // Make a JSONP call if neccessary.
  16560. if(options.jsonp) {
  16561. var head = document.getElementsByTagName('head')[0];
  16562. var script = document.createElement('script');
  16563. script.type = 'text/javascript';
  16564. script.src = url;
  16565. head.appendChild(script);
  16566. return;
  16567. }
  16568. }
  16569. // Since we got here, it is no JSONP request, so make a normal XHR request.
  16570. getXhr(function (err, xhr) {
  16571. if(err) return callback(err);
  16572. // Open the request.
  16573. xhr.open(method, url, options.async);
  16574. // Set the request headers.
  16575. for(var header in headers) {
  16576. if(headers.hasOwnProperty(header)) {
  16577. xhr.setRequestHeader(header, headers[header]);
  16578. }
  16579. }
  16580. // Handle the request events.
  16581. xhr.onreadystatechange = function () {
  16582. if(xhr.readyState === 4) {
  16583. var data = xhr.responseText || '';
  16584. // If no callback is given, return.
  16585. if(!callback) {
  16586. return;
  16587. }
  16588. // Return an object that provides access to the data as text and JSON.
  16589. callback(xhr.status, {
  16590. text: function () {
  16591. return data;
  16592. },
  16593. json: function () {
  16594. try {
  16595. return JSON.parse(data)
  16596. } catch (e) {
  16597. f.error('Can not parse JSON. URL: ' + url);
  16598. return {};
  16599. }
  16600. }
  16601. });
  16602. }
  16603. };
  16604. // Actually send the XHR request.
  16605. xhr.send(payload);
  16606. });
  16607. };
  16608. // Define the external interface.
  16609. var http = {
  16610. authBasic: function (username, password) {
  16611. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  16612. },
  16613. connect: function (url, options, callback) {
  16614. return ajax('CONNECT', url, options, callback);
  16615. },
  16616. del: function (url, options, callback) {
  16617. return ajax('DELETE', url, options, callback);
  16618. },
  16619. get: function (url, options, callback) {
  16620. return ajax('GET', url, options, callback);
  16621. },
  16622. head: function (url, options, callback) {
  16623. return ajax('HEAD', url, options, callback);
  16624. },
  16625. headers: function (headers) {
  16626. ajax.headers = headers || {};
  16627. },
  16628. isAllowed: function (url, verb, callback) {
  16629. this.options(url, function (status, data) {
  16630. callback(data.text().indexOf(verb) !== -1);
  16631. });
  16632. },
  16633. options: function (url, options, callback) {
  16634. return ajax('OPTIONS', url, options, callback);
  16635. },
  16636. patch: function (url, options, callback) {
  16637. return ajax('PATCH', url, options, callback);
  16638. },
  16639. post: function (url, options, callback) {
  16640. return ajax('POST', url, options, callback);
  16641. },
  16642. put: function (url, options, callback) {
  16643. return ajax('PUT', url, options, callback);
  16644. },
  16645. trace: function (url, options, callback) {
  16646. return ajax('TRACE', url, options, callback);
  16647. }
  16648. };
  16649. var methode = options.type ? options.type.toLowerCase() : 'get';
  16650. http[methode](options.url, options, function (status, data) {
  16651. // file: protocol always gives status code 0, so check for data
  16652. if (status === 200 || (status === 0 && data.text())) {
  16653. options.success(data.json(), status, null);
  16654. } else {
  16655. options.error(data.text(), status, null);
  16656. }
  16657. });
  16658. }
  16659. var _cookie = {
  16660. create: function(name,value,minutes,domain) {
  16661. var expires;
  16662. if (minutes) {
  16663. var date = new Date();
  16664. date.setTime(date.getTime()+(minutes*60*1000));
  16665. expires = "; expires="+date.toGMTString();
  16666. }
  16667. else expires = "";
  16668. domain = (domain)? "domain="+domain+";" : "";
  16669. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  16670. },
  16671. read: function(name) {
  16672. var nameEQ = name + "=";
  16673. var ca = document.cookie.split(';');
  16674. for(var i=0;i < ca.length;i++) {
  16675. var c = ca[i];
  16676. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  16677. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  16678. }
  16679. return null;
  16680. },
  16681. remove: function(name) {
  16682. this.create(name,"",-1);
  16683. }
  16684. };
  16685. var cookie_noop = {
  16686. create: function(name,value,minutes,domain) {},
  16687. read: function(name) { return null; },
  16688. remove: function(name) {}
  16689. };
  16690. // move dependent functions to a container so that
  16691. // they can be overriden easier in no jquery environment (node.js)
  16692. var f = {
  16693. extend: $ ? $.extend : _extend,
  16694. deepExtend: _deepExtend,
  16695. each: $ ? $.each : _each,
  16696. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  16697. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  16698. detectLanguage: detectLanguage,
  16699. escape: _escape,
  16700. log: function(str) {
  16701. if (o.debug && typeof console !== "undefined") console.log(str);
  16702. },
  16703. error: function(str) {
  16704. if (typeof console !== "undefined") console.error(str);
  16705. },
  16706. getCountyIndexOfLng: function(lng) {
  16707. var lng_index = 0;
  16708. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  16709. return lng_index;
  16710. },
  16711. toLanguages: function(lng) {
  16712. var log = this.log;
  16713. function applyCase(l) {
  16714. var ret = l;
  16715. if (typeof l === 'string' && l.indexOf('-') > -1) {
  16716. var parts = l.split('-');
  16717. ret = o.lowerCaseLng ?
  16718. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16719. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16720. } else {
  16721. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  16722. }
  16723. return ret;
  16724. }
  16725. var languages = [];
  16726. var whitelist = o.lngWhitelist || false;
  16727. var addLanguage = function(language){
  16728. //reject langs not whitelisted
  16729. if(!whitelist || whitelist.indexOf(language) > -1){
  16730. languages.push(language);
  16731. }else{
  16732. log('rejecting non-whitelisted language: ' + language);
  16733. }
  16734. };
  16735. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  16736. var parts = lng.split('-');
  16737. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  16738. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  16739. } else {
  16740. addLanguage(applyCase(lng));
  16741. }
  16742. for (var i = 0; i < o.fallbackLng.length; i++) {
  16743. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  16744. }
  16745. return languages;
  16746. },
  16747. regexEscape: function(str) {
  16748. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  16749. },
  16750. regexReplacementEscape: function(strOrFn) {
  16751. if (typeof strOrFn === 'string') {
  16752. return strOrFn.replace(/\$/g, "$$$$");
  16753. } else {
  16754. return strOrFn;
  16755. }
  16756. },
  16757. localStorage: {
  16758. setItem: function(key, value) {
  16759. if (window.localStorage) {
  16760. try {
  16761. window.localStorage.setItem(key, value);
  16762. } catch (e) {
  16763. f.log('failed to set value for key "' + key + '" to localStorage.');
  16764. }
  16765. }
  16766. }
  16767. }
  16768. };
  16769. function init(options, cb) {
  16770. if (typeof options === 'function') {
  16771. cb = options;
  16772. options = {};
  16773. }
  16774. options = options || {};
  16775. // override defaults with passed in options
  16776. f.extend(o, options);
  16777. delete o.fixLng; /* passed in each time */
  16778. // override functions: .log(), .detectLanguage(), etc
  16779. if (o.functions) {
  16780. delete o.functions;
  16781. f.extend(f, options.functions);
  16782. }
  16783. // create namespace object if namespace is passed in as string
  16784. if (typeof o.ns == 'string') {
  16785. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  16786. }
  16787. // fallback namespaces
  16788. if (typeof o.fallbackNS == 'string') {
  16789. o.fallbackNS = [o.fallbackNS];
  16790. }
  16791. // fallback languages
  16792. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  16793. o.fallbackLng = [o.fallbackLng];
  16794. }
  16795. // escape prefix/suffix
  16796. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  16797. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  16798. if (!o.lng) o.lng = f.detectLanguage();
  16799. languages = f.toLanguages(o.lng);
  16800. currentLng = languages[0];
  16801. f.log('currentLng set to: ' + currentLng);
  16802. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  16803. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  16804. }
  16805. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  16806. f.localStorage.setItem('i18next_lng', currentLng);
  16807. }
  16808. var lngTranslate = translate;
  16809. if (options.fixLng) {
  16810. lngTranslate = function(key, options) {
  16811. options = options || {};
  16812. options.lng = options.lng || lngTranslate.lng;
  16813. return translate(key, options);
  16814. };
  16815. lngTranslate.lng = currentLng;
  16816. }
  16817. pluralExtensions.setCurrentLng(currentLng);
  16818. // add JQuery extensions
  16819. if ($ && o.setJqueryExt) addJqueryFunct();
  16820. // jQuery deferred
  16821. var deferred;
  16822. if ($ && $.Deferred) {
  16823. deferred = $.Deferred();
  16824. }
  16825. // return immidiatly if res are passed in
  16826. if (o.resStore) {
  16827. resStore = o.resStore;
  16828. initialized = true;
  16829. if (cb) cb(lngTranslate);
  16830. if (deferred) deferred.resolve(lngTranslate);
  16831. if (deferred) return deferred.promise();
  16832. return;
  16833. }
  16834. // languages to load
  16835. var lngsToLoad = f.toLanguages(o.lng);
  16836. if (typeof o.preload === 'string') o.preload = [o.preload];
  16837. for (var i = 0, l = o.preload.length; i < l; i++) {
  16838. var pres = f.toLanguages(o.preload[i]);
  16839. for (var y = 0, len = pres.length; y < len; y++) {
  16840. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16841. lngsToLoad.push(pres[y]);
  16842. }
  16843. }
  16844. }
  16845. // else load them
  16846. i18n.sync.load(lngsToLoad, o, function(err, store) {
  16847. resStore = store;
  16848. initialized = true;
  16849. if (cb) cb(lngTranslate);
  16850. if (deferred) deferred.resolve(lngTranslate);
  16851. });
  16852. if (deferred) return deferred.promise();
  16853. }
  16854. function preload(lngs, cb) {
  16855. if (typeof lngs === 'string') lngs = [lngs];
  16856. for (var i = 0, l = lngs.length; i < l; i++) {
  16857. if (o.preload.indexOf(lngs[i]) < 0) {
  16858. o.preload.push(lngs[i]);
  16859. }
  16860. }
  16861. return init(cb);
  16862. }
  16863. function addResourceBundle(lng, ns, resources, deep) {
  16864. if (typeof ns !== 'string') {
  16865. resources = ns;
  16866. ns = o.ns.defaultNs;
  16867. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16868. o.ns.namespaces.push(ns);
  16869. }
  16870. resStore[lng] = resStore[lng] || {};
  16871. resStore[lng][ns] = resStore[lng][ns] || {};
  16872. if (deep) {
  16873. f.deepExtend(resStore[lng][ns], resources);
  16874. } else {
  16875. f.extend(resStore[lng][ns], resources);
  16876. }
  16877. }
  16878. function hasResourceBundle(lng, ns) {
  16879. if (typeof ns !== 'string') {
  16880. ns = o.ns.defaultNs;
  16881. }
  16882. resStore[lng] = resStore[lng] || {};
  16883. var res = resStore[lng][ns] || {};
  16884. var hasValues = false;
  16885. for(var prop in res) {
  16886. if (res.hasOwnProperty(prop)) {
  16887. hasValues = true;
  16888. }
  16889. }
  16890. return hasValues;
  16891. }
  16892. function removeResourceBundle(lng, ns) {
  16893. if (typeof ns !== 'string') {
  16894. ns = o.ns.defaultNs;
  16895. }
  16896. resStore[lng] = resStore[lng] || {};
  16897. resStore[lng][ns] = {};
  16898. }
  16899. function addResource(lng, ns, key, value) {
  16900. if (typeof ns !== 'string') {
  16901. resource = ns;
  16902. ns = o.ns.defaultNs;
  16903. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16904. o.ns.namespaces.push(ns);
  16905. }
  16906. resStore[lng] = resStore[lng] || {};
  16907. resStore[lng][ns] = resStore[lng][ns] || {};
  16908. var keys = key.split(o.keyseparator);
  16909. var x = 0;
  16910. var node = resStore[lng][ns];
  16911. var origRef = node;
  16912. while (keys[x]) {
  16913. if (x == keys.length - 1)
  16914. node[keys[x]] = value;
  16915. else {
  16916. if (node[keys[x]] == null)
  16917. node[keys[x]] = {};
  16918. node = node[keys[x]];
  16919. }
  16920. x++;
  16921. }
  16922. }
  16923. function addResources(lng, ns, resources) {
  16924. if (typeof ns !== 'string') {
  16925. resource = ns;
  16926. ns = o.ns.defaultNs;
  16927. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16928. o.ns.namespaces.push(ns);
  16929. }
  16930. for (var m in resources) {
  16931. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  16932. }
  16933. }
  16934. function setDefaultNamespace(ns) {
  16935. o.ns.defaultNs = ns;
  16936. }
  16937. function loadNamespace(namespace, cb) {
  16938. loadNamespaces([namespace], cb);
  16939. }
  16940. function loadNamespaces(namespaces, cb) {
  16941. var opts = {
  16942. dynamicLoad: o.dynamicLoad,
  16943. resGetPath: o.resGetPath,
  16944. getAsync: o.getAsync,
  16945. customLoad: o.customLoad,
  16946. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  16947. };
  16948. // languages to load
  16949. var lngsToLoad = f.toLanguages(o.lng);
  16950. if (typeof o.preload === 'string') o.preload = [o.preload];
  16951. for (var i = 0, l = o.preload.length; i < l; i++) {
  16952. var pres = f.toLanguages(o.preload[i]);
  16953. for (var y = 0, len = pres.length; y < len; y++) {
  16954. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16955. lngsToLoad.push(pres[y]);
  16956. }
  16957. }
  16958. }
  16959. // check if we have to load
  16960. var lngNeedLoad = [];
  16961. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  16962. var needLoad = false;
  16963. var resSet = resStore[lngsToLoad[a]];
  16964. if (resSet) {
  16965. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  16966. if (!resSet[namespaces[b]]) needLoad = true;
  16967. }
  16968. } else {
  16969. needLoad = true;
  16970. }
  16971. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  16972. }
  16973. if (lngNeedLoad.length) {
  16974. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  16975. var todo = namespaces.length * lngNeedLoad.length;
  16976. // load each file individual
  16977. f.each(namespaces, function(nsIndex, nsValue) {
  16978. // append namespace to namespace array
  16979. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  16980. o.ns.namespaces.push(nsValue);
  16981. }
  16982. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  16983. resStore[lngValue] = resStore[lngValue] || {};
  16984. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  16985. todo--; // wait for all done befor callback
  16986. if (todo === 0 && cb) {
  16987. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  16988. cb();
  16989. }
  16990. });
  16991. });
  16992. });
  16993. } else {
  16994. if (cb) cb();
  16995. }
  16996. }
  16997. function setLng(lng, options, cb) {
  16998. if (typeof options === 'function') {
  16999. cb = options;
  17000. options = {};
  17001. } else if (!options) {
  17002. options = {};
  17003. }
  17004. options.lng = lng;
  17005. return init(options, cb);
  17006. }
  17007. function lng() {
  17008. return currentLng;
  17009. }
  17010. function reload(cb) {
  17011. resStore = {};
  17012. setLng(currentLng, cb);
  17013. }
  17014. function addJqueryFunct() {
  17015. // $.t shortcut
  17016. $.t = $.t || translate;
  17017. function parse(ele, key, options) {
  17018. if (key.length === 0) return;
  17019. var attr = 'text';
  17020. if (key.indexOf('[') === 0) {
  17021. var parts = key.split(']');
  17022. key = parts[1];
  17023. attr = parts[0].substr(1, parts[0].length-1);
  17024. }
  17025. if (key.indexOf(';') === key.length-1) {
  17026. key = key.substr(0, key.length-2);
  17027. }
  17028. var optionsToUse;
  17029. if (attr === 'html') {
  17030. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17031. ele.html($.t(key, optionsToUse));
  17032. } else if (attr === 'text') {
  17033. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  17034. ele.text($.t(key, optionsToUse));
  17035. } else if (attr === 'prepend') {
  17036. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17037. ele.prepend($.t(key, optionsToUse));
  17038. } else if (attr === 'append') {
  17039. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17040. ele.append($.t(key, optionsToUse));
  17041. } else if (attr.indexOf("data-") === 0) {
  17042. var dataAttr = attr.substr(("data-").length);
  17043. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  17044. var translated = $.t(key, optionsToUse);
  17045. //we change into the data cache
  17046. ele.data(dataAttr, translated);
  17047. //we change into the dom
  17048. ele.attr(attr, translated);
  17049. } else {
  17050. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  17051. ele.attr(attr, $.t(key, optionsToUse));
  17052. }
  17053. }
  17054. function localize(ele, options) {
  17055. var key = ele.attr(o.selectorAttr);
  17056. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  17057. if (!key) return;
  17058. var target = ele
  17059. , targetSelector = ele.data("i18n-target");
  17060. if (targetSelector) {
  17061. target = ele.find(targetSelector) || ele;
  17062. }
  17063. if (!options && o.useDataAttrOptions === true) {
  17064. options = ele.data("i18n-options");
  17065. }
  17066. options = options || {};
  17067. if (key.indexOf(';') >= 0) {
  17068. var keys = key.split(';');
  17069. $.each(keys, function(m, k) {
  17070. if (k !== '') parse(target, k, options);
  17071. });
  17072. } else {
  17073. parse(target, key, options);
  17074. }
  17075. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  17076. }
  17077. // fn
  17078. $.fn.i18n = function (options) {
  17079. return this.each(function() {
  17080. // localize element itself
  17081. localize($(this), options);
  17082. // localize childs
  17083. var elements = $(this).find('[' + o.selectorAttr + ']');
  17084. elements.each(function() {
  17085. localize($(this), options);
  17086. });
  17087. });
  17088. };
  17089. }
  17090. function applyReplacement(str, replacementHash, nestedKey, options) {
  17091. if (!str) return str;
  17092. options = options || replacementHash; // first call uses replacement hash combined with options
  17093. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  17094. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  17095. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  17096. , unEscapingSuffix = 'HTML'+suffix;
  17097. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  17098. f.each(hash, function(key, value) {
  17099. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  17100. if (typeof value === 'object' && value !== null) {
  17101. str = applyReplacement(str, value, nextKey, options);
  17102. } else {
  17103. if (options.escapeInterpolation || o.escapeInterpolation) {
  17104. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  17105. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  17106. } else {
  17107. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  17108. }
  17109. // str = options.escapeInterpolation;
  17110. }
  17111. });
  17112. return str;
  17113. }
  17114. // append it to functions
  17115. f.applyReplacement = applyReplacement;
  17116. function applyReuse(translated, options) {
  17117. var comma = ',';
  17118. var options_open = '{';
  17119. var options_close = '}';
  17120. var opts = f.extend({}, options);
  17121. delete opts.postProcess;
  17122. while (translated.indexOf(o.reusePrefix) != -1) {
  17123. replacementCounter++;
  17124. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  17125. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  17126. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  17127. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  17128. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  17129. if (index_of_end_of_closing <= index_of_opening) {
  17130. f.error('there is an missing closing in following translation value', translated);
  17131. return '';
  17132. }
  17133. if (token_without_symbols.indexOf(comma) != -1) {
  17134. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  17135. 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) {
  17136. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  17137. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  17138. try {
  17139. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  17140. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  17141. } catch (e) {
  17142. }
  17143. }
  17144. }
  17145. var translated_token = _translate(token_without_symbols, opts);
  17146. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  17147. }
  17148. return translated;
  17149. }
  17150. function hasContext(options) {
  17151. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  17152. }
  17153. function needsPlural(options, lng) {
  17154. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  17155. }
  17156. function needsIndefiniteArticle(options) {
  17157. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  17158. }
  17159. function exists(key, options) {
  17160. options = options || {};
  17161. var notFound = _getDefaultValue(key, options)
  17162. , found = _find(key, options);
  17163. return found !== undefined || found === notFound;
  17164. }
  17165. function translate(key, options) {
  17166. options = options || {};
  17167. if (!initialized) {
  17168. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  17169. return options.defaultValue || '';
  17170. };
  17171. replacementCounter = 0;
  17172. return _translate.apply(null, arguments);
  17173. }
  17174. function _getDefaultValue(key, options) {
  17175. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  17176. }
  17177. function _injectSprintfProcessor() {
  17178. var values = [];
  17179. // mh: build array from second argument onwards
  17180. for (var i = 1; i < arguments.length; i++) {
  17181. values.push(arguments[i]);
  17182. }
  17183. return {
  17184. postProcess: 'sprintf',
  17185. sprintf: values
  17186. };
  17187. }
  17188. function _translate(potentialKeys, options) {
  17189. if (options && typeof options !== 'object') {
  17190. if (o.shortcutFunction === 'sprintf') {
  17191. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  17192. options = _injectSprintfProcessor.apply(null, arguments);
  17193. } else if (o.shortcutFunction === 'defaultValue') {
  17194. options = {
  17195. defaultValue: options
  17196. }
  17197. }
  17198. } else {
  17199. options = options || {};
  17200. }
  17201. if (typeof o.defaultVariables === 'object') {
  17202. options = f.extend({}, o.defaultVariables, options);
  17203. }
  17204. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  17205. if (typeof potentialKeys === 'string') {
  17206. potentialKeys = [potentialKeys];
  17207. }
  17208. var key = potentialKeys[0];
  17209. if (potentialKeys.length > 1) {
  17210. for (var i = 0; i < potentialKeys.length; i++) {
  17211. key = potentialKeys[i];
  17212. if (exists(key, options)) {
  17213. break;
  17214. }
  17215. }
  17216. }
  17217. var notFound = _getDefaultValue(key, options)
  17218. , found = _find(key, options)
  17219. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  17220. , ns = options.ns || o.ns.defaultNs
  17221. , parts;
  17222. // split ns and key
  17223. if (key.indexOf(o.nsseparator) > -1) {
  17224. parts = key.split(o.nsseparator);
  17225. ns = parts[0];
  17226. key = parts[1];
  17227. }
  17228. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  17229. if (options.lng) {
  17230. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  17231. } else {
  17232. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  17233. }
  17234. }
  17235. var postProcessor = options.postProcess || o.postProcess;
  17236. if (found !== undefined && postProcessor) {
  17237. if (postProcessors[postProcessor]) {
  17238. found = postProcessors[postProcessor](found, key, options);
  17239. }
  17240. }
  17241. // process notFound if function exists
  17242. var splitNotFound = notFound;
  17243. if (notFound.indexOf(o.nsseparator) > -1) {
  17244. parts = notFound.split(o.nsseparator);
  17245. splitNotFound = parts[1];
  17246. }
  17247. if (splitNotFound === key && o.parseMissingKey) {
  17248. notFound = o.parseMissingKey(notFound);
  17249. }
  17250. if (found === undefined) {
  17251. notFound = applyReplacement(notFound, options);
  17252. notFound = applyReuse(notFound, options);
  17253. if (postProcessor && postProcessors[postProcessor]) {
  17254. var val = _getDefaultValue(key, options);
  17255. found = postProcessors[postProcessor](val, key, options);
  17256. }
  17257. }
  17258. return (found !== undefined) ? found : notFound;
  17259. }
  17260. function _find(key, options) {
  17261. options = options || {};
  17262. var optionWithoutCount, translated
  17263. , notFound = _getDefaultValue(key, options)
  17264. , lngs = languages;
  17265. if (!resStore) { return notFound; } // no resStore to translate from
  17266. // CI mode
  17267. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  17268. // passed in lng
  17269. if (options.lngs) lngs = options.lngs;
  17270. if (options.lng) {
  17271. lngs = f.toLanguages(options.lng, options.fallbackLng);
  17272. if (!resStore[lngs[0]]) {
  17273. var oldAsync = o.getAsync;
  17274. o.getAsync = false;
  17275. i18n.sync.load(lngs, o, function(err, store) {
  17276. f.extend(resStore, store);
  17277. o.getAsync = oldAsync;
  17278. });
  17279. }
  17280. }
  17281. var ns = options.ns || o.ns.defaultNs;
  17282. if (key.indexOf(o.nsseparator) > -1) {
  17283. var parts = key.split(o.nsseparator);
  17284. ns = parts[0];
  17285. key = parts[1];
  17286. }
  17287. if (hasContext(options)) {
  17288. optionWithoutCount = f.extend({}, options);
  17289. delete optionWithoutCount.context;
  17290. optionWithoutCount.defaultValue = o.contextNotFound;
  17291. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  17292. translated = translate(contextKey, optionWithoutCount);
  17293. if (translated != o.contextNotFound) {
  17294. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  17295. } // else continue translation with original/nonContext key
  17296. }
  17297. if (needsPlural(options, lngs[0])) {
  17298. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  17299. delete optionWithoutCount.count;
  17300. delete optionWithoutCount.lng;
  17301. optionWithoutCount.defaultValue = o.pluralNotFound;
  17302. var pluralKey;
  17303. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  17304. pluralKey = ns + o.nsseparator + key;
  17305. } else {
  17306. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  17307. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  17308. if (pluralExtension >= 0) {
  17309. pluralKey = pluralKey + '_' + pluralExtension;
  17310. } else if (pluralExtension === 1) {
  17311. pluralKey = ns + o.nsseparator + key; // singular
  17312. }
  17313. }
  17314. translated = translate(pluralKey, optionWithoutCount);
  17315. if (translated != o.pluralNotFound) {
  17316. return applyReplacement(translated, {
  17317. count: options.count,
  17318. interpolationPrefix: options.interpolationPrefix,
  17319. interpolationSuffix: options.interpolationSuffix
  17320. }); // apply replacement for count only
  17321. } else if (lngs.length > 1) {
  17322. // remove failed lng
  17323. var clone = lngs.slice();
  17324. clone.shift();
  17325. options = f.extend(options, { lngs: clone });
  17326. delete options.lng;
  17327. // retry with fallbacks
  17328. translated = translate(ns + o.nsseparator + key, options);
  17329. if (translated != o.pluralNotFound) return translated;
  17330. } else {
  17331. return translated;
  17332. }
  17333. }
  17334. if (needsIndefiniteArticle(options)) {
  17335. var optionsWithoutIndef = f.extend({}, options);
  17336. delete optionsWithoutIndef.indefinite_article;
  17337. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  17338. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  17339. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  17340. translated = translate(indefiniteKey, optionsWithoutIndef);
  17341. if (translated != o.indefiniteNotFound) {
  17342. return translated;
  17343. }
  17344. }
  17345. var found;
  17346. var keys = key.split(o.keyseparator);
  17347. for (var i = 0, len = lngs.length; i < len; i++ ) {
  17348. if (found !== undefined) break;
  17349. var l = lngs[i];
  17350. var x = 0;
  17351. var value = resStore[l] && resStore[l][ns];
  17352. while (keys[x]) {
  17353. value = value && value[keys[x]];
  17354. x++;
  17355. }
  17356. if (value !== undefined) {
  17357. var valueType = Object.prototype.toString.apply(value);
  17358. if (typeof value === 'string') {
  17359. value = applyReplacement(value, options);
  17360. value = applyReuse(value, options);
  17361. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  17362. value = value.join('\n');
  17363. value = applyReplacement(value, options);
  17364. value = applyReuse(value, options);
  17365. } else if (value === null && o.fallbackOnNull === true) {
  17366. value = undefined;
  17367. } else if (value !== null) {
  17368. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  17369. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  17370. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  17371. } else {
  17372. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  17373. 'returned an object instead of string.';
  17374. f.log(value);
  17375. }
  17376. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  17377. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  17378. f.each(value, function(m) {
  17379. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  17380. });
  17381. value = copy;
  17382. }
  17383. }
  17384. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  17385. value = undefined;
  17386. found = value;
  17387. }
  17388. }
  17389. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  17390. // set flag for fallback lookup - avoid recursion
  17391. options.isFallbackLookup = true;
  17392. if (o.fallbackNS.length) {
  17393. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  17394. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  17395. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  17396. /* compare value without namespace */
  17397. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  17398. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  17399. if (foundValue !== notFoundValue) break;
  17400. }
  17401. }
  17402. } else {
  17403. found = _find(key, options); // fallback to default NS
  17404. }
  17405. options.isFallbackLookup = false;
  17406. }
  17407. return found;
  17408. }
  17409. function detectLanguage() {
  17410. var detectedLng;
  17411. var whitelist = o.lngWhitelist || [];
  17412. var userLngChoices = [];
  17413. // get from qs
  17414. var qsParm = [];
  17415. if (typeof window !== 'undefined') {
  17416. (function() {
  17417. var query = window.location.search.substring(1);
  17418. var params = query.split('&');
  17419. for (var i=0; i<params.length; i++) {
  17420. var pos = params[i].indexOf('=');
  17421. if (pos > 0) {
  17422. var key = params[i].substring(0,pos);
  17423. if (key == o.detectLngQS) {
  17424. userLngChoices.push(params[i].substring(pos+1));
  17425. }
  17426. }
  17427. }
  17428. })();
  17429. }
  17430. // get from cookie
  17431. if (o.useCookie && typeof document !== 'undefined') {
  17432. var c = f.cookie.read(o.cookieName);
  17433. if (c) userLngChoices.push(c);
  17434. }
  17435. // get from localStorage
  17436. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  17437. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  17438. }
  17439. // get from navigator
  17440. if (typeof navigator !== 'undefined') {
  17441. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  17442. for (var i=0;i<navigator.languages.length;i++) {
  17443. userLngChoices.push(navigator.languages[i]);
  17444. }
  17445. }
  17446. if (navigator.userLanguage) {
  17447. userLngChoices.push(navigator.userLanguage);
  17448. }
  17449. if (navigator.language) {
  17450. userLngChoices.push(navigator.language);
  17451. }
  17452. }
  17453. (function() {
  17454. for (var i=0;i<userLngChoices.length;i++) {
  17455. var lng = userLngChoices[i];
  17456. if (lng.indexOf('-') > -1) {
  17457. var parts = lng.split('-');
  17458. lng = o.lowerCaseLng ?
  17459. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17460. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17461. }
  17462. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  17463. detectedLng = lng;
  17464. break;
  17465. }
  17466. }
  17467. })();
  17468. //fallback
  17469. if (!detectedLng){
  17470. detectedLng = o.fallbackLng[0];
  17471. }
  17472. return detectedLng;
  17473. }
  17474. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  17475. /* [code, name, numbers, pluralsType] */
  17476. var _rules = [
  17477. ["ach", "Acholi", [1,2], 1],
  17478. ["af", "Afrikaans",[1,2], 2],
  17479. ["ak", "Akan", [1,2], 1],
  17480. ["am", "Amharic", [1,2], 1],
  17481. ["an", "Aragonese",[1,2], 2],
  17482. ["ar", "Arabic", [0,1,2,3,11,100],5],
  17483. ["arn", "Mapudungun",[1,2], 1],
  17484. ["ast", "Asturian", [1,2], 2],
  17485. ["ay", "Aymará", [1], 3],
  17486. ["az", "Azerbaijani",[1,2],2],
  17487. ["be", "Belarusian",[1,2,5],4],
  17488. ["bg", "Bulgarian",[1,2], 2],
  17489. ["bn", "Bengali", [1,2], 2],
  17490. ["bo", "Tibetan", [1], 3],
  17491. ["br", "Breton", [1,2], 1],
  17492. ["bs", "Bosnian", [1,2,5],4],
  17493. ["ca", "Catalan", [1,2], 2],
  17494. ["cgg", "Chiga", [1], 3],
  17495. ["cs", "Czech", [1,2,5],6],
  17496. ["csb", "Kashubian",[1,2,5],7],
  17497. ["cy", "Welsh", [1,2,3,8],8],
  17498. ["da", "Danish", [1,2], 2],
  17499. ["de", "German", [1,2], 2],
  17500. ["dev", "Development Fallback", [1,2], 2],
  17501. ["dz", "Dzongkha", [1], 3],
  17502. ["el", "Greek", [1,2], 2],
  17503. ["en", "English", [1,2], 2],
  17504. ["eo", "Esperanto",[1,2], 2],
  17505. ["es", "Spanish", [1,2], 2],
  17506. ["es_ar","Argentinean Spanish", [1,2], 2],
  17507. ["et", "Estonian", [1,2], 2],
  17508. ["eu", "Basque", [1,2], 2],
  17509. ["fa", "Persian", [1], 3],
  17510. ["fi", "Finnish", [1,2], 2],
  17511. ["fil", "Filipino", [1,2], 1],
  17512. ["fo", "Faroese", [1,2], 2],
  17513. ["fr", "French", [1,2], 9],
  17514. ["fur", "Friulian", [1,2], 2],
  17515. ["fy", "Frisian", [1,2], 2],
  17516. ["ga", "Irish", [1,2,3,7,11],10],
  17517. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  17518. ["gl", "Galician", [1,2], 2],
  17519. ["gu", "Gujarati", [1,2], 2],
  17520. ["gun", "Gun", [1,2], 1],
  17521. ["ha", "Hausa", [1,2], 2],
  17522. ["he", "Hebrew", [1,2], 2],
  17523. ["hi", "Hindi", [1,2], 2],
  17524. ["hr", "Croatian", [1,2,5],4],
  17525. ["hu", "Hungarian",[1,2], 2],
  17526. ["hy", "Armenian", [1,2], 2],
  17527. ["ia", "Interlingua",[1,2],2],
  17528. ["id", "Indonesian",[1], 3],
  17529. ["is", "Icelandic",[1,2], 12],
  17530. ["it", "Italian", [1,2], 2],
  17531. ["ja", "Japanese", [1], 3],
  17532. ["jbo", "Lojban", [1], 3],
  17533. ["jv", "Javanese", [0,1], 13],
  17534. ["ka", "Georgian", [1], 3],
  17535. ["kk", "Kazakh", [1], 3],
  17536. ["km", "Khmer", [1], 3],
  17537. ["kn", "Kannada", [1,2], 2],
  17538. ["ko", "Korean", [1], 3],
  17539. ["ku", "Kurdish", [1,2], 2],
  17540. ["kw", "Cornish", [1,2,3,4],14],
  17541. ["ky", "Kyrgyz", [1], 3],
  17542. ["lb", "Letzeburgesch",[1,2],2],
  17543. ["ln", "Lingala", [1,2], 1],
  17544. ["lo", "Lao", [1], 3],
  17545. ["lt", "Lithuanian",[1,2,10],15],
  17546. ["lv", "Latvian", [1,2,0],16],
  17547. ["mai", "Maithili", [1,2], 2],
  17548. ["mfe", "Mauritian Creole",[1,2],1],
  17549. ["mg", "Malagasy", [1,2], 1],
  17550. ["mi", "Maori", [1,2], 1],
  17551. ["mk", "Macedonian",[1,2],17],
  17552. ["ml", "Malayalam",[1,2], 2],
  17553. ["mn", "Mongolian",[1,2], 2],
  17554. ["mnk", "Mandinka", [0,1,2],18],
  17555. ["mr", "Marathi", [1,2], 2],
  17556. ["ms", "Malay", [1], 3],
  17557. ["mt", "Maltese", [1,2,11,20],19],
  17558. ["nah", "Nahuatl", [1,2], 2],
  17559. ["nap", "Neapolitan",[1,2], 2],
  17560. ["nb", "Norwegian Bokmal",[1,2],2],
  17561. ["ne", "Nepali", [1,2], 2],
  17562. ["nl", "Dutch", [1,2], 2],
  17563. ["nn", "Norwegian Nynorsk",[1,2],2],
  17564. ["no", "Norwegian",[1,2], 2],
  17565. ["nso", "Northern Sotho",[1,2],2],
  17566. ["oc", "Occitan", [1,2], 1],
  17567. ["or", "Oriya", [2,1], 2],
  17568. ["pa", "Punjabi", [1,2], 2],
  17569. ["pap", "Papiamento",[1,2], 2],
  17570. ["pl", "Polish", [1,2,5],7],
  17571. ["pms", "Piemontese",[1,2], 2],
  17572. ["ps", "Pashto", [1,2], 2],
  17573. ["pt", "Portuguese",[1,2], 2],
  17574. ["pt_br","Brazilian Portuguese",[1,2], 2],
  17575. ["rm", "Romansh", [1,2], 2],
  17576. ["ro", "Romanian", [1,2,20],20],
  17577. ["ru", "Russian", [1,2,5],4],
  17578. ["sah", "Yakut", [1], 3],
  17579. ["sco", "Scots", [1,2], 2],
  17580. ["se", "Northern Sami",[1,2], 2],
  17581. ["si", "Sinhala", [1,2], 2],
  17582. ["sk", "Slovak", [1,2,5],6],
  17583. ["sl", "Slovenian",[5,1,2,3],21],
  17584. ["so", "Somali", [1,2], 2],
  17585. ["son", "Songhay", [1,2], 2],
  17586. ["sq", "Albanian", [1,2], 2],
  17587. ["sr", "Serbian", [1,2,5],4],
  17588. ["su", "Sundanese",[1], 3],
  17589. ["sv", "Swedish", [1,2], 2],
  17590. ["sw", "Swahili", [1,2], 2],
  17591. ["ta", "Tamil", [1,2], 2],
  17592. ["te", "Telugu", [1,2], 2],
  17593. ["tg", "Tajik", [1,2], 1],
  17594. ["th", "Thai", [1], 3],
  17595. ["ti", "Tigrinya", [1,2], 1],
  17596. ["tk", "Turkmen", [1,2], 2],
  17597. ["tr", "Turkish", [1,2], 1],
  17598. ["tt", "Tatar", [1], 3],
  17599. ["ug", "Uyghur", [1], 3],
  17600. ["uk", "Ukrainian",[1,2,5],4],
  17601. ["ur", "Urdu", [1,2], 2],
  17602. ["uz", "Uzbek", [1,2], 1],
  17603. ["vi", "Vietnamese",[1], 3],
  17604. ["wa", "Walloon", [1,2], 1],
  17605. ["wo", "Wolof", [1], 3],
  17606. ["yo", "Yoruba", [1,2], 2],
  17607. ["zh", "Chinese", [1], 3]
  17608. ];
  17609. var _rulesPluralsTypes = {
  17610. 1: function(n) {return Number(n > 1);},
  17611. 2: function(n) {return Number(n != 1);},
  17612. 3: function(n) {return 0;},
  17613. 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);},
  17614. 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);},
  17615. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  17616. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  17617. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  17618. 9: function(n) {return Number(n >= 2);},
  17619. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  17620. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  17621. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  17622. 13: function(n) {return Number(n !== 0);},
  17623. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  17624. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  17625. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  17626. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  17627. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  17628. 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);},
  17629. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  17630. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  17631. };
  17632. var pluralExtensions = {
  17633. rules: (function () {
  17634. var l, rules = {};
  17635. for (l=_rules.length; l-- ;) {
  17636. rules[_rules[l][0]] = {
  17637. name: _rules[l][1],
  17638. numbers: _rules[l][2],
  17639. plurals: _rulesPluralsTypes[_rules[l][3]]
  17640. }
  17641. }
  17642. return rules;
  17643. }()),
  17644. // you can add your own pluralExtensions
  17645. addRule: function(lng, obj) {
  17646. pluralExtensions.rules[lng] = obj;
  17647. },
  17648. setCurrentLng: function(lng) {
  17649. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  17650. var parts = lng.split('-');
  17651. pluralExtensions.currentRule = {
  17652. lng: lng,
  17653. rule: pluralExtensions.rules[parts[0]]
  17654. };
  17655. }
  17656. },
  17657. needsPlural: function(lng, count) {
  17658. var parts = lng.split('-');
  17659. var ext;
  17660. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  17661. ext = pluralExtensions.currentRule.rule;
  17662. } else {
  17663. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  17664. }
  17665. if (ext && ext.numbers.length <= 1) {
  17666. return false;
  17667. } else {
  17668. return this.get(lng, count) !== 1;
  17669. }
  17670. },
  17671. get: function(lng, count) {
  17672. var parts = lng.split('-');
  17673. function getResult(l, c) {
  17674. var ext;
  17675. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  17676. ext = pluralExtensions.currentRule.rule;
  17677. } else {
  17678. ext = pluralExtensions.rules[l];
  17679. }
  17680. if (ext) {
  17681. var i;
  17682. if (ext.noAbs) {
  17683. i = ext.plurals(c);
  17684. } else {
  17685. i = ext.plurals(Math.abs(c));
  17686. }
  17687. var number = ext.numbers[i];
  17688. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  17689. if (number === 2) {
  17690. number = -1; // regular plural
  17691. } else if (number === 1) {
  17692. number = 1; // singular
  17693. }
  17694. }//console.log(count + '-' + number);
  17695. return number;
  17696. } else {
  17697. return c === 1 ? '1' : '-1';
  17698. }
  17699. }
  17700. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  17701. }
  17702. };
  17703. var postProcessors = {};
  17704. var addPostProcessor = function(name, fc) {
  17705. postProcessors[name] = fc;
  17706. };
  17707. // sprintf support
  17708. var sprintf = (function() {
  17709. function get_type(variable) {
  17710. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  17711. }
  17712. function str_repeat(input, multiplier) {
  17713. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  17714. return output.join('');
  17715. }
  17716. var str_format = function() {
  17717. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  17718. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  17719. }
  17720. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  17721. };
  17722. str_format.format = function(parse_tree, argv) {
  17723. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  17724. for (i = 0; i < tree_length; i++) {
  17725. node_type = get_type(parse_tree[i]);
  17726. if (node_type === 'string') {
  17727. output.push(parse_tree[i]);
  17728. }
  17729. else if (node_type === 'array') {
  17730. match = parse_tree[i]; // convenience purposes only
  17731. if (match[2]) { // keyword argument
  17732. arg = argv[cursor];
  17733. for (k = 0; k < match[2].length; k++) {
  17734. if (!arg.hasOwnProperty(match[2][k])) {
  17735. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  17736. }
  17737. arg = arg[match[2][k]];
  17738. }
  17739. }
  17740. else if (match[1]) { // positional argument (explicit)
  17741. arg = argv[match[1]];
  17742. }
  17743. else { // positional argument (implicit)
  17744. arg = argv[cursor++];
  17745. }
  17746. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  17747. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  17748. }
  17749. switch (match[8]) {
  17750. case 'b': arg = arg.toString(2); break;
  17751. case 'c': arg = String.fromCharCode(arg); break;
  17752. case 'd': arg = parseInt(arg, 10); break;
  17753. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  17754. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  17755. case 'o': arg = arg.toString(8); break;
  17756. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  17757. case 'u': arg = Math.abs(arg); break;
  17758. case 'x': arg = arg.toString(16); break;
  17759. case 'X': arg = arg.toString(16).toUpperCase(); break;
  17760. }
  17761. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  17762. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  17763. pad_length = match[6] - String(arg).length;
  17764. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  17765. output.push(match[5] ? arg + pad : pad + arg);
  17766. }
  17767. }
  17768. return output.join('');
  17769. };
  17770. str_format.cache = {};
  17771. str_format.parse = function(fmt) {
  17772. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  17773. while (_fmt) {
  17774. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  17775. parse_tree.push(match[0]);
  17776. }
  17777. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  17778. parse_tree.push('%');
  17779. }
  17780. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  17781. if (match[2]) {
  17782. arg_names |= 1;
  17783. var field_list = [], replacement_field = match[2], field_match = [];
  17784. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17785. field_list.push(field_match[1]);
  17786. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  17787. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17788. field_list.push(field_match[1]);
  17789. }
  17790. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  17791. field_list.push(field_match[1]);
  17792. }
  17793. else {
  17794. throw('[sprintf] huh?');
  17795. }
  17796. }
  17797. }
  17798. else {
  17799. throw('[sprintf] huh?');
  17800. }
  17801. match[2] = field_list;
  17802. }
  17803. else {
  17804. arg_names |= 2;
  17805. }
  17806. if (arg_names === 3) {
  17807. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  17808. }
  17809. parse_tree.push(match);
  17810. }
  17811. else {
  17812. throw('[sprintf] huh?');
  17813. }
  17814. _fmt = _fmt.substring(match[0].length);
  17815. }
  17816. return parse_tree;
  17817. };
  17818. return str_format;
  17819. })();
  17820. var vsprintf = function(fmt, argv) {
  17821. argv.unshift(fmt);
  17822. return sprintf.apply(null, argv);
  17823. };
  17824. addPostProcessor("sprintf", function(val, key, opts) {
  17825. if (!opts.sprintf) return val;
  17826. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  17827. return vsprintf(val, opts.sprintf);
  17828. } else if (typeof opts.sprintf === 'object') {
  17829. return sprintf(val, opts.sprintf);
  17830. }
  17831. return val;
  17832. });
  17833. // public api interface
  17834. i18n.init = init;
  17835. i18n.setLng = setLng;
  17836. i18n.preload = preload;
  17837. i18n.addResourceBundle = addResourceBundle;
  17838. i18n.hasResourceBundle = hasResourceBundle;
  17839. i18n.addResource = addResource;
  17840. i18n.addResources = addResources;
  17841. i18n.removeResourceBundle = removeResourceBundle;
  17842. i18n.loadNamespace = loadNamespace;
  17843. i18n.loadNamespaces = loadNamespaces;
  17844. i18n.setDefaultNamespace = setDefaultNamespace;
  17845. i18n.t = translate;
  17846. i18n.translate = translate;
  17847. i18n.exists = exists;
  17848. i18n.detectLanguage = f.detectLanguage;
  17849. i18n.pluralExtensions = pluralExtensions;
  17850. i18n.sync = sync;
  17851. i18n.functions = f;
  17852. i18n.lng = lng;
  17853. i18n.addPostProcessor = addPostProcessor;
  17854. i18n.options = o;
  17855. })();
  17856. },{"jquery":"jquery"}],64:[function(require,module,exports){
  17857. // Top level file is just a mixin of submodules & constants
  17858. 'use strict';
  17859. var assign = require('./lib/utils/common').assign;
  17860. var deflate = require('./lib/deflate');
  17861. var inflate = require('./lib/inflate');
  17862. var constants = require('./lib/zlib/constants');
  17863. var pako = {};
  17864. assign(pako, deflate, inflate, constants);
  17865. module.exports = pako;
  17866. },{"./lib/deflate":65,"./lib/inflate":66,"./lib/utils/common":67,"./lib/zlib/constants":70}],65:[function(require,module,exports){
  17867. 'use strict';
  17868. var zlib_deflate = require('./zlib/deflate.js');
  17869. var utils = require('./utils/common');
  17870. var strings = require('./utils/strings');
  17871. var msg = require('./zlib/messages');
  17872. var zstream = require('./zlib/zstream');
  17873. var toString = Object.prototype.toString;
  17874. /* Public constants ==========================================================*/
  17875. /* ===========================================================================*/
  17876. var Z_NO_FLUSH = 0;
  17877. var Z_FINISH = 4;
  17878. var Z_OK = 0;
  17879. var Z_STREAM_END = 1;
  17880. var Z_DEFAULT_COMPRESSION = -1;
  17881. var Z_DEFAULT_STRATEGY = 0;
  17882. var Z_DEFLATED = 8;
  17883. /* ===========================================================================*/
  17884. /**
  17885. * class Deflate
  17886. *
  17887. * Generic JS-style wrapper for zlib calls. If you don't need
  17888. * streaming behaviour - use more simple functions: [[deflate]],
  17889. * [[deflateRaw]] and [[gzip]].
  17890. **/
  17891. /* internal
  17892. * Deflate.chunks -> Array
  17893. *
  17894. * Chunks of output data, if [[Deflate#onData]] not overriden.
  17895. **/
  17896. /**
  17897. * Deflate.result -> Uint8Array|Array
  17898. *
  17899. * Compressed result, generated by default [[Deflate#onData]]
  17900. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  17901. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  17902. **/
  17903. /**
  17904. * Deflate.err -> Number
  17905. *
  17906. * Error code after deflate finished. 0 (Z_OK) on success.
  17907. * You will not need it in real life, because deflate errors
  17908. * are possible only on wrong options or bad `onData` / `onEnd`
  17909. * custom handlers.
  17910. **/
  17911. /**
  17912. * Deflate.msg -> String
  17913. *
  17914. * Error message, if [[Deflate.err]] != 0
  17915. **/
  17916. /**
  17917. * new Deflate(options)
  17918. * - options (Object): zlib deflate options.
  17919. *
  17920. * Creates new deflator instance with specified params. Throws exception
  17921. * on bad params. Supported options:
  17922. *
  17923. * - `level`
  17924. * - `windowBits`
  17925. * - `memLevel`
  17926. * - `strategy`
  17927. *
  17928. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17929. * for more information on these.
  17930. *
  17931. * Additional options, for internal needs:
  17932. *
  17933. * - `chunkSize` - size of generated data chunks (16K by default)
  17934. * - `raw` (Boolean) - do raw deflate
  17935. * - `gzip` (Boolean) - create gzip wrapper
  17936. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17937. * (each char code [0..255])
  17938. * - `header` (Object) - custom header for gzip
  17939. * - `text` (Boolean) - true if compressed data believed to be text
  17940. * - `time` (Number) - modification time, unix timestamp
  17941. * - `os` (Number) - operation system code
  17942. * - `extra` (Array) - array of bytes with extra data (max 65536)
  17943. * - `name` (String) - file name (binary string)
  17944. * - `comment` (String) - comment (binary string)
  17945. * - `hcrc` (Boolean) - true if header crc should be added
  17946. *
  17947. * ##### Example:
  17948. *
  17949. * ```javascript
  17950. * var pako = require('pako')
  17951. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17952. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17953. *
  17954. * var deflate = new pako.Deflate({ level: 3});
  17955. *
  17956. * deflate.push(chunk1, false);
  17957. * deflate.push(chunk2, true); // true -> last chunk
  17958. *
  17959. * if (deflate.err) { throw new Error(deflate.err); }
  17960. *
  17961. * console.log(deflate.result);
  17962. * ```
  17963. **/
  17964. var Deflate = function(options) {
  17965. this.options = utils.assign({
  17966. level: Z_DEFAULT_COMPRESSION,
  17967. method: Z_DEFLATED,
  17968. chunkSize: 16384,
  17969. windowBits: 15,
  17970. memLevel: 8,
  17971. strategy: Z_DEFAULT_STRATEGY,
  17972. to: ''
  17973. }, options || {});
  17974. var opt = this.options;
  17975. if (opt.raw && (opt.windowBits > 0)) {
  17976. opt.windowBits = -opt.windowBits;
  17977. }
  17978. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  17979. opt.windowBits += 16;
  17980. }
  17981. this.err = 0; // error code, if happens (0 = Z_OK)
  17982. this.msg = ''; // error message
  17983. this.ended = false; // used to avoid multiple onEnd() calls
  17984. this.chunks = []; // chunks of compressed data
  17985. this.strm = new zstream();
  17986. this.strm.avail_out = 0;
  17987. var status = zlib_deflate.deflateInit2(
  17988. this.strm,
  17989. opt.level,
  17990. opt.method,
  17991. opt.windowBits,
  17992. opt.memLevel,
  17993. opt.strategy
  17994. );
  17995. if (status !== Z_OK) {
  17996. throw new Error(msg[status]);
  17997. }
  17998. if (opt.header) {
  17999. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  18000. }
  18001. };
  18002. /**
  18003. * Deflate#push(data[, mode]) -> Boolean
  18004. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  18005. * converted to utf8 byte sequence.
  18006. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18007. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18008. *
  18009. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  18010. * new compressed chunks. Returns `true` on success. The last data block must have
  18011. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  18012. * [[Deflate#onEnd]].
  18013. *
  18014. * On fail call [[Deflate#onEnd]] with error code and return false.
  18015. *
  18016. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18017. * array format is detected automatically). Also, don't skip last param and always
  18018. * use the same type in your code (boolean or number). That will improve JS speed.
  18019. *
  18020. * For regular `Array`-s make sure all elements are [0..255].
  18021. *
  18022. * ##### Example
  18023. *
  18024. * ```javascript
  18025. * push(chunk, false); // push one of data chunks
  18026. * ...
  18027. * push(chunk, true); // push last chunk
  18028. * ```
  18029. **/
  18030. Deflate.prototype.push = function(data, mode) {
  18031. var strm = this.strm;
  18032. var chunkSize = this.options.chunkSize;
  18033. var status, _mode;
  18034. if (this.ended) { return false; }
  18035. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  18036. // Convert data if needed
  18037. if (typeof data === 'string') {
  18038. // If we need to compress text, change encoding to utf8.
  18039. strm.input = strings.string2buf(data);
  18040. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18041. strm.input = new Uint8Array(data);
  18042. } else {
  18043. strm.input = data;
  18044. }
  18045. strm.next_in = 0;
  18046. strm.avail_in = strm.input.length;
  18047. do {
  18048. if (strm.avail_out === 0) {
  18049. strm.output = new utils.Buf8(chunkSize);
  18050. strm.next_out = 0;
  18051. strm.avail_out = chunkSize;
  18052. }
  18053. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  18054. if (status !== Z_STREAM_END && status !== Z_OK) {
  18055. this.onEnd(status);
  18056. this.ended = true;
  18057. return false;
  18058. }
  18059. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  18060. if (this.options.to === 'string') {
  18061. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  18062. } else {
  18063. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18064. }
  18065. }
  18066. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  18067. // Finalize on the last chunk.
  18068. if (_mode === Z_FINISH) {
  18069. status = zlib_deflate.deflateEnd(this.strm);
  18070. this.onEnd(status);
  18071. this.ended = true;
  18072. return status === Z_OK;
  18073. }
  18074. return true;
  18075. };
  18076. /**
  18077. * Deflate#onData(chunk) -> Void
  18078. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18079. * on js engine support. When string output requested, each chunk
  18080. * will be string.
  18081. *
  18082. * By default, stores data blocks in `chunks[]` property and glue
  18083. * those in `onEnd`. Override this handler, if you need another behaviour.
  18084. **/
  18085. Deflate.prototype.onData = function(chunk) {
  18086. this.chunks.push(chunk);
  18087. };
  18088. /**
  18089. * Deflate#onEnd(status) -> Void
  18090. * - status (Number): deflate status. 0 (Z_OK) on success,
  18091. * other if not.
  18092. *
  18093. * Called once after you tell deflate that input stream complete
  18094. * or error happenned. By default - join collected chunks,
  18095. * free memory and fill `results` / `err` properties.
  18096. **/
  18097. Deflate.prototype.onEnd = function(status) {
  18098. // On success - join
  18099. if (status === Z_OK) {
  18100. if (this.options.to === 'string') {
  18101. this.result = this.chunks.join('');
  18102. } else {
  18103. this.result = utils.flattenChunks(this.chunks);
  18104. }
  18105. }
  18106. this.chunks = [];
  18107. this.err = status;
  18108. this.msg = this.strm.msg;
  18109. };
  18110. /**
  18111. * deflate(data[, options]) -> Uint8Array|Array|String
  18112. * - data (Uint8Array|Array|String): input data to compress.
  18113. * - options (Object): zlib deflate options.
  18114. *
  18115. * Compress `data` with deflate alrorythm and `options`.
  18116. *
  18117. * Supported options are:
  18118. *
  18119. * - level
  18120. * - windowBits
  18121. * - memLevel
  18122. * - strategy
  18123. *
  18124. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18125. * for more information on these.
  18126. *
  18127. * Sugar (options):
  18128. *
  18129. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  18130. * negative windowBits implicitly.
  18131. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18132. * (each char code [0..255])
  18133. *
  18134. * ##### Example:
  18135. *
  18136. * ```javascript
  18137. * var pako = require('pako')
  18138. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  18139. *
  18140. * console.log(pako.deflate(data));
  18141. * ```
  18142. **/
  18143. function deflate(input, options) {
  18144. var deflator = new Deflate(options);
  18145. deflator.push(input, true);
  18146. // That will never happens, if you don't cheat with options :)
  18147. if (deflator.err) { throw deflator.msg; }
  18148. return deflator.result;
  18149. }
  18150. /**
  18151. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  18152. * - data (Uint8Array|Array|String): input data to compress.
  18153. * - options (Object): zlib deflate options.
  18154. *
  18155. * The same as [[deflate]], but creates raw data, without wrapper
  18156. * (header and adler32 crc).
  18157. **/
  18158. function deflateRaw(input, options) {
  18159. options = options || {};
  18160. options.raw = true;
  18161. return deflate(input, options);
  18162. }
  18163. /**
  18164. * gzip(data[, options]) -> Uint8Array|Array|String
  18165. * - data (Uint8Array|Array|String): input data to compress.
  18166. * - options (Object): zlib deflate options.
  18167. *
  18168. * The same as [[deflate]], but create gzip wrapper instead of
  18169. * deflate one.
  18170. **/
  18171. function gzip(input, options) {
  18172. options = options || {};
  18173. options.gzip = true;
  18174. return deflate(input, options);
  18175. }
  18176. exports.Deflate = Deflate;
  18177. exports.deflate = deflate;
  18178. exports.deflateRaw = deflateRaw;
  18179. exports.gzip = gzip;
  18180. },{"./utils/common":67,"./utils/strings":68,"./zlib/deflate.js":72,"./zlib/messages":77,"./zlib/zstream":79}],66:[function(require,module,exports){
  18181. 'use strict';
  18182. var zlib_inflate = require('./zlib/inflate.js');
  18183. var utils = require('./utils/common');
  18184. var strings = require('./utils/strings');
  18185. var c = require('./zlib/constants');
  18186. var msg = require('./zlib/messages');
  18187. var zstream = require('./zlib/zstream');
  18188. var gzheader = require('./zlib/gzheader');
  18189. var toString = Object.prototype.toString;
  18190. /**
  18191. * class Inflate
  18192. *
  18193. * Generic JS-style wrapper for zlib calls. If you don't need
  18194. * streaming behaviour - use more simple functions: [[inflate]]
  18195. * and [[inflateRaw]].
  18196. **/
  18197. /* internal
  18198. * inflate.chunks -> Array
  18199. *
  18200. * Chunks of output data, if [[Inflate#onData]] not overriden.
  18201. **/
  18202. /**
  18203. * Inflate.result -> Uint8Array|Array|String
  18204. *
  18205. * Uncompressed result, generated by default [[Inflate#onData]]
  18206. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  18207. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  18208. **/
  18209. /**
  18210. * Inflate.err -> Number
  18211. *
  18212. * Error code after inflate finished. 0 (Z_OK) on success.
  18213. * Should be checked if broken data possible.
  18214. **/
  18215. /**
  18216. * Inflate.msg -> String
  18217. *
  18218. * Error message, if [[Inflate.err]] != 0
  18219. **/
  18220. /**
  18221. * new Inflate(options)
  18222. * - options (Object): zlib inflate options.
  18223. *
  18224. * Creates new inflator instance with specified params. Throws exception
  18225. * on bad params. Supported options:
  18226. *
  18227. * - `windowBits`
  18228. *
  18229. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18230. * for more information on these.
  18231. *
  18232. * Additional options, for internal needs:
  18233. *
  18234. * - `chunkSize` - size of generated data chunks (16K by default)
  18235. * - `raw` (Boolean) - do raw inflate
  18236. * - `to` (String) - if equal to 'string', then result will be converted
  18237. * from utf8 to utf16 (javascript) string. When string output requested,
  18238. * chunk length can differ from `chunkSize`, depending on content.
  18239. *
  18240. * By default, when no options set, autodetect deflate/gzip data format via
  18241. * wrapper header.
  18242. *
  18243. * ##### Example:
  18244. *
  18245. * ```javascript
  18246. * var pako = require('pako')
  18247. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18248. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18249. *
  18250. * var inflate = new pako.Inflate({ level: 3});
  18251. *
  18252. * inflate.push(chunk1, false);
  18253. * inflate.push(chunk2, true); // true -> last chunk
  18254. *
  18255. * if (inflate.err) { throw new Error(inflate.err); }
  18256. *
  18257. * console.log(inflate.result);
  18258. * ```
  18259. **/
  18260. var Inflate = function(options) {
  18261. this.options = utils.assign({
  18262. chunkSize: 16384,
  18263. windowBits: 0,
  18264. to: ''
  18265. }, options || {});
  18266. var opt = this.options;
  18267. // Force window size for `raw` data, if not set directly,
  18268. // because we have no header for autodetect.
  18269. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  18270. opt.windowBits = -opt.windowBits;
  18271. if (opt.windowBits === 0) { opt.windowBits = -15; }
  18272. }
  18273. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  18274. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  18275. !(options && options.windowBits)) {
  18276. opt.windowBits += 32;
  18277. }
  18278. // Gzip header has no info about windows size, we can do autodetect only
  18279. // for deflate. So, if window size not set, force it to max when gzip possible
  18280. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  18281. // bit 3 (16) -> gzipped data
  18282. // bit 4 (32) -> autodetect gzip/deflate
  18283. if ((opt.windowBits & 15) === 0) {
  18284. opt.windowBits |= 15;
  18285. }
  18286. }
  18287. this.err = 0; // error code, if happens (0 = Z_OK)
  18288. this.msg = ''; // error message
  18289. this.ended = false; // used to avoid multiple onEnd() calls
  18290. this.chunks = []; // chunks of compressed data
  18291. this.strm = new zstream();
  18292. this.strm.avail_out = 0;
  18293. var status = zlib_inflate.inflateInit2(
  18294. this.strm,
  18295. opt.windowBits
  18296. );
  18297. if (status !== c.Z_OK) {
  18298. throw new Error(msg[status]);
  18299. }
  18300. this.header = new gzheader();
  18301. zlib_inflate.inflateGetHeader(this.strm, this.header);
  18302. };
  18303. /**
  18304. * Inflate#push(data[, mode]) -> Boolean
  18305. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  18306. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18307. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18308. *
  18309. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  18310. * new output chunks. Returns `true` on success. The last data block must have
  18311. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  18312. * [[Inflate#onEnd]].
  18313. *
  18314. * On fail call [[Inflate#onEnd]] with error code and return false.
  18315. *
  18316. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18317. * format is detected automatically). Also, don't skip last param and always
  18318. * use the same type in your code (boolean or number). That will improve JS speed.
  18319. *
  18320. * For regular `Array`-s make sure all elements are [0..255].
  18321. *
  18322. * ##### Example
  18323. *
  18324. * ```javascript
  18325. * push(chunk, false); // push one of data chunks
  18326. * ...
  18327. * push(chunk, true); // push last chunk
  18328. * ```
  18329. **/
  18330. Inflate.prototype.push = function(data, mode) {
  18331. var strm = this.strm;
  18332. var chunkSize = this.options.chunkSize;
  18333. var status, _mode;
  18334. var next_out_utf8, tail, utf8str;
  18335. if (this.ended) { return false; }
  18336. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  18337. // Convert data if needed
  18338. if (typeof data === 'string') {
  18339. // Only binary strings can be decompressed on practice
  18340. strm.input = strings.binstring2buf(data);
  18341. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18342. strm.input = new Uint8Array(data);
  18343. } else {
  18344. strm.input = data;
  18345. }
  18346. strm.next_in = 0;
  18347. strm.avail_in = strm.input.length;
  18348. do {
  18349. if (strm.avail_out === 0) {
  18350. strm.output = new utils.Buf8(chunkSize);
  18351. strm.next_out = 0;
  18352. strm.avail_out = chunkSize;
  18353. }
  18354. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  18355. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  18356. this.onEnd(status);
  18357. this.ended = true;
  18358. return false;
  18359. }
  18360. if (strm.next_out) {
  18361. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  18362. if (this.options.to === 'string') {
  18363. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  18364. tail = strm.next_out - next_out_utf8;
  18365. utf8str = strings.buf2string(strm.output, next_out_utf8);
  18366. // move tail
  18367. strm.next_out = tail;
  18368. strm.avail_out = chunkSize - tail;
  18369. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  18370. this.onData(utf8str);
  18371. } else {
  18372. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18373. }
  18374. }
  18375. }
  18376. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  18377. if (status === c.Z_STREAM_END) {
  18378. _mode = c.Z_FINISH;
  18379. }
  18380. // Finalize on the last chunk.
  18381. if (_mode === c.Z_FINISH) {
  18382. status = zlib_inflate.inflateEnd(this.strm);
  18383. this.onEnd(status);
  18384. this.ended = true;
  18385. return status === c.Z_OK;
  18386. }
  18387. return true;
  18388. };
  18389. /**
  18390. * Inflate#onData(chunk) -> Void
  18391. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18392. * on js engine support. When string output requested, each chunk
  18393. * will be string.
  18394. *
  18395. * By default, stores data blocks in `chunks[]` property and glue
  18396. * those in `onEnd`. Override this handler, if you need another behaviour.
  18397. **/
  18398. Inflate.prototype.onData = function(chunk) {
  18399. this.chunks.push(chunk);
  18400. };
  18401. /**
  18402. * Inflate#onEnd(status) -> Void
  18403. * - status (Number): inflate status. 0 (Z_OK) on success,
  18404. * other if not.
  18405. *
  18406. * Called once after you tell inflate that input stream complete
  18407. * or error happenned. By default - join collected chunks,
  18408. * free memory and fill `results` / `err` properties.
  18409. **/
  18410. Inflate.prototype.onEnd = function(status) {
  18411. // On success - join
  18412. if (status === c.Z_OK) {
  18413. if (this.options.to === 'string') {
  18414. // Glue & convert here, until we teach pako to send
  18415. // utf8 alligned strings to onData
  18416. this.result = this.chunks.join('');
  18417. } else {
  18418. this.result = utils.flattenChunks(this.chunks);
  18419. }
  18420. }
  18421. this.chunks = [];
  18422. this.err = status;
  18423. this.msg = this.strm.msg;
  18424. };
  18425. /**
  18426. * inflate(data[, options]) -> Uint8Array|Array|String
  18427. * - data (Uint8Array|Array|String): input data to decompress.
  18428. * - options (Object): zlib inflate options.
  18429. *
  18430. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  18431. * format via wrapper header by default. That's why we don't provide
  18432. * separate `ungzip` method.
  18433. *
  18434. * Supported options are:
  18435. *
  18436. * - windowBits
  18437. *
  18438. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18439. * for more information.
  18440. *
  18441. * Sugar (options):
  18442. *
  18443. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  18444. * negative windowBits implicitly.
  18445. * - `to` (String) - if equal to 'string', then result will be converted
  18446. * from utf8 to utf16 (javascript) string. When string output requested,
  18447. * chunk length can differ from `chunkSize`, depending on content.
  18448. *
  18449. *
  18450. * ##### Example:
  18451. *
  18452. * ```javascript
  18453. * var pako = require('pako')
  18454. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  18455. * , output;
  18456. *
  18457. * try {
  18458. * output = pako.inflate(input);
  18459. * } catch (err)
  18460. * console.log(err);
  18461. * }
  18462. * ```
  18463. **/
  18464. function inflate(input, options) {
  18465. var inflator = new Inflate(options);
  18466. inflator.push(input, true);
  18467. // That will never happens, if you don't cheat with options :)
  18468. if (inflator.err) { throw inflator.msg; }
  18469. return inflator.result;
  18470. }
  18471. /**
  18472. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  18473. * - data (Uint8Array|Array|String): input data to decompress.
  18474. * - options (Object): zlib inflate options.
  18475. *
  18476. * The same as [[inflate]], but creates raw data, without wrapper
  18477. * (header and adler32 crc).
  18478. **/
  18479. function inflateRaw(input, options) {
  18480. options = options || {};
  18481. options.raw = true;
  18482. return inflate(input, options);
  18483. }
  18484. /**
  18485. * ungzip(data[, options]) -> Uint8Array|Array|String
  18486. * - data (Uint8Array|Array|String): input data to decompress.
  18487. * - options (Object): zlib inflate options.
  18488. *
  18489. * Just shortcut to [[inflate]], because it autodetects format
  18490. * by header.content. Done for convenience.
  18491. **/
  18492. exports.Inflate = Inflate;
  18493. exports.inflate = inflate;
  18494. exports.inflateRaw = inflateRaw;
  18495. exports.ungzip = inflate;
  18496. },{"./utils/common":67,"./utils/strings":68,"./zlib/constants":70,"./zlib/gzheader":73,"./zlib/inflate.js":75,"./zlib/messages":77,"./zlib/zstream":79}],67:[function(require,module,exports){
  18497. 'use strict';
  18498. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  18499. (typeof Uint16Array !== 'undefined') &&
  18500. (typeof Int32Array !== 'undefined');
  18501. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  18502. var sources = Array.prototype.slice.call(arguments, 1);
  18503. while (sources.length) {
  18504. var source = sources.shift();
  18505. if (!source) { continue; }
  18506. if (typeof(source) !== 'object') {
  18507. throw new TypeError(source + 'must be non-object');
  18508. }
  18509. for (var p in source) {
  18510. if (source.hasOwnProperty(p)) {
  18511. obj[p] = source[p];
  18512. }
  18513. }
  18514. }
  18515. return obj;
  18516. };
  18517. // reduce buffer size, avoiding mem copy
  18518. exports.shrinkBuf = function (buf, size) {
  18519. if (buf.length === size) { return buf; }
  18520. if (buf.subarray) { return buf.subarray(0, size); }
  18521. buf.length = size;
  18522. return buf;
  18523. };
  18524. var fnTyped = {
  18525. arraySet: function (dest, src, src_offs, len, dest_offs) {
  18526. if (src.subarray && dest.subarray) {
  18527. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  18528. return;
  18529. }
  18530. // Fallback to ordinary array
  18531. for(var i=0; i<len; i++) {
  18532. dest[dest_offs + i] = src[src_offs + i];
  18533. }
  18534. },
  18535. // Join array of chunks to single array.
  18536. flattenChunks: function(chunks) {
  18537. var i, l, len, pos, chunk, result;
  18538. // calculate data length
  18539. len = 0;
  18540. for (i=0, l=chunks.length; i<l; i++) {
  18541. len += chunks[i].length;
  18542. }
  18543. // join chunks
  18544. result = new Uint8Array(len);
  18545. pos = 0;
  18546. for (i=0, l=chunks.length; i<l; i++) {
  18547. chunk = chunks[i];
  18548. result.set(chunk, pos);
  18549. pos += chunk.length;
  18550. }
  18551. return result;
  18552. }
  18553. };
  18554. var fnUntyped = {
  18555. arraySet: function (dest, src, src_offs, len, dest_offs) {
  18556. for(var i=0; i<len; i++) {
  18557. dest[dest_offs + i] = src[src_offs + i];
  18558. }
  18559. },
  18560. // Join array of chunks to single array.
  18561. flattenChunks: function(chunks) {
  18562. return [].concat.apply([], chunks);
  18563. }
  18564. };
  18565. // Enable/Disable typed arrays use, for testing
  18566. //
  18567. exports.setTyped = function (on) {
  18568. if (on) {
  18569. exports.Buf8 = Uint8Array;
  18570. exports.Buf16 = Uint16Array;
  18571. exports.Buf32 = Int32Array;
  18572. exports.assign(exports, fnTyped);
  18573. } else {
  18574. exports.Buf8 = Array;
  18575. exports.Buf16 = Array;
  18576. exports.Buf32 = Array;
  18577. exports.assign(exports, fnUntyped);
  18578. }
  18579. };
  18580. exports.setTyped(TYPED_OK);
  18581. },{}],68:[function(require,module,exports){
  18582. // String encode/decode helpers
  18583. 'use strict';
  18584. var utils = require('./common');
  18585. // Quick check if we can use fast array to bin string conversion
  18586. //
  18587. // - apply(Array) can fail on Android 2.2
  18588. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  18589. //
  18590. var STR_APPLY_OK = true;
  18591. var STR_APPLY_UIA_OK = true;
  18592. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  18593. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  18594. // Table with utf8 lengths (calculated by first byte of sequence)
  18595. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  18596. // because max possible codepoint is 0x10ffff
  18597. var _utf8len = new utils.Buf8(256);
  18598. for (var i=0; i<256; i++) {
  18599. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  18600. }
  18601. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  18602. // convert string to array (typed, when possible)
  18603. exports.string2buf = function (str) {
  18604. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  18605. // count binary size
  18606. for (m_pos = 0; m_pos < str_len; m_pos++) {
  18607. c = str.charCodeAt(m_pos);
  18608. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  18609. c2 = str.charCodeAt(m_pos+1);
  18610. if ((c2 & 0xfc00) === 0xdc00) {
  18611. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  18612. m_pos++;
  18613. }
  18614. }
  18615. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  18616. }
  18617. // allocate buffer
  18618. buf = new utils.Buf8(buf_len);
  18619. // convert
  18620. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  18621. c = str.charCodeAt(m_pos);
  18622. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  18623. c2 = str.charCodeAt(m_pos+1);
  18624. if ((c2 & 0xfc00) === 0xdc00) {
  18625. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  18626. m_pos++;
  18627. }
  18628. }
  18629. if (c < 0x80) {
  18630. /* one byte */
  18631. buf[i++] = c;
  18632. } else if (c < 0x800) {
  18633. /* two bytes */
  18634. buf[i++] = 0xC0 | (c >>> 6);
  18635. buf[i++] = 0x80 | (c & 0x3f);
  18636. } else if (c < 0x10000) {
  18637. /* three bytes */
  18638. buf[i++] = 0xE0 | (c >>> 12);
  18639. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  18640. buf[i++] = 0x80 | (c & 0x3f);
  18641. } else {
  18642. /* four bytes */
  18643. buf[i++] = 0xf0 | (c >>> 18);
  18644. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  18645. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  18646. buf[i++] = 0x80 | (c & 0x3f);
  18647. }
  18648. }
  18649. return buf;
  18650. };
  18651. // Helper (used in 2 places)
  18652. function buf2binstring(buf, len) {
  18653. // use fallback for big arrays to avoid stack overflow
  18654. if (len < 65537) {
  18655. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  18656. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  18657. }
  18658. }
  18659. var result = '';
  18660. for(var i=0; i < len; i++) {
  18661. result += String.fromCharCode(buf[i]);
  18662. }
  18663. return result;
  18664. }
  18665. // Convert byte array to binary string
  18666. exports.buf2binstring = function(buf) {
  18667. return buf2binstring(buf, buf.length);
  18668. };
  18669. // Convert binary string (typed, when possible)
  18670. exports.binstring2buf = function(str) {
  18671. var buf = new utils.Buf8(str.length);
  18672. for(var i=0, len=buf.length; i < len; i++) {
  18673. buf[i] = str.charCodeAt(i);
  18674. }
  18675. return buf;
  18676. };
  18677. // convert array to string
  18678. exports.buf2string = function (buf, max) {
  18679. var i, out, c, c_len;
  18680. var len = max || buf.length;
  18681. // Reserve max possible length (2 words per char)
  18682. // NB: by unknown reasons, Array is significantly faster for
  18683. // String.fromCharCode.apply than Uint16Array.
  18684. var utf16buf = new Array(len*2);
  18685. for (out=0, i=0; i<len;) {
  18686. c = buf[i++];
  18687. // quick process ascii
  18688. if (c < 0x80) { utf16buf[out++] = c; continue; }
  18689. c_len = _utf8len[c];
  18690. // skip 5 & 6 byte codes
  18691. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  18692. // apply mask on first byte
  18693. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  18694. // join the rest
  18695. while (c_len > 1 && i < len) {
  18696. c = (c << 6) | (buf[i++] & 0x3f);
  18697. c_len--;
  18698. }
  18699. // terminated by end of string?
  18700. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  18701. if (c < 0x10000) {
  18702. utf16buf[out++] = c;
  18703. } else {
  18704. c -= 0x10000;
  18705. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  18706. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  18707. }
  18708. }
  18709. return buf2binstring(utf16buf, out);
  18710. };
  18711. // Calculate max possible position in utf8 buffer,
  18712. // that will not break sequence. If that's not possible
  18713. // - (very small limits) return max size as is.
  18714. //
  18715. // buf[] - utf8 bytes array
  18716. // max - length limit (mandatory);
  18717. exports.utf8border = function(buf, max) {
  18718. var pos;
  18719. max = max || buf.length;
  18720. if (max > buf.length) { max = buf.length; }
  18721. // go back from last position, until start of sequence found
  18722. pos = max-1;
  18723. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  18724. // Fuckup - very small and broken sequence,
  18725. // return max, because we should return something anyway.
  18726. if (pos < 0) { return max; }
  18727. // If we came to start of buffer - that means vuffer is too small,
  18728. // return max too.
  18729. if (pos === 0) { return max; }
  18730. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  18731. };
  18732. },{"./common":67}],69:[function(require,module,exports){
  18733. 'use strict';
  18734. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  18735. // It doesn't worth to make additional optimizationa as in original.
  18736. // Small size is preferable.
  18737. function adler32(adler, buf, len, pos) {
  18738. var s1 = (adler & 0xffff) |0
  18739. , s2 = ((adler >>> 16) & 0xffff) |0
  18740. , n = 0;
  18741. while (len !== 0) {
  18742. // Set limit ~ twice less than 5552, to keep
  18743. // s2 in 31-bits, because we force signed ints.
  18744. // in other case %= will fail.
  18745. n = len > 2000 ? 2000 : len;
  18746. len -= n;
  18747. do {
  18748. s1 = (s1 + buf[pos++]) |0;
  18749. s2 = (s2 + s1) |0;
  18750. } while (--n);
  18751. s1 %= 65521;
  18752. s2 %= 65521;
  18753. }
  18754. return (s1 | (s2 << 16)) |0;
  18755. }
  18756. module.exports = adler32;
  18757. },{}],70:[function(require,module,exports){
  18758. module.exports = {
  18759. /* Allowed flush values; see deflate() and inflate() below for details */
  18760. Z_NO_FLUSH: 0,
  18761. Z_PARTIAL_FLUSH: 1,
  18762. Z_SYNC_FLUSH: 2,
  18763. Z_FULL_FLUSH: 3,
  18764. Z_FINISH: 4,
  18765. Z_BLOCK: 5,
  18766. Z_TREES: 6,
  18767. /* Return codes for the compression/decompression functions. Negative values
  18768. * are errors, positive values are used for special but normal events.
  18769. */
  18770. Z_OK: 0,
  18771. Z_STREAM_END: 1,
  18772. Z_NEED_DICT: 2,
  18773. Z_ERRNO: -1,
  18774. Z_STREAM_ERROR: -2,
  18775. Z_DATA_ERROR: -3,
  18776. //Z_MEM_ERROR: -4,
  18777. Z_BUF_ERROR: -5,
  18778. //Z_VERSION_ERROR: -6,
  18779. /* compression levels */
  18780. Z_NO_COMPRESSION: 0,
  18781. Z_BEST_SPEED: 1,
  18782. Z_BEST_COMPRESSION: 9,
  18783. Z_DEFAULT_COMPRESSION: -1,
  18784. Z_FILTERED: 1,
  18785. Z_HUFFMAN_ONLY: 2,
  18786. Z_RLE: 3,
  18787. Z_FIXED: 4,
  18788. Z_DEFAULT_STRATEGY: 0,
  18789. /* Possible values of the data_type field (though see inflate()) */
  18790. Z_BINARY: 0,
  18791. Z_TEXT: 1,
  18792. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  18793. Z_UNKNOWN: 2,
  18794. /* The deflate compression method */
  18795. Z_DEFLATED: 8
  18796. //Z_NULL: null // Use -1 or null inline, depending on var type
  18797. };
  18798. },{}],71:[function(require,module,exports){
  18799. 'use strict';
  18800. // Note: we can't get significant speed boost here.
  18801. // So write code to minimize size - no pregenerated tables
  18802. // and array tools dependencies.
  18803. // Use ordinary array, since untyped makes no boost here
  18804. function makeTable() {
  18805. var c, table = [];
  18806. for(var n =0; n < 256; n++){
  18807. c = n;
  18808. for(var k =0; k < 8; k++){
  18809. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  18810. }
  18811. table[n] = c;
  18812. }
  18813. return table;
  18814. }
  18815. // Create table on load. Just 255 signed longs. Not a problem.
  18816. var crcTable = makeTable();
  18817. function crc32(crc, buf, len, pos) {
  18818. var t = crcTable
  18819. , end = pos + len;
  18820. crc = crc ^ (-1);
  18821. for (var i = pos; i < end; i++ ) {
  18822. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  18823. }
  18824. return (crc ^ (-1)); // >>> 0;
  18825. }
  18826. module.exports = crc32;
  18827. },{}],72:[function(require,module,exports){
  18828. 'use strict';
  18829. var utils = require('../utils/common');
  18830. var trees = require('./trees');
  18831. var adler32 = require('./adler32');
  18832. var crc32 = require('./crc32');
  18833. var msg = require('./messages');
  18834. /* Public constants ==========================================================*/
  18835. /* ===========================================================================*/
  18836. /* Allowed flush values; see deflate() and inflate() below for details */
  18837. var Z_NO_FLUSH = 0;
  18838. var Z_PARTIAL_FLUSH = 1;
  18839. //var Z_SYNC_FLUSH = 2;
  18840. var Z_FULL_FLUSH = 3;
  18841. var Z_FINISH = 4;
  18842. var Z_BLOCK = 5;
  18843. //var Z_TREES = 6;
  18844. /* Return codes for the compression/decompression functions. Negative values
  18845. * are errors, positive values are used for special but normal events.
  18846. */
  18847. var Z_OK = 0;
  18848. var Z_STREAM_END = 1;
  18849. //var Z_NEED_DICT = 2;
  18850. //var Z_ERRNO = -1;
  18851. var Z_STREAM_ERROR = -2;
  18852. var Z_DATA_ERROR = -3;
  18853. //var Z_MEM_ERROR = -4;
  18854. var Z_BUF_ERROR = -5;
  18855. //var Z_VERSION_ERROR = -6;
  18856. /* compression levels */
  18857. //var Z_NO_COMPRESSION = 0;
  18858. //var Z_BEST_SPEED = 1;
  18859. //var Z_BEST_COMPRESSION = 9;
  18860. var Z_DEFAULT_COMPRESSION = -1;
  18861. var Z_FILTERED = 1;
  18862. var Z_HUFFMAN_ONLY = 2;
  18863. var Z_RLE = 3;
  18864. var Z_FIXED = 4;
  18865. var Z_DEFAULT_STRATEGY = 0;
  18866. /* Possible values of the data_type field (though see inflate()) */
  18867. //var Z_BINARY = 0;
  18868. //var Z_TEXT = 1;
  18869. //var Z_ASCII = 1; // = Z_TEXT
  18870. var Z_UNKNOWN = 2;
  18871. /* The deflate compression method */
  18872. var Z_DEFLATED = 8;
  18873. /*============================================================================*/
  18874. var MAX_MEM_LEVEL = 9;
  18875. /* Maximum value for memLevel in deflateInit2 */
  18876. var MAX_WBITS = 15;
  18877. /* 32K LZ77 window */
  18878. var DEF_MEM_LEVEL = 8;
  18879. var LENGTH_CODES = 29;
  18880. /* number of length codes, not counting the special END_BLOCK code */
  18881. var LITERALS = 256;
  18882. /* number of literal bytes 0..255 */
  18883. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18884. /* number of Literal or Length codes, including the END_BLOCK code */
  18885. var D_CODES = 30;
  18886. /* number of distance codes */
  18887. var BL_CODES = 19;
  18888. /* number of codes used to transfer the bit lengths */
  18889. var HEAP_SIZE = 2*L_CODES + 1;
  18890. /* maximum heap size */
  18891. var MAX_BITS = 15;
  18892. /* All codes must not exceed MAX_BITS bits */
  18893. var MIN_MATCH = 3;
  18894. var MAX_MATCH = 258;
  18895. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  18896. var PRESET_DICT = 0x20;
  18897. var INIT_STATE = 42;
  18898. var EXTRA_STATE = 69;
  18899. var NAME_STATE = 73;
  18900. var COMMENT_STATE = 91;
  18901. var HCRC_STATE = 103;
  18902. var BUSY_STATE = 113;
  18903. var FINISH_STATE = 666;
  18904. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  18905. var BS_BLOCK_DONE = 2; /* block flush performed */
  18906. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  18907. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  18908. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  18909. function err(strm, errorCode) {
  18910. strm.msg = msg[errorCode];
  18911. return errorCode;
  18912. }
  18913. function rank(f) {
  18914. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  18915. }
  18916. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18917. /* =========================================================================
  18918. * Flush as much pending output as possible. All deflate() output goes
  18919. * through this function so some applications may wish to modify it
  18920. * to avoid allocating a large strm->output buffer and copying into it.
  18921. * (See also read_buf()).
  18922. */
  18923. function flush_pending(strm) {
  18924. var s = strm.state;
  18925. //_tr_flush_bits(s);
  18926. var len = s.pending;
  18927. if (len > strm.avail_out) {
  18928. len = strm.avail_out;
  18929. }
  18930. if (len === 0) { return; }
  18931. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  18932. strm.next_out += len;
  18933. s.pending_out += len;
  18934. strm.total_out += len;
  18935. strm.avail_out -= len;
  18936. s.pending -= len;
  18937. if (s.pending === 0) {
  18938. s.pending_out = 0;
  18939. }
  18940. }
  18941. function flush_block_only (s, last) {
  18942. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  18943. s.block_start = s.strstart;
  18944. flush_pending(s.strm);
  18945. }
  18946. function put_byte(s, b) {
  18947. s.pending_buf[s.pending++] = b;
  18948. }
  18949. /* =========================================================================
  18950. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  18951. * IN assertion: the stream state is correct and there is enough room in
  18952. * pending_buf.
  18953. */
  18954. function putShortMSB(s, b) {
  18955. // put_byte(s, (Byte)(b >> 8));
  18956. // put_byte(s, (Byte)(b & 0xff));
  18957. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  18958. s.pending_buf[s.pending++] = b & 0xff;
  18959. }
  18960. /* ===========================================================================
  18961. * Read a new buffer from the current input stream, update the adler32
  18962. * and total number of bytes read. All deflate() input goes through
  18963. * this function so some applications may wish to modify it to avoid
  18964. * allocating a large strm->input buffer and copying from it.
  18965. * (See also flush_pending()).
  18966. */
  18967. function read_buf(strm, buf, start, size) {
  18968. var len = strm.avail_in;
  18969. if (len > size) { len = size; }
  18970. if (len === 0) { return 0; }
  18971. strm.avail_in -= len;
  18972. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  18973. if (strm.state.wrap === 1) {
  18974. strm.adler = adler32(strm.adler, buf, len, start);
  18975. }
  18976. else if (strm.state.wrap === 2) {
  18977. strm.adler = crc32(strm.adler, buf, len, start);
  18978. }
  18979. strm.next_in += len;
  18980. strm.total_in += len;
  18981. return len;
  18982. }
  18983. /* ===========================================================================
  18984. * Set match_start to the longest match starting at the given string and
  18985. * return its length. Matches shorter or equal to prev_length are discarded,
  18986. * in which case the result is equal to prev_length and match_start is
  18987. * garbage.
  18988. * IN assertions: cur_match is the head of the hash chain for the current
  18989. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  18990. * OUT assertion: the match length is not greater than s->lookahead.
  18991. */
  18992. function longest_match(s, cur_match) {
  18993. var chain_length = s.max_chain_length; /* max hash chain length */
  18994. var scan = s.strstart; /* current string */
  18995. var match; /* matched string */
  18996. var len; /* length of current match */
  18997. var best_len = s.prev_length; /* best match length so far */
  18998. var nice_match = s.nice_match; /* stop if match long enough */
  18999. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  19000. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  19001. var _win = s.window; // shortcut
  19002. var wmask = s.w_mask;
  19003. var prev = s.prev;
  19004. /* Stop when cur_match becomes <= limit. To simplify the code,
  19005. * we prevent matches with the string of window index 0.
  19006. */
  19007. var strend = s.strstart + MAX_MATCH;
  19008. var scan_end1 = _win[scan + best_len - 1];
  19009. var scan_end = _win[scan + best_len];
  19010. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  19011. * It is easy to get rid of this optimization if necessary.
  19012. */
  19013. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  19014. /* Do not waste too much time if we already have a good match: */
  19015. if (s.prev_length >= s.good_match) {
  19016. chain_length >>= 2;
  19017. }
  19018. /* Do not look for matches beyond the end of the input. This is necessary
  19019. * to make deflate deterministic.
  19020. */
  19021. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  19022. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  19023. do {
  19024. // Assert(cur_match < s->strstart, "no future");
  19025. match = cur_match;
  19026. /* Skip to next match if the match length cannot increase
  19027. * or if the match length is less than 2. Note that the checks below
  19028. * for insufficient lookahead only occur occasionally for performance
  19029. * reasons. Therefore uninitialized memory will be accessed, and
  19030. * conditional jumps will be made that depend on those values.
  19031. * However the length of the match is limited to the lookahead, so
  19032. * the output of deflate is not affected by the uninitialized values.
  19033. */
  19034. if (_win[match + best_len] !== scan_end ||
  19035. _win[match + best_len - 1] !== scan_end1 ||
  19036. _win[match] !== _win[scan] ||
  19037. _win[++match] !== _win[scan + 1]) {
  19038. continue;
  19039. }
  19040. /* The check at best_len-1 can be removed because it will be made
  19041. * again later. (This heuristic is not always a win.)
  19042. * It is not necessary to compare scan[2] and match[2] since they
  19043. * are always equal when the other bytes match, given that
  19044. * the hash keys are equal and that HASH_BITS >= 8.
  19045. */
  19046. scan += 2;
  19047. match++;
  19048. // Assert(*scan == *match, "match[2]?");
  19049. /* We check for insufficient lookahead only every 8th comparison;
  19050. * the 256th check will be made at strstart+258.
  19051. */
  19052. do {
  19053. /*jshint noempty:false*/
  19054. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19055. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19056. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19057. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19058. scan < strend);
  19059. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  19060. len = MAX_MATCH - (strend - scan);
  19061. scan = strend - MAX_MATCH;
  19062. if (len > best_len) {
  19063. s.match_start = cur_match;
  19064. best_len = len;
  19065. if (len >= nice_match) {
  19066. break;
  19067. }
  19068. scan_end1 = _win[scan + best_len - 1];
  19069. scan_end = _win[scan + best_len];
  19070. }
  19071. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  19072. if (best_len <= s.lookahead) {
  19073. return best_len;
  19074. }
  19075. return s.lookahead;
  19076. }
  19077. /* ===========================================================================
  19078. * Fill the window when the lookahead becomes insufficient.
  19079. * Updates strstart and lookahead.
  19080. *
  19081. * IN assertion: lookahead < MIN_LOOKAHEAD
  19082. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  19083. * At least one byte has been read, or avail_in == 0; reads are
  19084. * performed for at least two bytes (required for the zip translate_eol
  19085. * option -- not supported here).
  19086. */
  19087. function fill_window(s) {
  19088. var _w_size = s.w_size;
  19089. var p, n, m, more, str;
  19090. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  19091. do {
  19092. more = s.window_size - s.lookahead - s.strstart;
  19093. // JS ints have 32 bit, block below not needed
  19094. /* Deal with !@#$% 64K limit: */
  19095. //if (sizeof(int) <= 2) {
  19096. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  19097. // more = wsize;
  19098. //
  19099. // } else if (more == (unsigned)(-1)) {
  19100. // /* Very unlikely, but possible on 16 bit machine if
  19101. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  19102. // */
  19103. // more--;
  19104. // }
  19105. //}
  19106. /* If the window is almost full and there is insufficient lookahead,
  19107. * move the upper half to the lower one to make room in the upper half.
  19108. */
  19109. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  19110. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  19111. s.match_start -= _w_size;
  19112. s.strstart -= _w_size;
  19113. /* we now have strstart >= MAX_DIST */
  19114. s.block_start -= _w_size;
  19115. /* Slide the hash table (could be avoided with 32 bit values
  19116. at the expense of memory usage). We slide even when level == 0
  19117. to keep the hash table consistent if we switch back to level > 0
  19118. later. (Using level 0 permanently is not an optimal usage of
  19119. zlib, so we don't care about this pathological case.)
  19120. */
  19121. n = s.hash_size;
  19122. p = n;
  19123. do {
  19124. m = s.head[--p];
  19125. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  19126. } while (--n);
  19127. n = _w_size;
  19128. p = n;
  19129. do {
  19130. m = s.prev[--p];
  19131. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  19132. /* If n is not on any hash chain, prev[n] is garbage but
  19133. * its value will never be used.
  19134. */
  19135. } while (--n);
  19136. more += _w_size;
  19137. }
  19138. if (s.strm.avail_in === 0) {
  19139. break;
  19140. }
  19141. /* If there was no sliding:
  19142. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  19143. * more == window_size - lookahead - strstart
  19144. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  19145. * => more >= window_size - 2*WSIZE + 2
  19146. * In the BIG_MEM or MMAP case (not yet supported),
  19147. * window_size == input_size + MIN_LOOKAHEAD &&
  19148. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  19149. * Otherwise, window_size == 2*WSIZE so more >= 2.
  19150. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  19151. */
  19152. //Assert(more >= 2, "more < 2");
  19153. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  19154. s.lookahead += n;
  19155. /* Initialize the hash value now that we have some input: */
  19156. if (s.lookahead + s.insert >= MIN_MATCH) {
  19157. str = s.strstart - s.insert;
  19158. s.ins_h = s.window[str];
  19159. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  19160. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  19161. //#if MIN_MATCH != 3
  19162. // Call update_hash() MIN_MATCH-3 more times
  19163. //#endif
  19164. while (s.insert) {
  19165. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  19166. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  19167. s.prev[str & s.w_mask] = s.head[s.ins_h];
  19168. s.head[s.ins_h] = str;
  19169. str++;
  19170. s.insert--;
  19171. if (s.lookahead + s.insert < MIN_MATCH) {
  19172. break;
  19173. }
  19174. }
  19175. }
  19176. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  19177. * but this is not important since only literal bytes will be emitted.
  19178. */
  19179. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  19180. /* If the WIN_INIT bytes after the end of the current data have never been
  19181. * written, then zero those bytes in order to avoid memory check reports of
  19182. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  19183. * the longest match routines. Update the high water mark for the next
  19184. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  19185. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  19186. */
  19187. // if (s.high_water < s.window_size) {
  19188. // var curr = s.strstart + s.lookahead;
  19189. // var init = 0;
  19190. //
  19191. // if (s.high_water < curr) {
  19192. // /* Previous high water mark below current data -- zero WIN_INIT
  19193. // * bytes or up to end of window, whichever is less.
  19194. // */
  19195. // init = s.window_size - curr;
  19196. // if (init > WIN_INIT)
  19197. // init = WIN_INIT;
  19198. // zmemzero(s->window + curr, (unsigned)init);
  19199. // s->high_water = curr + init;
  19200. // }
  19201. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  19202. // /* High water mark at or above current data, but below current data
  19203. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  19204. // * to end of window, whichever is less.
  19205. // */
  19206. // init = (ulg)curr + WIN_INIT - s->high_water;
  19207. // if (init > s->window_size - s->high_water)
  19208. // init = s->window_size - s->high_water;
  19209. // zmemzero(s->window + s->high_water, (unsigned)init);
  19210. // s->high_water += init;
  19211. // }
  19212. // }
  19213. //
  19214. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  19215. // "not enough room for search");
  19216. }
  19217. /* ===========================================================================
  19218. * Copy without compression as much as possible from the input stream, return
  19219. * the current block state.
  19220. * This function does not insert new strings in the dictionary since
  19221. * uncompressible data is probably not useful. This function is used
  19222. * only for the level=0 compression option.
  19223. * NOTE: this function should be optimized to avoid extra copying from
  19224. * window to pending_buf.
  19225. */
  19226. function deflate_stored(s, flush) {
  19227. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  19228. * to pending_buf_size, and each stored block has a 5 byte header:
  19229. */
  19230. var max_block_size = 0xffff;
  19231. if (max_block_size > s.pending_buf_size - 5) {
  19232. max_block_size = s.pending_buf_size - 5;
  19233. }
  19234. /* Copy as much as possible from input to output: */
  19235. for (;;) {
  19236. /* Fill the window as much as possible: */
  19237. if (s.lookahead <= 1) {
  19238. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  19239. // s->block_start >= (long)s->w_size, "slide too late");
  19240. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  19241. // s.block_start >= s.w_size)) {
  19242. // throw new Error("slide too late");
  19243. // }
  19244. fill_window(s);
  19245. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  19246. return BS_NEED_MORE;
  19247. }
  19248. if (s.lookahead === 0) {
  19249. break;
  19250. }
  19251. /* flush the current block */
  19252. }
  19253. //Assert(s->block_start >= 0L, "block gone");
  19254. // if (s.block_start < 0) throw new Error("block gone");
  19255. s.strstart += s.lookahead;
  19256. s.lookahead = 0;
  19257. /* Emit a stored block if pending_buf will be full: */
  19258. var max_start = s.block_start + max_block_size;
  19259. if (s.strstart === 0 || s.strstart >= max_start) {
  19260. /* strstart == 0 is possible when wraparound on 16-bit machine */
  19261. s.lookahead = s.strstart - max_start;
  19262. s.strstart = max_start;
  19263. /*** FLUSH_BLOCK(s, 0); ***/
  19264. flush_block_only(s, false);
  19265. if (s.strm.avail_out === 0) {
  19266. return BS_NEED_MORE;
  19267. }
  19268. /***/
  19269. }
  19270. /* Flush if we may have to slide, otherwise block_start may become
  19271. * negative and the data will be gone:
  19272. */
  19273. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  19274. /*** FLUSH_BLOCK(s, 0); ***/
  19275. flush_block_only(s, false);
  19276. if (s.strm.avail_out === 0) {
  19277. return BS_NEED_MORE;
  19278. }
  19279. /***/
  19280. }
  19281. }
  19282. s.insert = 0;
  19283. if (flush === Z_FINISH) {
  19284. /*** FLUSH_BLOCK(s, 1); ***/
  19285. flush_block_only(s, true);
  19286. if (s.strm.avail_out === 0) {
  19287. return BS_FINISH_STARTED;
  19288. }
  19289. /***/
  19290. return BS_FINISH_DONE;
  19291. }
  19292. if (s.strstart > s.block_start) {
  19293. /*** FLUSH_BLOCK(s, 0); ***/
  19294. flush_block_only(s, false);
  19295. if (s.strm.avail_out === 0) {
  19296. return BS_NEED_MORE;
  19297. }
  19298. /***/
  19299. }
  19300. return BS_NEED_MORE;
  19301. }
  19302. /* ===========================================================================
  19303. * Compress as much as possible from the input stream, return the current
  19304. * block state.
  19305. * This function does not perform lazy evaluation of matches and inserts
  19306. * new strings in the dictionary only for unmatched strings or for short
  19307. * matches. It is used only for the fast compression options.
  19308. */
  19309. function deflate_fast(s, flush) {
  19310. var hash_head; /* head of the hash chain */
  19311. var bflush; /* set if current block must be flushed */
  19312. for (;;) {
  19313. /* Make sure that we always have enough lookahead, except
  19314. * at the end of the input file. We need MAX_MATCH bytes
  19315. * for the next match, plus MIN_MATCH bytes to insert the
  19316. * string following the next match.
  19317. */
  19318. if (s.lookahead < MIN_LOOKAHEAD) {
  19319. fill_window(s);
  19320. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  19321. return BS_NEED_MORE;
  19322. }
  19323. if (s.lookahead === 0) {
  19324. break; /* flush the current block */
  19325. }
  19326. }
  19327. /* Insert the string window[strstart .. strstart+2] in the
  19328. * dictionary, and set hash_head to the head of the hash chain:
  19329. */
  19330. hash_head = 0/*NIL*/;
  19331. if (s.lookahead >= MIN_MATCH) {
  19332. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19333. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19334. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19335. s.head[s.ins_h] = s.strstart;
  19336. /***/
  19337. }
  19338. /* Find the longest match, discarding those <= prev_length.
  19339. * At this point we have always match_length < MIN_MATCH
  19340. */
  19341. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  19342. /* To simplify the code, we prevent matches with the string
  19343. * of window index 0 (in particular we have to avoid a match
  19344. * of the string with itself at the start of the input file).
  19345. */
  19346. s.match_length = longest_match(s, hash_head);
  19347. /* longest_match() sets match_start */
  19348. }
  19349. if (s.match_length >= MIN_MATCH) {
  19350. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  19351. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  19352. s.match_length - MIN_MATCH, bflush); ***/
  19353. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  19354. s.lookahead -= s.match_length;
  19355. /* Insert new strings in the hash table only if the match length
  19356. * is not too large. This saves time but degrades compression.
  19357. */
  19358. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  19359. s.match_length--; /* string at strstart already in table */
  19360. do {
  19361. s.strstart++;
  19362. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19363. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19364. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19365. s.head[s.ins_h] = s.strstart;
  19366. /***/
  19367. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  19368. * always MIN_MATCH bytes ahead.
  19369. */
  19370. } while (--s.match_length !== 0);
  19371. s.strstart++;
  19372. } else
  19373. {
  19374. s.strstart += s.match_length;
  19375. s.match_length = 0;
  19376. s.ins_h = s.window[s.strstart];
  19377. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  19378. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  19379. //#if MIN_MATCH != 3
  19380. // Call UPDATE_HASH() MIN_MATCH-3 more times
  19381. //#endif
  19382. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  19383. * matter since it will be recomputed at next deflate call.
  19384. */
  19385. }
  19386. } else {
  19387. /* No match, output a literal byte */
  19388. //Tracevv((stderr,"%c", s.window[s.strstart]));
  19389. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  19390. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  19391. s.lookahead--;
  19392. s.strstart++;
  19393. }
  19394. if (bflush) {
  19395. /*** FLUSH_BLOCK(s, 0); ***/
  19396. flush_block_only(s, false);
  19397. if (s.strm.avail_out === 0) {
  19398. return BS_NEED_MORE;
  19399. }
  19400. /***/
  19401. }
  19402. }
  19403. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  19404. if (flush === Z_FINISH) {
  19405. /*** FLUSH_BLOCK(s, 1); ***/
  19406. flush_block_only(s, true);
  19407. if (s.strm.avail_out === 0) {
  19408. return BS_FINISH_STARTED;
  19409. }
  19410. /***/
  19411. return BS_FINISH_DONE;
  19412. }
  19413. if (s.last_lit) {
  19414. /*** FLUSH_BLOCK(s, 0); ***/
  19415. flush_block_only(s, false);
  19416. if (s.strm.avail_out === 0) {
  19417. return BS_NEED_MORE;
  19418. }
  19419. /***/
  19420. }
  19421. return BS_BLOCK_DONE;
  19422. }
  19423. /* ===========================================================================
  19424. * Same as above, but achieves better compression. We use a lazy
  19425. * evaluation for matches: a match is finally adopted only if there is
  19426. * no better match at the next window position.
  19427. */
  19428. function deflate_slow(s, flush) {
  19429. var hash_head; /* head of hash chain */
  19430. var bflush; /* set if current block must be flushed */
  19431. var max_insert;
  19432. /* Process the input block. */
  19433. for (;;) {
  19434. /* Make sure that we always have enough lookahead, except
  19435. * at the end of the input file. We need MAX_MATCH bytes
  19436. * for the next match, plus MIN_MATCH bytes to insert the
  19437. * string following the next match.
  19438. */
  19439. if (s.lookahead < MIN_LOOKAHEAD) {
  19440. fill_window(s);
  19441. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  19442. return BS_NEED_MORE;
  19443. }
  19444. if (s.lookahead === 0) { break; } /* flush the current block */
  19445. }
  19446. /* Insert the string window[strstart .. strstart+2] in the
  19447. * dictionary, and set hash_head to the head of the hash chain:
  19448. */
  19449. hash_head = 0/*NIL*/;
  19450. if (s.lookahead >= MIN_MATCH) {
  19451. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19452. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19453. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19454. s.head[s.ins_h] = s.strstart;
  19455. /***/
  19456. }
  19457. /* Find the longest match, discarding those <= prev_length.
  19458. */
  19459. s.prev_length = s.match_length;
  19460. s.prev_match = s.match_start;
  19461. s.match_length = MIN_MATCH-1;
  19462. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  19463. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  19464. /* To simplify the code, we prevent matches with the string
  19465. * of window index 0 (in particular we have to avoid a match
  19466. * of the string with itself at the start of the input file).
  19467. */
  19468. s.match_length = longest_match(s, hash_head);
  19469. /* longest_match() sets match_start */
  19470. if (s.match_length <= 5 &&
  19471. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  19472. /* If prev_match is also MIN_MATCH, match_start is garbage
  19473. * but we will ignore the current match anyway.
  19474. */
  19475. s.match_length = MIN_MATCH-1;
  19476. }
  19477. }
  19478. /* If there was a match at the previous step and the current
  19479. * match is not better, output the previous match:
  19480. */
  19481. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  19482. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  19483. /* Do not insert strings in hash table beyond this. */
  19484. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  19485. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  19486. s.prev_length - MIN_MATCH, bflush);***/
  19487. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  19488. /* Insert in hash table all strings up to the end of the match.
  19489. * strstart-1 and strstart are already inserted. If there is not
  19490. * enough lookahead, the last two strings are not inserted in
  19491. * the hash table.
  19492. */
  19493. s.lookahead -= s.prev_length-1;
  19494. s.prev_length -= 2;
  19495. do {
  19496. if (++s.strstart <= max_insert) {
  19497. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  19498. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  19499. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  19500. s.head[s.ins_h] = s.strstart;
  19501. /***/
  19502. }
  19503. } while (--s.prev_length !== 0);
  19504. s.match_available = 0;
  19505. s.match_length = MIN_MATCH-1;
  19506. s.strstart++;
  19507. if (bflush) {
  19508. /*** FLUSH_BLOCK(s, 0); ***/
  19509. flush_block_only(s, false);
  19510. if (s.strm.avail_out === 0) {
  19511. return BS_NEED_MORE;
  19512. }
  19513. /***/
  19514. }
  19515. } else if (s.match_available) {
  19516. /* If there was no match at the previous position, output a
  19517. * single literal. If there was a match but the current match
  19518. * is longer, truncate the previous match to a single literal.
  19519. */
  19520. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  19521. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  19522. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  19523. if (bflush) {
  19524. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  19525. flush_block_only(s, false);
  19526. /***/
  19527. }
  19528. s.strstart++;
  19529. s.lookahead--;
  19530. if (s.strm.avail_out === 0) {
  19531. return BS_NEED_MORE;
  19532. }
  19533. } else {
  19534. /* There is no previous match to compare with, wait for
  19535. * the next step to decide.
  19536. */
  19537. s.match_available = 1;
  19538. s.strstart++;
  19539. s.lookahead--;
  19540. }
  19541. }
  19542. //Assert (flush != Z_NO_FLUSH, "no flush?");
  19543. if (s.match_available) {
  19544. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  19545. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  19546. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  19547. s.match_available = 0;
  19548. }
  19549. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  19550. if (flush === Z_FINISH) {
  19551. /*** FLUSH_BLOCK(s, 1); ***/
  19552. flush_block_only(s, true);
  19553. if (s.strm.avail_out === 0) {
  19554. return BS_FINISH_STARTED;
  19555. }
  19556. /***/
  19557. return BS_FINISH_DONE;
  19558. }
  19559. if (s.last_lit) {
  19560. /*** FLUSH_BLOCK(s, 0); ***/
  19561. flush_block_only(s, false);
  19562. if (s.strm.avail_out === 0) {
  19563. return BS_NEED_MORE;
  19564. }
  19565. /***/
  19566. }
  19567. return BS_BLOCK_DONE;
  19568. }
  19569. /* ===========================================================================
  19570. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  19571. * one. Do not maintain a hash table. (It will be regenerated if this run of
  19572. * deflate switches away from Z_RLE.)
  19573. */
  19574. function deflate_rle(s, flush) {
  19575. var bflush; /* set if current block must be flushed */
  19576. var prev; /* byte at distance one to match */
  19577. var scan, strend; /* scan goes up to strend for length of run */
  19578. var _win = s.window;
  19579. for (;;) {
  19580. /* Make sure that we always have enough lookahead, except
  19581. * at the end of the input file. We need MAX_MATCH bytes
  19582. * for the longest run, plus one for the unrolled loop.
  19583. */
  19584. if (s.lookahead <= MAX_MATCH) {
  19585. fill_window(s);
  19586. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  19587. return BS_NEED_MORE;
  19588. }
  19589. if (s.lookahead === 0) { break; } /* flush the current block */
  19590. }
  19591. /* See how many times the previous byte repeats */
  19592. s.match_length = 0;
  19593. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  19594. scan = s.strstart - 1;
  19595. prev = _win[scan];
  19596. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  19597. strend = s.strstart + MAX_MATCH;
  19598. do {
  19599. /*jshint noempty:false*/
  19600. } while (prev === _win[++scan] && prev === _win[++scan] &&
  19601. prev === _win[++scan] && prev === _win[++scan] &&
  19602. prev === _win[++scan] && prev === _win[++scan] &&
  19603. prev === _win[++scan] && prev === _win[++scan] &&
  19604. scan < strend);
  19605. s.match_length = MAX_MATCH - (strend - scan);
  19606. if (s.match_length > s.lookahead) {
  19607. s.match_length = s.lookahead;
  19608. }
  19609. }
  19610. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  19611. }
  19612. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  19613. if (s.match_length >= MIN_MATCH) {
  19614. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  19615. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  19616. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  19617. s.lookahead -= s.match_length;
  19618. s.strstart += s.match_length;
  19619. s.match_length = 0;
  19620. } else {
  19621. /* No match, output a literal byte */
  19622. //Tracevv((stderr,"%c", s->window[s->strstart]));
  19623. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  19624. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  19625. s.lookahead--;
  19626. s.strstart++;
  19627. }
  19628. if (bflush) {
  19629. /*** FLUSH_BLOCK(s, 0); ***/
  19630. flush_block_only(s, false);
  19631. if (s.strm.avail_out === 0) {
  19632. return BS_NEED_MORE;
  19633. }
  19634. /***/
  19635. }
  19636. }
  19637. s.insert = 0;
  19638. if (flush === Z_FINISH) {
  19639. /*** FLUSH_BLOCK(s, 1); ***/
  19640. flush_block_only(s, true);
  19641. if (s.strm.avail_out === 0) {
  19642. return BS_FINISH_STARTED;
  19643. }
  19644. /***/
  19645. return BS_FINISH_DONE;
  19646. }
  19647. if (s.last_lit) {
  19648. /*** FLUSH_BLOCK(s, 0); ***/
  19649. flush_block_only(s, false);
  19650. if (s.strm.avail_out === 0) {
  19651. return BS_NEED_MORE;
  19652. }
  19653. /***/
  19654. }
  19655. return BS_BLOCK_DONE;
  19656. }
  19657. /* ===========================================================================
  19658. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  19659. * (It will be regenerated if this run of deflate switches away from Huffman.)
  19660. */
  19661. function deflate_huff(s, flush) {
  19662. var bflush; /* set if current block must be flushed */
  19663. for (;;) {
  19664. /* Make sure that we have a literal to write. */
  19665. if (s.lookahead === 0) {
  19666. fill_window(s);
  19667. if (s.lookahead === 0) {
  19668. if (flush === Z_NO_FLUSH) {
  19669. return BS_NEED_MORE;
  19670. }
  19671. break; /* flush the current block */
  19672. }
  19673. }
  19674. /* Output a literal byte */
  19675. s.match_length = 0;
  19676. //Tracevv((stderr,"%c", s->window[s->strstart]));
  19677. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  19678. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  19679. s.lookahead--;
  19680. s.strstart++;
  19681. if (bflush) {
  19682. /*** FLUSH_BLOCK(s, 0); ***/
  19683. flush_block_only(s, false);
  19684. if (s.strm.avail_out === 0) {
  19685. return BS_NEED_MORE;
  19686. }
  19687. /***/
  19688. }
  19689. }
  19690. s.insert = 0;
  19691. if (flush === Z_FINISH) {
  19692. /*** FLUSH_BLOCK(s, 1); ***/
  19693. flush_block_only(s, true);
  19694. if (s.strm.avail_out === 0) {
  19695. return BS_FINISH_STARTED;
  19696. }
  19697. /***/
  19698. return BS_FINISH_DONE;
  19699. }
  19700. if (s.last_lit) {
  19701. /*** FLUSH_BLOCK(s, 0); ***/
  19702. flush_block_only(s, false);
  19703. if (s.strm.avail_out === 0) {
  19704. return BS_NEED_MORE;
  19705. }
  19706. /***/
  19707. }
  19708. return BS_BLOCK_DONE;
  19709. }
  19710. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  19711. * the desired pack level (0..9). The values given below have been tuned to
  19712. * exclude worst case performance for pathological files. Better values may be
  19713. * found for specific files.
  19714. */
  19715. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  19716. this.good_length = good_length;
  19717. this.max_lazy = max_lazy;
  19718. this.nice_length = nice_length;
  19719. this.max_chain = max_chain;
  19720. this.func = func;
  19721. };
  19722. var configuration_table;
  19723. configuration_table = [
  19724. /* good lazy nice chain */
  19725. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  19726. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  19727. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  19728. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  19729. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  19730. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  19731. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  19732. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  19733. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  19734. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  19735. ];
  19736. /* ===========================================================================
  19737. * Initialize the "longest match" routines for a new zlib stream
  19738. */
  19739. function lm_init(s) {
  19740. s.window_size = 2 * s.w_size;
  19741. /*** CLEAR_HASH(s); ***/
  19742. zero(s.head); // Fill with NIL (= 0);
  19743. /* Set the default configuration parameters:
  19744. */
  19745. s.max_lazy_match = configuration_table[s.level].max_lazy;
  19746. s.good_match = configuration_table[s.level].good_length;
  19747. s.nice_match = configuration_table[s.level].nice_length;
  19748. s.max_chain_length = configuration_table[s.level].max_chain;
  19749. s.strstart = 0;
  19750. s.block_start = 0;
  19751. s.lookahead = 0;
  19752. s.insert = 0;
  19753. s.match_length = s.prev_length = MIN_MATCH - 1;
  19754. s.match_available = 0;
  19755. s.ins_h = 0;
  19756. }
  19757. function DeflateState() {
  19758. this.strm = null; /* pointer back to this zlib stream */
  19759. this.status = 0; /* as the name implies */
  19760. this.pending_buf = null; /* output still pending */
  19761. this.pending_buf_size = 0; /* size of pending_buf */
  19762. this.pending_out = 0; /* next pending byte to output to the stream */
  19763. this.pending = 0; /* nb of bytes in the pending buffer */
  19764. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19765. this.gzhead = null; /* gzip header information to write */
  19766. this.gzindex = 0; /* where in extra, name, or comment */
  19767. this.method = Z_DEFLATED; /* can only be DEFLATED */
  19768. this.last_flush = -1; /* value of flush param for previous deflate call */
  19769. this.w_size = 0; /* LZ77 window size (32K by default) */
  19770. this.w_bits = 0; /* log2(w_size) (8..16) */
  19771. this.w_mask = 0; /* w_size - 1 */
  19772. this.window = null;
  19773. /* Sliding window. Input bytes are read into the second half of the window,
  19774. * and move to the first half later to keep a dictionary of at least wSize
  19775. * bytes. With this organization, matches are limited to a distance of
  19776. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  19777. * performed with a length multiple of the block size.
  19778. */
  19779. this.window_size = 0;
  19780. /* Actual size of window: 2*wSize, except when the user input buffer
  19781. * is directly used as sliding window.
  19782. */
  19783. this.prev = null;
  19784. /* Link to older string with same hash index. To limit the size of this
  19785. * array to 64K, this link is maintained only for the last 32K strings.
  19786. * An index in this array is thus a window index modulo 32K.
  19787. */
  19788. this.head = null; /* Heads of the hash chains or NIL. */
  19789. this.ins_h = 0; /* hash index of string to be inserted */
  19790. this.hash_size = 0; /* number of elements in hash table */
  19791. this.hash_bits = 0; /* log2(hash_size) */
  19792. this.hash_mask = 0; /* hash_size-1 */
  19793. this.hash_shift = 0;
  19794. /* Number of bits by which ins_h must be shifted at each input
  19795. * step. It must be such that after MIN_MATCH steps, the oldest
  19796. * byte no longer takes part in the hash key, that is:
  19797. * hash_shift * MIN_MATCH >= hash_bits
  19798. */
  19799. this.block_start = 0;
  19800. /* Window position at the beginning of the current output block. Gets
  19801. * negative when the window is moved backwards.
  19802. */
  19803. this.match_length = 0; /* length of best match */
  19804. this.prev_match = 0; /* previous match */
  19805. this.match_available = 0; /* set if previous match exists */
  19806. this.strstart = 0; /* start of string to insert */
  19807. this.match_start = 0; /* start of matching string */
  19808. this.lookahead = 0; /* number of valid bytes ahead in window */
  19809. this.prev_length = 0;
  19810. /* Length of the best match at previous step. Matches not greater than this
  19811. * are discarded. This is used in the lazy match evaluation.
  19812. */
  19813. this.max_chain_length = 0;
  19814. /* To speed up deflation, hash chains are never searched beyond this
  19815. * length. A higher limit improves compression ratio but degrades the
  19816. * speed.
  19817. */
  19818. this.max_lazy_match = 0;
  19819. /* Attempt to find a better match only when the current match is strictly
  19820. * smaller than this value. This mechanism is used only for compression
  19821. * levels >= 4.
  19822. */
  19823. // That's alias to max_lazy_match, don't use directly
  19824. //this.max_insert_length = 0;
  19825. /* Insert new strings in the hash table only if the match length is not
  19826. * greater than this length. This saves time but degrades compression.
  19827. * max_insert_length is used only for compression levels <= 3.
  19828. */
  19829. this.level = 0; /* compression level (1..9) */
  19830. this.strategy = 0; /* favor or force Huffman coding*/
  19831. this.good_match = 0;
  19832. /* Use a faster search when the previous match is longer than this */
  19833. this.nice_match = 0; /* Stop searching when current match exceeds this */
  19834. /* used by trees.c: */
  19835. /* Didn't use ct_data typedef below to suppress compiler warning */
  19836. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  19837. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  19838. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  19839. // Use flat array of DOUBLE size, with interleaved fata,
  19840. // because JS does not support effective
  19841. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  19842. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  19843. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  19844. zero(this.dyn_ltree);
  19845. zero(this.dyn_dtree);
  19846. zero(this.bl_tree);
  19847. this.l_desc = null; /* desc. for literal tree */
  19848. this.d_desc = null; /* desc. for distance tree */
  19849. this.bl_desc = null; /* desc. for bit length tree */
  19850. //ush bl_count[MAX_BITS+1];
  19851. this.bl_count = new utils.Buf16(MAX_BITS+1);
  19852. /* number of codes at each bit length for an optimal tree */
  19853. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  19854. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  19855. zero(this.heap);
  19856. this.heap_len = 0; /* number of elements in the heap */
  19857. this.heap_max = 0; /* element of largest frequency */
  19858. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  19859. * The same heap array is used to build all trees.
  19860. */
  19861. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  19862. zero(this.depth);
  19863. /* Depth of each subtree used as tie breaker for trees of equal frequency
  19864. */
  19865. this.l_buf = 0; /* buffer index for literals or lengths */
  19866. this.lit_bufsize = 0;
  19867. /* Size of match buffer for literals/lengths. There are 4 reasons for
  19868. * limiting lit_bufsize to 64K:
  19869. * - frequencies can be kept in 16 bit counters
  19870. * - if compression is not successful for the first block, all input
  19871. * data is still in the window so we can still emit a stored block even
  19872. * when input comes from standard input. (This can also be done for
  19873. * all blocks if lit_bufsize is not greater than 32K.)
  19874. * - if compression is not successful for a file smaller than 64K, we can
  19875. * even emit a stored file instead of a stored block (saving 5 bytes).
  19876. * This is applicable only for zip (not gzip or zlib).
  19877. * - creating new Huffman trees less frequently may not provide fast
  19878. * adaptation to changes in the input data statistics. (Take for
  19879. * example a binary file with poorly compressible code followed by
  19880. * a highly compressible string table.) Smaller buffer sizes give
  19881. * fast adaptation but have of course the overhead of transmitting
  19882. * trees more frequently.
  19883. * - I can't count above 4
  19884. */
  19885. this.last_lit = 0; /* running index in l_buf */
  19886. this.d_buf = 0;
  19887. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  19888. * the same number of elements. To use different lengths, an extra flag
  19889. * array would be necessary.
  19890. */
  19891. this.opt_len = 0; /* bit length of current block with optimal trees */
  19892. this.static_len = 0; /* bit length of current block with static trees */
  19893. this.matches = 0; /* number of string matches in current block */
  19894. this.insert = 0; /* bytes at end of window left to insert */
  19895. this.bi_buf = 0;
  19896. /* Output buffer. bits are inserted starting at the bottom (least
  19897. * significant bits).
  19898. */
  19899. this.bi_valid = 0;
  19900. /* Number of valid bits in bi_buf. All bits above the last valid bit
  19901. * are always zero.
  19902. */
  19903. // Used for window memory init. We safely ignore it for JS. That makes
  19904. // sense only for pointers and memory check tools.
  19905. //this.high_water = 0;
  19906. /* High water mark offset in window for initialized bytes -- bytes above
  19907. * this are set to zero in order to avoid memory check warnings when
  19908. * longest match routines access bytes past the input. This is then
  19909. * updated to the new high water mark.
  19910. */
  19911. }
  19912. function deflateResetKeep(strm) {
  19913. var s;
  19914. if (!strm || !strm.state) {
  19915. return err(strm, Z_STREAM_ERROR);
  19916. }
  19917. strm.total_in = strm.total_out = 0;
  19918. strm.data_type = Z_UNKNOWN;
  19919. s = strm.state;
  19920. s.pending = 0;
  19921. s.pending_out = 0;
  19922. if (s.wrap < 0) {
  19923. s.wrap = -s.wrap;
  19924. /* was made negative by deflate(..., Z_FINISH); */
  19925. }
  19926. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  19927. strm.adler = (s.wrap === 2) ?
  19928. 0 // crc32(0, Z_NULL, 0)
  19929. :
  19930. 1; // adler32(0, Z_NULL, 0)
  19931. s.last_flush = Z_NO_FLUSH;
  19932. trees._tr_init(s);
  19933. return Z_OK;
  19934. }
  19935. function deflateReset(strm) {
  19936. var ret = deflateResetKeep(strm);
  19937. if (ret === Z_OK) {
  19938. lm_init(strm.state);
  19939. }
  19940. return ret;
  19941. }
  19942. function deflateSetHeader(strm, head) {
  19943. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19944. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  19945. strm.state.gzhead = head;
  19946. return Z_OK;
  19947. }
  19948. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  19949. if (!strm) { // === Z_NULL
  19950. return Z_STREAM_ERROR;
  19951. }
  19952. var wrap = 1;
  19953. if (level === Z_DEFAULT_COMPRESSION) {
  19954. level = 6;
  19955. }
  19956. if (windowBits < 0) { /* suppress zlib wrapper */
  19957. wrap = 0;
  19958. windowBits = -windowBits;
  19959. }
  19960. else if (windowBits > 15) {
  19961. wrap = 2; /* write gzip wrapper instead */
  19962. windowBits -= 16;
  19963. }
  19964. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  19965. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  19966. strategy < 0 || strategy > Z_FIXED) {
  19967. return err(strm, Z_STREAM_ERROR);
  19968. }
  19969. if (windowBits === 8) {
  19970. windowBits = 9;
  19971. }
  19972. /* until 256-byte window bug fixed */
  19973. var s = new DeflateState();
  19974. strm.state = s;
  19975. s.strm = strm;
  19976. s.wrap = wrap;
  19977. s.gzhead = null;
  19978. s.w_bits = windowBits;
  19979. s.w_size = 1 << s.w_bits;
  19980. s.w_mask = s.w_size - 1;
  19981. s.hash_bits = memLevel + 7;
  19982. s.hash_size = 1 << s.hash_bits;
  19983. s.hash_mask = s.hash_size - 1;
  19984. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  19985. s.window = new utils.Buf8(s.w_size * 2);
  19986. s.head = new utils.Buf16(s.hash_size);
  19987. s.prev = new utils.Buf16(s.w_size);
  19988. // Don't need mem init magic for JS.
  19989. //s.high_water = 0; /* nothing written to s->window yet */
  19990. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  19991. s.pending_buf_size = s.lit_bufsize * 4;
  19992. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  19993. s.d_buf = s.lit_bufsize >> 1;
  19994. s.l_buf = (1 + 2) * s.lit_bufsize;
  19995. s.level = level;
  19996. s.strategy = strategy;
  19997. s.method = method;
  19998. return deflateReset(strm);
  19999. }
  20000. function deflateInit(strm, level) {
  20001. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  20002. }
  20003. function deflate(strm, flush) {
  20004. var old_flush, s;
  20005. var beg, val; // for gzip header write only
  20006. if (!strm || !strm.state ||
  20007. flush > Z_BLOCK || flush < 0) {
  20008. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  20009. }
  20010. s = strm.state;
  20011. if (!strm.output ||
  20012. (!strm.input && strm.avail_in !== 0) ||
  20013. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  20014. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  20015. }
  20016. s.strm = strm; /* just in case */
  20017. old_flush = s.last_flush;
  20018. s.last_flush = flush;
  20019. /* Write the header */
  20020. if (s.status === INIT_STATE) {
  20021. if (s.wrap === 2) { // GZIP header
  20022. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20023. put_byte(s, 31);
  20024. put_byte(s, 139);
  20025. put_byte(s, 8);
  20026. if (!s.gzhead) { // s->gzhead == Z_NULL
  20027. put_byte(s, 0);
  20028. put_byte(s, 0);
  20029. put_byte(s, 0);
  20030. put_byte(s, 0);
  20031. put_byte(s, 0);
  20032. put_byte(s, s.level === 9 ? 2 :
  20033. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20034. 4 : 0));
  20035. put_byte(s, OS_CODE);
  20036. s.status = BUSY_STATE;
  20037. }
  20038. else {
  20039. put_byte(s, (s.gzhead.text ? 1 : 0) +
  20040. (s.gzhead.hcrc ? 2 : 0) +
  20041. (!s.gzhead.extra ? 0 : 4) +
  20042. (!s.gzhead.name ? 0 : 8) +
  20043. (!s.gzhead.comment ? 0 : 16)
  20044. );
  20045. put_byte(s, s.gzhead.time & 0xff);
  20046. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  20047. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  20048. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  20049. put_byte(s, s.level === 9 ? 2 :
  20050. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20051. 4 : 0));
  20052. put_byte(s, s.gzhead.os & 0xff);
  20053. if (s.gzhead.extra && s.gzhead.extra.length) {
  20054. put_byte(s, s.gzhead.extra.length & 0xff);
  20055. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  20056. }
  20057. if (s.gzhead.hcrc) {
  20058. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  20059. }
  20060. s.gzindex = 0;
  20061. s.status = EXTRA_STATE;
  20062. }
  20063. }
  20064. else // DEFLATE header
  20065. {
  20066. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  20067. var level_flags = -1;
  20068. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  20069. level_flags = 0;
  20070. } else if (s.level < 6) {
  20071. level_flags = 1;
  20072. } else if (s.level === 6) {
  20073. level_flags = 2;
  20074. } else {
  20075. level_flags = 3;
  20076. }
  20077. header |= (level_flags << 6);
  20078. if (s.strstart !== 0) { header |= PRESET_DICT; }
  20079. header += 31 - (header % 31);
  20080. s.status = BUSY_STATE;
  20081. putShortMSB(s, header);
  20082. /* Save the adler32 of the preset dictionary: */
  20083. if (s.strstart !== 0) {
  20084. putShortMSB(s, strm.adler >>> 16);
  20085. putShortMSB(s, strm.adler & 0xffff);
  20086. }
  20087. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  20088. }
  20089. }
  20090. //#ifdef GZIP
  20091. if (s.status === EXTRA_STATE) {
  20092. if (s.gzhead.extra/* != Z_NULL*/) {
  20093. beg = s.pending; /* start of bytes to update crc */
  20094. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  20095. if (s.pending === s.pending_buf_size) {
  20096. if (s.gzhead.hcrc && s.pending > beg) {
  20097. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20098. }
  20099. flush_pending(strm);
  20100. beg = s.pending;
  20101. if (s.pending === s.pending_buf_size) {
  20102. break;
  20103. }
  20104. }
  20105. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  20106. s.gzindex++;
  20107. }
  20108. if (s.gzhead.hcrc && s.pending > beg) {
  20109. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20110. }
  20111. if (s.gzindex === s.gzhead.extra.length) {
  20112. s.gzindex = 0;
  20113. s.status = NAME_STATE;
  20114. }
  20115. }
  20116. else {
  20117. s.status = NAME_STATE;
  20118. }
  20119. }
  20120. if (s.status === NAME_STATE) {
  20121. if (s.gzhead.name/* != Z_NULL*/) {
  20122. beg = s.pending; /* start of bytes to update crc */
  20123. //int val;
  20124. do {
  20125. if (s.pending === s.pending_buf_size) {
  20126. if (s.gzhead.hcrc && s.pending > beg) {
  20127. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20128. }
  20129. flush_pending(strm);
  20130. beg = s.pending;
  20131. if (s.pending === s.pending_buf_size) {
  20132. val = 1;
  20133. break;
  20134. }
  20135. }
  20136. // JS specific: little magic to add zero terminator to end of string
  20137. if (s.gzindex < s.gzhead.name.length) {
  20138. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  20139. } else {
  20140. val = 0;
  20141. }
  20142. put_byte(s, val);
  20143. } while (val !== 0);
  20144. if (s.gzhead.hcrc && s.pending > beg){
  20145. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20146. }
  20147. if (val === 0) {
  20148. s.gzindex = 0;
  20149. s.status = COMMENT_STATE;
  20150. }
  20151. }
  20152. else {
  20153. s.status = COMMENT_STATE;
  20154. }
  20155. }
  20156. if (s.status === COMMENT_STATE) {
  20157. if (s.gzhead.comment/* != Z_NULL*/) {
  20158. beg = s.pending; /* start of bytes to update crc */
  20159. //int val;
  20160. do {
  20161. if (s.pending === s.pending_buf_size) {
  20162. if (s.gzhead.hcrc && s.pending > beg) {
  20163. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20164. }
  20165. flush_pending(strm);
  20166. beg = s.pending;
  20167. if (s.pending === s.pending_buf_size) {
  20168. val = 1;
  20169. break;
  20170. }
  20171. }
  20172. // JS specific: little magic to add zero terminator to end of string
  20173. if (s.gzindex < s.gzhead.comment.length) {
  20174. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  20175. } else {
  20176. val = 0;
  20177. }
  20178. put_byte(s, val);
  20179. } while (val !== 0);
  20180. if (s.gzhead.hcrc && s.pending > beg) {
  20181. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20182. }
  20183. if (val === 0) {
  20184. s.status = HCRC_STATE;
  20185. }
  20186. }
  20187. else {
  20188. s.status = HCRC_STATE;
  20189. }
  20190. }
  20191. if (s.status === HCRC_STATE) {
  20192. if (s.gzhead.hcrc) {
  20193. if (s.pending + 2 > s.pending_buf_size) {
  20194. flush_pending(strm);
  20195. }
  20196. if (s.pending + 2 <= s.pending_buf_size) {
  20197. put_byte(s, strm.adler & 0xff);
  20198. put_byte(s, (strm.adler >> 8) & 0xff);
  20199. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20200. s.status = BUSY_STATE;
  20201. }
  20202. }
  20203. else {
  20204. s.status = BUSY_STATE;
  20205. }
  20206. }
  20207. //#endif
  20208. /* Flush as much pending output as possible */
  20209. if (s.pending !== 0) {
  20210. flush_pending(strm);
  20211. if (strm.avail_out === 0) {
  20212. /* Since avail_out is 0, deflate will be called again with
  20213. * more output space, but possibly with both pending and
  20214. * avail_in equal to zero. There won't be anything to do,
  20215. * but this is not an error situation so make sure we
  20216. * return OK instead of BUF_ERROR at next call of deflate:
  20217. */
  20218. s.last_flush = -1;
  20219. return Z_OK;
  20220. }
  20221. /* Make sure there is something to do and avoid duplicate consecutive
  20222. * flushes. For repeated and useless calls with Z_FINISH, we keep
  20223. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  20224. */
  20225. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  20226. flush !== Z_FINISH) {
  20227. return err(strm, Z_BUF_ERROR);
  20228. }
  20229. /* User must not provide more input after the first FINISH: */
  20230. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  20231. return err(strm, Z_BUF_ERROR);
  20232. }
  20233. /* Start a new block or continue the current one.
  20234. */
  20235. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  20236. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  20237. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  20238. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  20239. configuration_table[s.level].func(s, flush));
  20240. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  20241. s.status = FINISH_STATE;
  20242. }
  20243. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  20244. if (strm.avail_out === 0) {
  20245. s.last_flush = -1;
  20246. /* avoid BUF_ERROR next call, see above */
  20247. }
  20248. return Z_OK;
  20249. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  20250. * of deflate should use the same flush parameter to make sure
  20251. * that the flush is complete. So we don't have to output an
  20252. * empty block here, this will be done at next call. This also
  20253. * ensures that for a very small output buffer, we emit at most
  20254. * one empty block.
  20255. */
  20256. }
  20257. if (bstate === BS_BLOCK_DONE) {
  20258. if (flush === Z_PARTIAL_FLUSH) {
  20259. trees._tr_align(s);
  20260. }
  20261. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  20262. trees._tr_stored_block(s, 0, 0, false);
  20263. /* For a full flush, this empty block will be recognized
  20264. * as a special marker by inflate_sync().
  20265. */
  20266. if (flush === Z_FULL_FLUSH) {
  20267. /*** CLEAR_HASH(s); ***/ /* forget history */
  20268. zero(s.head); // Fill with NIL (= 0);
  20269. if (s.lookahead === 0) {
  20270. s.strstart = 0;
  20271. s.block_start = 0;
  20272. s.insert = 0;
  20273. }
  20274. }
  20275. }
  20276. flush_pending(strm);
  20277. if (strm.avail_out === 0) {
  20278. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  20279. return Z_OK;
  20280. }
  20281. }
  20282. }
  20283. //Assert(strm->avail_out > 0, "bug2");
  20284. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  20285. if (flush !== Z_FINISH) { return Z_OK; }
  20286. if (s.wrap <= 0) { return Z_STREAM_END; }
  20287. /* Write the trailer */
  20288. if (s.wrap === 2) {
  20289. put_byte(s, strm.adler & 0xff);
  20290. put_byte(s, (strm.adler >> 8) & 0xff);
  20291. put_byte(s, (strm.adler >> 16) & 0xff);
  20292. put_byte(s, (strm.adler >> 24) & 0xff);
  20293. put_byte(s, strm.total_in & 0xff);
  20294. put_byte(s, (strm.total_in >> 8) & 0xff);
  20295. put_byte(s, (strm.total_in >> 16) & 0xff);
  20296. put_byte(s, (strm.total_in >> 24) & 0xff);
  20297. }
  20298. else
  20299. {
  20300. putShortMSB(s, strm.adler >>> 16);
  20301. putShortMSB(s, strm.adler & 0xffff);
  20302. }
  20303. flush_pending(strm);
  20304. /* If avail_out is zero, the application will call deflate again
  20305. * to flush the rest.
  20306. */
  20307. if (s.wrap > 0) { s.wrap = -s.wrap; }
  20308. /* write the trailer only once! */
  20309. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  20310. }
  20311. function deflateEnd(strm) {
  20312. var status;
  20313. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  20314. return Z_STREAM_ERROR;
  20315. }
  20316. status = strm.state.status;
  20317. if (status !== INIT_STATE &&
  20318. status !== EXTRA_STATE &&
  20319. status !== NAME_STATE &&
  20320. status !== COMMENT_STATE &&
  20321. status !== HCRC_STATE &&
  20322. status !== BUSY_STATE &&
  20323. status !== FINISH_STATE
  20324. ) {
  20325. return err(strm, Z_STREAM_ERROR);
  20326. }
  20327. strm.state = null;
  20328. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  20329. }
  20330. /* =========================================================================
  20331. * Copy the source state to the destination state
  20332. */
  20333. //function deflateCopy(dest, source) {
  20334. //
  20335. //}
  20336. exports.deflateInit = deflateInit;
  20337. exports.deflateInit2 = deflateInit2;
  20338. exports.deflateReset = deflateReset;
  20339. exports.deflateResetKeep = deflateResetKeep;
  20340. exports.deflateSetHeader = deflateSetHeader;
  20341. exports.deflate = deflate;
  20342. exports.deflateEnd = deflateEnd;
  20343. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  20344. /* Not implemented
  20345. exports.deflateBound = deflateBound;
  20346. exports.deflateCopy = deflateCopy;
  20347. exports.deflateSetDictionary = deflateSetDictionary;
  20348. exports.deflateParams = deflateParams;
  20349. exports.deflatePending = deflatePending;
  20350. exports.deflatePrime = deflatePrime;
  20351. exports.deflateTune = deflateTune;
  20352. */
  20353. },{"../utils/common":67,"./adler32":69,"./crc32":71,"./messages":77,"./trees":78}],73:[function(require,module,exports){
  20354. 'use strict';
  20355. function GZheader() {
  20356. /* true if compressed data believed to be text */
  20357. this.text = 0;
  20358. /* modification time */
  20359. this.time = 0;
  20360. /* extra flags (not used when writing a gzip file) */
  20361. this.xflags = 0;
  20362. /* operating system */
  20363. this.os = 0;
  20364. /* pointer to extra field or Z_NULL if none */
  20365. this.extra = null;
  20366. /* extra field length (valid if extra != Z_NULL) */
  20367. this.extra_len = 0; // Actually, we don't need it in JS,
  20368. // but leave for few code modifications
  20369. //
  20370. // Setup limits is not necessary because in js we should not preallocate memory
  20371. // for inflate use constant limit in 65536 bytes
  20372. //
  20373. /* space at extra (only when reading header) */
  20374. // this.extra_max = 0;
  20375. /* pointer to zero-terminated file name or Z_NULL */
  20376. this.name = '';
  20377. /* space at name (only when reading header) */
  20378. // this.name_max = 0;
  20379. /* pointer to zero-terminated comment or Z_NULL */
  20380. this.comment = '';
  20381. /* space at comment (only when reading header) */
  20382. // this.comm_max = 0;
  20383. /* true if there was or will be a header crc */
  20384. this.hcrc = 0;
  20385. /* true when done reading gzip header (not used when writing a gzip file) */
  20386. this.done = false;
  20387. }
  20388. module.exports = GZheader;
  20389. },{}],74:[function(require,module,exports){
  20390. 'use strict';
  20391. // See state defs from inflate.js
  20392. var BAD = 30; /* got a data error -- remain here until reset */
  20393. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  20394. /*
  20395. Decode literal, length, and distance codes and write out the resulting
  20396. literal and match bytes until either not enough input or output is
  20397. available, an end-of-block is encountered, or a data error is encountered.
  20398. When large enough input and output buffers are supplied to inflate(), for
  20399. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  20400. inflate execution time is spent in this routine.
  20401. Entry assumptions:
  20402. state.mode === LEN
  20403. strm.avail_in >= 6
  20404. strm.avail_out >= 258
  20405. start >= strm.avail_out
  20406. state.bits < 8
  20407. On return, state.mode is one of:
  20408. LEN -- ran out of enough output space or enough available input
  20409. TYPE -- reached end of block code, inflate() to interpret next block
  20410. BAD -- error in block data
  20411. Notes:
  20412. - The maximum input bits used by a length/distance pair is 15 bits for the
  20413. length code, 5 bits for the length extra, 15 bits for the distance code,
  20414. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  20415. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  20416. checking for available input while decoding.
  20417. - The maximum bytes that a single length/distance pair can output is 258
  20418. bytes, which is the maximum length that can be coded. inflate_fast()
  20419. requires strm.avail_out >= 258 for each loop to avoid checking for
  20420. output space.
  20421. */
  20422. module.exports = function inflate_fast(strm, start) {
  20423. var state;
  20424. var _in; /* local strm.input */
  20425. var last; /* have enough input while in < last */
  20426. var _out; /* local strm.output */
  20427. var beg; /* inflate()'s initial strm.output */
  20428. var end; /* while out < end, enough space available */
  20429. //#ifdef INFLATE_STRICT
  20430. var dmax; /* maximum distance from zlib header */
  20431. //#endif
  20432. var wsize; /* window size or zero if not using window */
  20433. var whave; /* valid bytes in the window */
  20434. var wnext; /* window write index */
  20435. var window; /* allocated sliding window, if wsize != 0 */
  20436. var hold; /* local strm.hold */
  20437. var bits; /* local strm.bits */
  20438. var lcode; /* local strm.lencode */
  20439. var dcode; /* local strm.distcode */
  20440. var lmask; /* mask for first level of length codes */
  20441. var dmask; /* mask for first level of distance codes */
  20442. var here; /* retrieved table entry */
  20443. var op; /* code bits, operation, extra bits, or */
  20444. /* window position, window bytes to copy */
  20445. var len; /* match length, unused bytes */
  20446. var dist; /* match distance */
  20447. var from; /* where to copy match from */
  20448. var from_source;
  20449. var input, output; // JS specific, because we have no pointers
  20450. /* copy state to local variables */
  20451. state = strm.state;
  20452. //here = state.here;
  20453. _in = strm.next_in;
  20454. input = strm.input;
  20455. last = _in + (strm.avail_in - 5);
  20456. _out = strm.next_out;
  20457. output = strm.output;
  20458. beg = _out - (start - strm.avail_out);
  20459. end = _out + (strm.avail_out - 257);
  20460. //#ifdef INFLATE_STRICT
  20461. dmax = state.dmax;
  20462. //#endif
  20463. wsize = state.wsize;
  20464. whave = state.whave;
  20465. wnext = state.wnext;
  20466. window = state.window;
  20467. hold = state.hold;
  20468. bits = state.bits;
  20469. lcode = state.lencode;
  20470. dcode = state.distcode;
  20471. lmask = (1 << state.lenbits) - 1;
  20472. dmask = (1 << state.distbits) - 1;
  20473. /* decode literals and length/distances until end-of-block or not enough
  20474. input data or output space */
  20475. top:
  20476. do {
  20477. if (bits < 15) {
  20478. hold += input[_in++] << bits;
  20479. bits += 8;
  20480. hold += input[_in++] << bits;
  20481. bits += 8;
  20482. }
  20483. here = lcode[hold & lmask];
  20484. dolen:
  20485. for (;;) { // Goto emulation
  20486. op = here >>> 24/*here.bits*/;
  20487. hold >>>= op;
  20488. bits -= op;
  20489. op = (here >>> 16) & 0xff/*here.op*/;
  20490. if (op === 0) { /* literal */
  20491. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20492. // "inflate: literal '%c'\n" :
  20493. // "inflate: literal 0x%02x\n", here.val));
  20494. output[_out++] = here & 0xffff/*here.val*/;
  20495. }
  20496. else if (op & 16) { /* length base */
  20497. len = here & 0xffff/*here.val*/;
  20498. op &= 15; /* number of extra bits */
  20499. if (op) {
  20500. if (bits < op) {
  20501. hold += input[_in++] << bits;
  20502. bits += 8;
  20503. }
  20504. len += hold & ((1 << op) - 1);
  20505. hold >>>= op;
  20506. bits -= op;
  20507. }
  20508. //Tracevv((stderr, "inflate: length %u\n", len));
  20509. if (bits < 15) {
  20510. hold += input[_in++] << bits;
  20511. bits += 8;
  20512. hold += input[_in++] << bits;
  20513. bits += 8;
  20514. }
  20515. here = dcode[hold & dmask];
  20516. dodist:
  20517. for (;;) { // goto emulation
  20518. op = here >>> 24/*here.bits*/;
  20519. hold >>>= op;
  20520. bits -= op;
  20521. op = (here >>> 16) & 0xff/*here.op*/;
  20522. if (op & 16) { /* distance base */
  20523. dist = here & 0xffff/*here.val*/;
  20524. op &= 15; /* number of extra bits */
  20525. if (bits < op) {
  20526. hold += input[_in++] << bits;
  20527. bits += 8;
  20528. if (bits < op) {
  20529. hold += input[_in++] << bits;
  20530. bits += 8;
  20531. }
  20532. }
  20533. dist += hold & ((1 << op) - 1);
  20534. //#ifdef INFLATE_STRICT
  20535. if (dist > dmax) {
  20536. strm.msg = 'invalid distance too far back';
  20537. state.mode = BAD;
  20538. break top;
  20539. }
  20540. //#endif
  20541. hold >>>= op;
  20542. bits -= op;
  20543. //Tracevv((stderr, "inflate: distance %u\n", dist));
  20544. op = _out - beg; /* max distance in output */
  20545. if (dist > op) { /* see if copy from window */
  20546. op = dist - op; /* distance back in window */
  20547. if (op > whave) {
  20548. if (state.sane) {
  20549. strm.msg = 'invalid distance too far back';
  20550. state.mode = BAD;
  20551. break top;
  20552. }
  20553. // (!) This block is disabled in zlib defailts,
  20554. // don't enable it for binary compatibility
  20555. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20556. // if (len <= op - whave) {
  20557. // do {
  20558. // output[_out++] = 0;
  20559. // } while (--len);
  20560. // continue top;
  20561. // }
  20562. // len -= op - whave;
  20563. // do {
  20564. // output[_out++] = 0;
  20565. // } while (--op > whave);
  20566. // if (op === 0) {
  20567. // from = _out - dist;
  20568. // do {
  20569. // output[_out++] = output[from++];
  20570. // } while (--len);
  20571. // continue top;
  20572. // }
  20573. //#endif
  20574. }
  20575. from = 0; // window index
  20576. from_source = window;
  20577. if (wnext === 0) { /* very common case */
  20578. from += wsize - op;
  20579. if (op < len) { /* some from window */
  20580. len -= op;
  20581. do {
  20582. output[_out++] = window[from++];
  20583. } while (--op);
  20584. from = _out - dist; /* rest from output */
  20585. from_source = output;
  20586. }
  20587. }
  20588. else if (wnext < op) { /* wrap around window */
  20589. from += wsize + wnext - op;
  20590. op -= wnext;
  20591. if (op < len) { /* some from end of window */
  20592. len -= op;
  20593. do {
  20594. output[_out++] = window[from++];
  20595. } while (--op);
  20596. from = 0;
  20597. if (wnext < len) { /* some from start of window */
  20598. op = wnext;
  20599. len -= op;
  20600. do {
  20601. output[_out++] = window[from++];
  20602. } while (--op);
  20603. from = _out - dist; /* rest from output */
  20604. from_source = output;
  20605. }
  20606. }
  20607. }
  20608. else { /* contiguous in window */
  20609. from += wnext - op;
  20610. if (op < len) { /* some from window */
  20611. len -= op;
  20612. do {
  20613. output[_out++] = window[from++];
  20614. } while (--op);
  20615. from = _out - dist; /* rest from output */
  20616. from_source = output;
  20617. }
  20618. }
  20619. while (len > 2) {
  20620. output[_out++] = from_source[from++];
  20621. output[_out++] = from_source[from++];
  20622. output[_out++] = from_source[from++];
  20623. len -= 3;
  20624. }
  20625. if (len) {
  20626. output[_out++] = from_source[from++];
  20627. if (len > 1) {
  20628. output[_out++] = from_source[from++];
  20629. }
  20630. }
  20631. }
  20632. else {
  20633. from = _out - dist; /* copy direct from output */
  20634. do { /* minimum length is three */
  20635. output[_out++] = output[from++];
  20636. output[_out++] = output[from++];
  20637. output[_out++] = output[from++];
  20638. len -= 3;
  20639. } while (len > 2);
  20640. if (len) {
  20641. output[_out++] = output[from++];
  20642. if (len > 1) {
  20643. output[_out++] = output[from++];
  20644. }
  20645. }
  20646. }
  20647. }
  20648. else if ((op & 64) === 0) { /* 2nd level distance code */
  20649. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  20650. continue dodist;
  20651. }
  20652. else {
  20653. strm.msg = 'invalid distance code';
  20654. state.mode = BAD;
  20655. break top;
  20656. }
  20657. break; // need to emulate goto via "continue"
  20658. }
  20659. }
  20660. else if ((op & 64) === 0) { /* 2nd level length code */
  20661. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  20662. continue dolen;
  20663. }
  20664. else if (op & 32) { /* end-of-block */
  20665. //Tracevv((stderr, "inflate: end of block\n"));
  20666. state.mode = TYPE;
  20667. break top;
  20668. }
  20669. else {
  20670. strm.msg = 'invalid literal/length code';
  20671. state.mode = BAD;
  20672. break top;
  20673. }
  20674. break; // need to emulate goto via "continue"
  20675. }
  20676. } while (_in < last && _out < end);
  20677. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  20678. len = bits >> 3;
  20679. _in -= len;
  20680. bits -= len << 3;
  20681. hold &= (1 << bits) - 1;
  20682. /* update state and return */
  20683. strm.next_in = _in;
  20684. strm.next_out = _out;
  20685. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  20686. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  20687. state.hold = hold;
  20688. state.bits = bits;
  20689. return;
  20690. };
  20691. },{}],75:[function(require,module,exports){
  20692. 'use strict';
  20693. var utils = require('../utils/common');
  20694. var adler32 = require('./adler32');
  20695. var crc32 = require('./crc32');
  20696. var inflate_fast = require('./inffast');
  20697. var inflate_table = require('./inftrees');
  20698. var CODES = 0;
  20699. var LENS = 1;
  20700. var DISTS = 2;
  20701. /* Public constants ==========================================================*/
  20702. /* ===========================================================================*/
  20703. /* Allowed flush values; see deflate() and inflate() below for details */
  20704. //var Z_NO_FLUSH = 0;
  20705. //var Z_PARTIAL_FLUSH = 1;
  20706. //var Z_SYNC_FLUSH = 2;
  20707. //var Z_FULL_FLUSH = 3;
  20708. var Z_FINISH = 4;
  20709. var Z_BLOCK = 5;
  20710. var Z_TREES = 6;
  20711. /* Return codes for the compression/decompression functions. Negative values
  20712. * are errors, positive values are used for special but normal events.
  20713. */
  20714. var Z_OK = 0;
  20715. var Z_STREAM_END = 1;
  20716. var Z_NEED_DICT = 2;
  20717. //var Z_ERRNO = -1;
  20718. var Z_STREAM_ERROR = -2;
  20719. var Z_DATA_ERROR = -3;
  20720. var Z_MEM_ERROR = -4;
  20721. var Z_BUF_ERROR = -5;
  20722. //var Z_VERSION_ERROR = -6;
  20723. /* The deflate compression method */
  20724. var Z_DEFLATED = 8;
  20725. /* STATES ====================================================================*/
  20726. /* ===========================================================================*/
  20727. var HEAD = 1; /* i: waiting for magic header */
  20728. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  20729. var TIME = 3; /* i: waiting for modification time (gzip) */
  20730. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  20731. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  20732. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  20733. var NAME = 7; /* i: waiting for end of file name (gzip) */
  20734. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  20735. var HCRC = 9; /* i: waiting for header crc (gzip) */
  20736. var DICTID = 10; /* i: waiting for dictionary check value */
  20737. var DICT = 11; /* waiting for inflateSetDictionary() call */
  20738. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  20739. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  20740. var STORED = 14; /* i: waiting for stored size (length and complement) */
  20741. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  20742. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  20743. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  20744. var LENLENS = 18; /* i: waiting for code length code lengths */
  20745. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  20746. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  20747. var LEN = 21; /* i: waiting for length/lit/eob code */
  20748. var LENEXT = 22; /* i: waiting for length extra bits */
  20749. var DIST = 23; /* i: waiting for distance code */
  20750. var DISTEXT = 24; /* i: waiting for distance extra bits */
  20751. var MATCH = 25; /* o: waiting for output space to copy string */
  20752. var LIT = 26; /* o: waiting for output space to write literal */
  20753. var CHECK = 27; /* i: waiting for 32-bit check value */
  20754. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  20755. var DONE = 29; /* finished check, done -- remain here until reset */
  20756. var BAD = 30; /* got a data error -- remain here until reset */
  20757. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  20758. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  20759. /* ===========================================================================*/
  20760. var ENOUGH_LENS = 852;
  20761. var ENOUGH_DISTS = 592;
  20762. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20763. var MAX_WBITS = 15;
  20764. /* 32K LZ77 window */
  20765. var DEF_WBITS = MAX_WBITS;
  20766. function ZSWAP32(q) {
  20767. return (((q >>> 24) & 0xff) +
  20768. ((q >>> 8) & 0xff00) +
  20769. ((q & 0xff00) << 8) +
  20770. ((q & 0xff) << 24));
  20771. }
  20772. function InflateState() {
  20773. this.mode = 0; /* current inflate mode */
  20774. this.last = false; /* true if processing last block */
  20775. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20776. this.havedict = false; /* true if dictionary provided */
  20777. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  20778. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  20779. this.check = 0; /* protected copy of check value */
  20780. this.total = 0; /* protected copy of output count */
  20781. // TODO: may be {}
  20782. this.head = null; /* where to save gzip header information */
  20783. /* sliding window */
  20784. this.wbits = 0; /* log base 2 of requested window size */
  20785. this.wsize = 0; /* window size or zero if not using window */
  20786. this.whave = 0; /* valid bytes in the window */
  20787. this.wnext = 0; /* window write index */
  20788. this.window = null; /* allocated sliding window, if needed */
  20789. /* bit accumulator */
  20790. this.hold = 0; /* input bit accumulator */
  20791. this.bits = 0; /* number of bits in "in" */
  20792. /* for string and stored block copying */
  20793. this.length = 0; /* literal or length of data to copy */
  20794. this.offset = 0; /* distance back to copy string from */
  20795. /* for table and code decoding */
  20796. this.extra = 0; /* extra bits needed */
  20797. /* fixed and dynamic code tables */
  20798. this.lencode = null; /* starting table for length/literal codes */
  20799. this.distcode = null; /* starting table for distance codes */
  20800. this.lenbits = 0; /* index bits for lencode */
  20801. this.distbits = 0; /* index bits for distcode */
  20802. /* dynamic table building */
  20803. this.ncode = 0; /* number of code length code lengths */
  20804. this.nlen = 0; /* number of length code lengths */
  20805. this.ndist = 0; /* number of distance code lengths */
  20806. this.have = 0; /* number of code lengths in lens[] */
  20807. this.next = null; /* next available space in codes[] */
  20808. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  20809. this.work = new utils.Buf16(288); /* work area for code table building */
  20810. /*
  20811. because we don't have pointers in js, we use lencode and distcode directly
  20812. as buffers so we don't need codes
  20813. */
  20814. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  20815. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  20816. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  20817. this.sane = 0; /* if false, allow invalid distance too far */
  20818. this.back = 0; /* bits back of last unprocessed length/lit */
  20819. this.was = 0; /* initial length of match */
  20820. }
  20821. function inflateResetKeep(strm) {
  20822. var state;
  20823. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20824. state = strm.state;
  20825. strm.total_in = strm.total_out = state.total = 0;
  20826. strm.msg = ''; /*Z_NULL*/
  20827. if (state.wrap) { /* to support ill-conceived Java test suite */
  20828. strm.adler = state.wrap & 1;
  20829. }
  20830. state.mode = HEAD;
  20831. state.last = 0;
  20832. state.havedict = 0;
  20833. state.dmax = 32768;
  20834. state.head = null/*Z_NULL*/;
  20835. state.hold = 0;
  20836. state.bits = 0;
  20837. //state.lencode = state.distcode = state.next = state.codes;
  20838. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  20839. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  20840. state.sane = 1;
  20841. state.back = -1;
  20842. //Tracev((stderr, "inflate: reset\n"));
  20843. return Z_OK;
  20844. }
  20845. function inflateReset(strm) {
  20846. var state;
  20847. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20848. state = strm.state;
  20849. state.wsize = 0;
  20850. state.whave = 0;
  20851. state.wnext = 0;
  20852. return inflateResetKeep(strm);
  20853. }
  20854. function inflateReset2(strm, windowBits) {
  20855. var wrap;
  20856. var state;
  20857. /* get the state */
  20858. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20859. state = strm.state;
  20860. /* extract wrap request from windowBits parameter */
  20861. if (windowBits < 0) {
  20862. wrap = 0;
  20863. windowBits = -windowBits;
  20864. }
  20865. else {
  20866. wrap = (windowBits >> 4) + 1;
  20867. if (windowBits < 48) {
  20868. windowBits &= 15;
  20869. }
  20870. }
  20871. /* set number of window bits, free window if different */
  20872. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  20873. return Z_STREAM_ERROR;
  20874. }
  20875. if (state.window !== null && state.wbits !== windowBits) {
  20876. state.window = null;
  20877. }
  20878. /* update state and reset the rest of it */
  20879. state.wrap = wrap;
  20880. state.wbits = windowBits;
  20881. return inflateReset(strm);
  20882. }
  20883. function inflateInit2(strm, windowBits) {
  20884. var ret;
  20885. var state;
  20886. if (!strm) { return Z_STREAM_ERROR; }
  20887. //strm.msg = Z_NULL; /* in case we return an error */
  20888. state = new InflateState();
  20889. //if (state === Z_NULL) return Z_MEM_ERROR;
  20890. //Tracev((stderr, "inflate: allocated\n"));
  20891. strm.state = state;
  20892. state.window = null/*Z_NULL*/;
  20893. ret = inflateReset2(strm, windowBits);
  20894. if (ret !== Z_OK) {
  20895. strm.state = null/*Z_NULL*/;
  20896. }
  20897. return ret;
  20898. }
  20899. function inflateInit(strm) {
  20900. return inflateInit2(strm, DEF_WBITS);
  20901. }
  20902. /*
  20903. Return state with length and distance decoding tables and index sizes set to
  20904. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  20905. If BUILDFIXED is defined, then instead this routine builds the tables the
  20906. first time it's called, and returns those tables the first time and
  20907. thereafter. This reduces the size of the code by about 2K bytes, in
  20908. exchange for a little execution time. However, BUILDFIXED should not be
  20909. used for threaded applications, since the rewriting of the tables and virgin
  20910. may not be thread-safe.
  20911. */
  20912. var virgin = true;
  20913. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  20914. function fixedtables(state) {
  20915. /* build fixed huffman tables if first call (may not be thread safe) */
  20916. if (virgin) {
  20917. var sym;
  20918. lenfix = new utils.Buf32(512);
  20919. distfix = new utils.Buf32(32);
  20920. /* literal/length table */
  20921. sym = 0;
  20922. while (sym < 144) { state.lens[sym++] = 8; }
  20923. while (sym < 256) { state.lens[sym++] = 9; }
  20924. while (sym < 280) { state.lens[sym++] = 7; }
  20925. while (sym < 288) { state.lens[sym++] = 8; }
  20926. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  20927. /* distance table */
  20928. sym = 0;
  20929. while (sym < 32) { state.lens[sym++] = 5; }
  20930. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  20931. /* do this just once */
  20932. virgin = false;
  20933. }
  20934. state.lencode = lenfix;
  20935. state.lenbits = 9;
  20936. state.distcode = distfix;
  20937. state.distbits = 5;
  20938. }
  20939. /*
  20940. Update the window with the last wsize (normally 32K) bytes written before
  20941. returning. If window does not exist yet, create it. This is only called
  20942. when a window is already in use, or when output has been written during this
  20943. inflate call, but the end of the deflate stream has not been reached yet.
  20944. It is also called to create a window for dictionary data when a dictionary
  20945. is loaded.
  20946. Providing output buffers larger than 32K to inflate() should provide a speed
  20947. advantage, since only the last 32K of output is copied to the sliding window
  20948. upon return from inflate(), and since all distances after the first 32K of
  20949. output will fall in the output data, making match copies simpler and faster.
  20950. The advantage may be dependent on the size of the processor's data caches.
  20951. */
  20952. function updatewindow(strm, src, end, copy) {
  20953. var dist;
  20954. var state = strm.state;
  20955. /* if it hasn't been done already, allocate space for the window */
  20956. if (state.window === null) {
  20957. state.wsize = 1 << state.wbits;
  20958. state.wnext = 0;
  20959. state.whave = 0;
  20960. state.window = new utils.Buf8(state.wsize);
  20961. }
  20962. /* copy state->wsize or less output bytes into the circular window */
  20963. if (copy >= state.wsize) {
  20964. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  20965. state.wnext = 0;
  20966. state.whave = state.wsize;
  20967. }
  20968. else {
  20969. dist = state.wsize - state.wnext;
  20970. if (dist > copy) {
  20971. dist = copy;
  20972. }
  20973. //zmemcpy(state->window + state->wnext, end - copy, dist);
  20974. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  20975. copy -= dist;
  20976. if (copy) {
  20977. //zmemcpy(state->window, end - copy, copy);
  20978. utils.arraySet(state.window,src, end - copy, copy, 0);
  20979. state.wnext = copy;
  20980. state.whave = state.wsize;
  20981. }
  20982. else {
  20983. state.wnext += dist;
  20984. if (state.wnext === state.wsize) { state.wnext = 0; }
  20985. if (state.whave < state.wsize) { state.whave += dist; }
  20986. }
  20987. }
  20988. return 0;
  20989. }
  20990. function inflate(strm, flush) {
  20991. var state;
  20992. var input, output; // input/output buffers
  20993. var next; /* next input INDEX */
  20994. var put; /* next output INDEX */
  20995. var have, left; /* available input and output */
  20996. var hold; /* bit buffer */
  20997. var bits; /* bits in bit buffer */
  20998. var _in, _out; /* save starting available input and output */
  20999. var copy; /* number of stored or match bytes to copy */
  21000. var from; /* where to copy match bytes from */
  21001. var from_source;
  21002. var here = 0; /* current decoding table entry */
  21003. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  21004. //var last; /* parent table entry */
  21005. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  21006. var len; /* length to copy for repeats, bits to drop */
  21007. var ret; /* return code */
  21008. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  21009. var opts;
  21010. var n; // temporary var for NEED_BITS
  21011. var order = /* permutation of code lengths */
  21012. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  21013. if (!strm || !strm.state || !strm.output ||
  21014. (!strm.input && strm.avail_in !== 0)) {
  21015. return Z_STREAM_ERROR;
  21016. }
  21017. state = strm.state;
  21018. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  21019. //--- LOAD() ---
  21020. put = strm.next_out;
  21021. output = strm.output;
  21022. left = strm.avail_out;
  21023. next = strm.next_in;
  21024. input = strm.input;
  21025. have = strm.avail_in;
  21026. hold = state.hold;
  21027. bits = state.bits;
  21028. //---
  21029. _in = have;
  21030. _out = left;
  21031. ret = Z_OK;
  21032. inf_leave: // goto emulation
  21033. for (;;) {
  21034. switch (state.mode) {
  21035. case HEAD:
  21036. if (state.wrap === 0) {
  21037. state.mode = TYPEDO;
  21038. break;
  21039. }
  21040. //=== NEEDBITS(16);
  21041. while (bits < 16) {
  21042. if (have === 0) { break inf_leave; }
  21043. have--;
  21044. hold += input[next++] << bits;
  21045. bits += 8;
  21046. }
  21047. //===//
  21048. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  21049. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  21050. //=== CRC2(state.check, hold);
  21051. hbuf[0] = hold & 0xff;
  21052. hbuf[1] = (hold >>> 8) & 0xff;
  21053. state.check = crc32(state.check, hbuf, 2, 0);
  21054. //===//
  21055. //=== INITBITS();
  21056. hold = 0;
  21057. bits = 0;
  21058. //===//
  21059. state.mode = FLAGS;
  21060. break;
  21061. }
  21062. state.flags = 0; /* expect zlib header */
  21063. if (state.head) {
  21064. state.head.done = false;
  21065. }
  21066. if (!(state.wrap & 1) || /* check if zlib header allowed */
  21067. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  21068. strm.msg = 'incorrect header check';
  21069. state.mode = BAD;
  21070. break;
  21071. }
  21072. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  21073. strm.msg = 'unknown compression method';
  21074. state.mode = BAD;
  21075. break;
  21076. }
  21077. //--- DROPBITS(4) ---//
  21078. hold >>>= 4;
  21079. bits -= 4;
  21080. //---//
  21081. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  21082. if (state.wbits === 0) {
  21083. state.wbits = len;
  21084. }
  21085. else if (len > state.wbits) {
  21086. strm.msg = 'invalid window size';
  21087. state.mode = BAD;
  21088. break;
  21089. }
  21090. state.dmax = 1 << len;
  21091. //Tracev((stderr, "inflate: zlib header ok\n"));
  21092. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  21093. state.mode = hold & 0x200 ? DICTID : TYPE;
  21094. //=== INITBITS();
  21095. hold = 0;
  21096. bits = 0;
  21097. //===//
  21098. break;
  21099. case FLAGS:
  21100. //=== NEEDBITS(16); */
  21101. while (bits < 16) {
  21102. if (have === 0) { break inf_leave; }
  21103. have--;
  21104. hold += input[next++] << bits;
  21105. bits += 8;
  21106. }
  21107. //===//
  21108. state.flags = hold;
  21109. if ((state.flags & 0xff) !== Z_DEFLATED) {
  21110. strm.msg = 'unknown compression method';
  21111. state.mode = BAD;
  21112. break;
  21113. }
  21114. if (state.flags & 0xe000) {
  21115. strm.msg = 'unknown header flags set';
  21116. state.mode = BAD;
  21117. break;
  21118. }
  21119. if (state.head) {
  21120. state.head.text = ((hold >> 8) & 1);
  21121. }
  21122. if (state.flags & 0x0200) {
  21123. //=== CRC2(state.check, hold);
  21124. hbuf[0] = hold & 0xff;
  21125. hbuf[1] = (hold >>> 8) & 0xff;
  21126. state.check = crc32(state.check, hbuf, 2, 0);
  21127. //===//
  21128. }
  21129. //=== INITBITS();
  21130. hold = 0;
  21131. bits = 0;
  21132. //===//
  21133. state.mode = TIME;
  21134. /* falls through */
  21135. case TIME:
  21136. //=== NEEDBITS(32); */
  21137. while (bits < 32) {
  21138. if (have === 0) { break inf_leave; }
  21139. have--;
  21140. hold += input[next++] << bits;
  21141. bits += 8;
  21142. }
  21143. //===//
  21144. if (state.head) {
  21145. state.head.time = hold;
  21146. }
  21147. if (state.flags & 0x0200) {
  21148. //=== CRC4(state.check, hold)
  21149. hbuf[0] = hold & 0xff;
  21150. hbuf[1] = (hold >>> 8) & 0xff;
  21151. hbuf[2] = (hold >>> 16) & 0xff;
  21152. hbuf[3] = (hold >>> 24) & 0xff;
  21153. state.check = crc32(state.check, hbuf, 4, 0);
  21154. //===
  21155. }
  21156. //=== INITBITS();
  21157. hold = 0;
  21158. bits = 0;
  21159. //===//
  21160. state.mode = OS;
  21161. /* falls through */
  21162. case OS:
  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.head) {
  21172. state.head.xflags = (hold & 0xff);
  21173. state.head.os = (hold >> 8);
  21174. }
  21175. if (state.flags & 0x0200) {
  21176. //=== CRC2(state.check, hold);
  21177. hbuf[0] = hold & 0xff;
  21178. hbuf[1] = (hold >>> 8) & 0xff;
  21179. state.check = crc32(state.check, hbuf, 2, 0);
  21180. //===//
  21181. }
  21182. //=== INITBITS();
  21183. hold = 0;
  21184. bits = 0;
  21185. //===//
  21186. state.mode = EXLEN;
  21187. /* falls through */
  21188. case EXLEN:
  21189. if (state.flags & 0x0400) {
  21190. //=== NEEDBITS(16); */
  21191. while (bits < 16) {
  21192. if (have === 0) { break inf_leave; }
  21193. have--;
  21194. hold += input[next++] << bits;
  21195. bits += 8;
  21196. }
  21197. //===//
  21198. state.length = hold;
  21199. if (state.head) {
  21200. state.head.extra_len = hold;
  21201. }
  21202. if (state.flags & 0x0200) {
  21203. //=== CRC2(state.check, hold);
  21204. hbuf[0] = hold & 0xff;
  21205. hbuf[1] = (hold >>> 8) & 0xff;
  21206. state.check = crc32(state.check, hbuf, 2, 0);
  21207. //===//
  21208. }
  21209. //=== INITBITS();
  21210. hold = 0;
  21211. bits = 0;
  21212. //===//
  21213. }
  21214. else if (state.head) {
  21215. state.head.extra = null/*Z_NULL*/;
  21216. }
  21217. state.mode = EXTRA;
  21218. /* falls through */
  21219. case EXTRA:
  21220. if (state.flags & 0x0400) {
  21221. copy = state.length;
  21222. if (copy > have) { copy = have; }
  21223. if (copy) {
  21224. if (state.head) {
  21225. len = state.head.extra_len - state.length;
  21226. if (!state.head.extra) {
  21227. // Use untyped array for more conveniend processing later
  21228. state.head.extra = new Array(state.head.extra_len);
  21229. }
  21230. utils.arraySet(
  21231. state.head.extra,
  21232. input,
  21233. next,
  21234. // extra field is limited to 65536 bytes
  21235. // - no need for additional size check
  21236. copy,
  21237. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  21238. len
  21239. );
  21240. //zmemcpy(state.head.extra + len, next,
  21241. // len + copy > state.head.extra_max ?
  21242. // state.head.extra_max - len : copy);
  21243. }
  21244. if (state.flags & 0x0200) {
  21245. state.check = crc32(state.check, input, copy, next);
  21246. }
  21247. have -= copy;
  21248. next += copy;
  21249. state.length -= copy;
  21250. }
  21251. if (state.length) { break inf_leave; }
  21252. }
  21253. state.length = 0;
  21254. state.mode = NAME;
  21255. /* falls through */
  21256. case NAME:
  21257. if (state.flags & 0x0800) {
  21258. if (have === 0) { break inf_leave; }
  21259. copy = 0;
  21260. do {
  21261. // TODO: 2 or 1 bytes?
  21262. len = input[next + copy++];
  21263. /* use constant limit because in js we should not preallocate memory */
  21264. if (state.head && len &&
  21265. (state.length < 65536 /*state.head.name_max*/)) {
  21266. state.head.name += String.fromCharCode(len);
  21267. }
  21268. } while (len && copy < have);
  21269. if (state.flags & 0x0200) {
  21270. state.check = crc32(state.check, input, copy, next);
  21271. }
  21272. have -= copy;
  21273. next += copy;
  21274. if (len) { break inf_leave; }
  21275. }
  21276. else if (state.head) {
  21277. state.head.name = null;
  21278. }
  21279. state.length = 0;
  21280. state.mode = COMMENT;
  21281. /* falls through */
  21282. case COMMENT:
  21283. if (state.flags & 0x1000) {
  21284. if (have === 0) { break inf_leave; }
  21285. copy = 0;
  21286. do {
  21287. len = input[next + copy++];
  21288. /* use constant limit because in js we should not preallocate memory */
  21289. if (state.head && len &&
  21290. (state.length < 65536 /*state.head.comm_max*/)) {
  21291. state.head.comment += String.fromCharCode(len);
  21292. }
  21293. } while (len && copy < have);
  21294. if (state.flags & 0x0200) {
  21295. state.check = crc32(state.check, input, copy, next);
  21296. }
  21297. have -= copy;
  21298. next += copy;
  21299. if (len) { break inf_leave; }
  21300. }
  21301. else if (state.head) {
  21302. state.head.comment = null;
  21303. }
  21304. state.mode = HCRC;
  21305. /* falls through */
  21306. case HCRC:
  21307. if (state.flags & 0x0200) {
  21308. //=== NEEDBITS(16); */
  21309. while (bits < 16) {
  21310. if (have === 0) { break inf_leave; }
  21311. have--;
  21312. hold += input[next++] << bits;
  21313. bits += 8;
  21314. }
  21315. //===//
  21316. if (hold !== (state.check & 0xffff)) {
  21317. strm.msg = 'header crc mismatch';
  21318. state.mode = BAD;
  21319. break;
  21320. }
  21321. //=== INITBITS();
  21322. hold = 0;
  21323. bits = 0;
  21324. //===//
  21325. }
  21326. if (state.head) {
  21327. state.head.hcrc = ((state.flags >> 9) & 1);
  21328. state.head.done = true;
  21329. }
  21330. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  21331. state.mode = TYPE;
  21332. break;
  21333. case DICTID:
  21334. //=== NEEDBITS(32); */
  21335. while (bits < 32) {
  21336. if (have === 0) { break inf_leave; }
  21337. have--;
  21338. hold += input[next++] << bits;
  21339. bits += 8;
  21340. }
  21341. //===//
  21342. strm.adler = state.check = ZSWAP32(hold);
  21343. //=== INITBITS();
  21344. hold = 0;
  21345. bits = 0;
  21346. //===//
  21347. state.mode = DICT;
  21348. /* falls through */
  21349. case DICT:
  21350. if (state.havedict === 0) {
  21351. //--- RESTORE() ---
  21352. strm.next_out = put;
  21353. strm.avail_out = left;
  21354. strm.next_in = next;
  21355. strm.avail_in = have;
  21356. state.hold = hold;
  21357. state.bits = bits;
  21358. //---
  21359. return Z_NEED_DICT;
  21360. }
  21361. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  21362. state.mode = TYPE;
  21363. /* falls through */
  21364. case TYPE:
  21365. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  21366. /* falls through */
  21367. case TYPEDO:
  21368. if (state.last) {
  21369. //--- BYTEBITS() ---//
  21370. hold >>>= bits & 7;
  21371. bits -= bits & 7;
  21372. //---//
  21373. state.mode = CHECK;
  21374. break;
  21375. }
  21376. //=== NEEDBITS(3); */
  21377. while (bits < 3) {
  21378. if (have === 0) { break inf_leave; }
  21379. have--;
  21380. hold += input[next++] << bits;
  21381. bits += 8;
  21382. }
  21383. //===//
  21384. state.last = (hold & 0x01)/*BITS(1)*/;
  21385. //--- DROPBITS(1) ---//
  21386. hold >>>= 1;
  21387. bits -= 1;
  21388. //---//
  21389. switch ((hold & 0x03)/*BITS(2)*/) {
  21390. case 0: /* stored block */
  21391. //Tracev((stderr, "inflate: stored block%s\n",
  21392. // state.last ? " (last)" : ""));
  21393. state.mode = STORED;
  21394. break;
  21395. case 1: /* fixed block */
  21396. fixedtables(state);
  21397. //Tracev((stderr, "inflate: fixed codes block%s\n",
  21398. // state.last ? " (last)" : ""));
  21399. state.mode = LEN_; /* decode codes */
  21400. if (flush === Z_TREES) {
  21401. //--- DROPBITS(2) ---//
  21402. hold >>>= 2;
  21403. bits -= 2;
  21404. //---//
  21405. break inf_leave;
  21406. }
  21407. break;
  21408. case 2: /* dynamic block */
  21409. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  21410. // state.last ? " (last)" : ""));
  21411. state.mode = TABLE;
  21412. break;
  21413. case 3:
  21414. strm.msg = 'invalid block type';
  21415. state.mode = BAD;
  21416. }
  21417. //--- DROPBITS(2) ---//
  21418. hold >>>= 2;
  21419. bits -= 2;
  21420. //---//
  21421. break;
  21422. case STORED:
  21423. //--- BYTEBITS() ---// /* go to byte boundary */
  21424. hold >>>= bits & 7;
  21425. bits -= bits & 7;
  21426. //---//
  21427. //=== NEEDBITS(32); */
  21428. while (bits < 32) {
  21429. if (have === 0) { break inf_leave; }
  21430. have--;
  21431. hold += input[next++] << bits;
  21432. bits += 8;
  21433. }
  21434. //===//
  21435. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  21436. strm.msg = 'invalid stored block lengths';
  21437. state.mode = BAD;
  21438. break;
  21439. }
  21440. state.length = hold & 0xffff;
  21441. //Tracev((stderr, "inflate: stored length %u\n",
  21442. // state.length));
  21443. //=== INITBITS();
  21444. hold = 0;
  21445. bits = 0;
  21446. //===//
  21447. state.mode = COPY_;
  21448. if (flush === Z_TREES) { break inf_leave; }
  21449. /* falls through */
  21450. case COPY_:
  21451. state.mode = COPY;
  21452. /* falls through */
  21453. case COPY:
  21454. copy = state.length;
  21455. if (copy) {
  21456. if (copy > have) { copy = have; }
  21457. if (copy > left) { copy = left; }
  21458. if (copy === 0) { break inf_leave; }
  21459. //--- zmemcpy(put, next, copy); ---
  21460. utils.arraySet(output, input, next, copy, put);
  21461. //---//
  21462. have -= copy;
  21463. next += copy;
  21464. left -= copy;
  21465. put += copy;
  21466. state.length -= copy;
  21467. break;
  21468. }
  21469. //Tracev((stderr, "inflate: stored end\n"));
  21470. state.mode = TYPE;
  21471. break;
  21472. case TABLE:
  21473. //=== NEEDBITS(14); */
  21474. while (bits < 14) {
  21475. if (have === 0) { break inf_leave; }
  21476. have--;
  21477. hold += input[next++] << bits;
  21478. bits += 8;
  21479. }
  21480. //===//
  21481. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  21482. //--- DROPBITS(5) ---//
  21483. hold >>>= 5;
  21484. bits -= 5;
  21485. //---//
  21486. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  21487. //--- DROPBITS(5) ---//
  21488. hold >>>= 5;
  21489. bits -= 5;
  21490. //---//
  21491. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  21492. //--- DROPBITS(4) ---//
  21493. hold >>>= 4;
  21494. bits -= 4;
  21495. //---//
  21496. //#ifndef PKZIP_BUG_WORKAROUND
  21497. if (state.nlen > 286 || state.ndist > 30) {
  21498. strm.msg = 'too many length or distance symbols';
  21499. state.mode = BAD;
  21500. break;
  21501. }
  21502. //#endif
  21503. //Tracev((stderr, "inflate: table sizes ok\n"));
  21504. state.have = 0;
  21505. state.mode = LENLENS;
  21506. /* falls through */
  21507. case LENLENS:
  21508. while (state.have < state.ncode) {
  21509. //=== NEEDBITS(3);
  21510. while (bits < 3) {
  21511. if (have === 0) { break inf_leave; }
  21512. have--;
  21513. hold += input[next++] << bits;
  21514. bits += 8;
  21515. }
  21516. //===//
  21517. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  21518. //--- DROPBITS(3) ---//
  21519. hold >>>= 3;
  21520. bits -= 3;
  21521. //---//
  21522. }
  21523. while (state.have < 19) {
  21524. state.lens[order[state.have++]] = 0;
  21525. }
  21526. // We have separate tables & no pointers. 2 commented lines below not needed.
  21527. //state.next = state.codes;
  21528. //state.lencode = state.next;
  21529. // Switch to use dynamic table
  21530. state.lencode = state.lendyn;
  21531. state.lenbits = 7;
  21532. opts = {bits: state.lenbits};
  21533. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  21534. state.lenbits = opts.bits;
  21535. if (ret) {
  21536. strm.msg = 'invalid code lengths set';
  21537. state.mode = BAD;
  21538. break;
  21539. }
  21540. //Tracev((stderr, "inflate: code lengths ok\n"));
  21541. state.have = 0;
  21542. state.mode = CODELENS;
  21543. /* falls through */
  21544. case CODELENS:
  21545. while (state.have < state.nlen + state.ndist) {
  21546. for (;;) {
  21547. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  21548. here_bits = here >>> 24;
  21549. here_op = (here >>> 16) & 0xff;
  21550. here_val = here & 0xffff;
  21551. if ((here_bits) <= bits) { break; }
  21552. //--- PULLBYTE() ---//
  21553. if (have === 0) { break inf_leave; }
  21554. have--;
  21555. hold += input[next++] << bits;
  21556. bits += 8;
  21557. //---//
  21558. }
  21559. if (here_val < 16) {
  21560. //--- DROPBITS(here.bits) ---//
  21561. hold >>>= here_bits;
  21562. bits -= here_bits;
  21563. //---//
  21564. state.lens[state.have++] = here_val;
  21565. }
  21566. else {
  21567. if (here_val === 16) {
  21568. //=== NEEDBITS(here.bits + 2);
  21569. n = here_bits + 2;
  21570. while (bits < n) {
  21571. if (have === 0) { break inf_leave; }
  21572. have--;
  21573. hold += input[next++] << bits;
  21574. bits += 8;
  21575. }
  21576. //===//
  21577. //--- DROPBITS(here.bits) ---//
  21578. hold >>>= here_bits;
  21579. bits -= here_bits;
  21580. //---//
  21581. if (state.have === 0) {
  21582. strm.msg = 'invalid bit length repeat';
  21583. state.mode = BAD;
  21584. break;
  21585. }
  21586. len = state.lens[state.have - 1];
  21587. copy = 3 + (hold & 0x03);//BITS(2);
  21588. //--- DROPBITS(2) ---//
  21589. hold >>>= 2;
  21590. bits -= 2;
  21591. //---//
  21592. }
  21593. else if (here_val === 17) {
  21594. //=== NEEDBITS(here.bits + 3);
  21595. n = here_bits + 3;
  21596. while (bits < n) {
  21597. if (have === 0) { break inf_leave; }
  21598. have--;
  21599. hold += input[next++] << bits;
  21600. bits += 8;
  21601. }
  21602. //===//
  21603. //--- DROPBITS(here.bits) ---//
  21604. hold >>>= here_bits;
  21605. bits -= here_bits;
  21606. //---//
  21607. len = 0;
  21608. copy = 3 + (hold & 0x07);//BITS(3);
  21609. //--- DROPBITS(3) ---//
  21610. hold >>>= 3;
  21611. bits -= 3;
  21612. //---//
  21613. }
  21614. else {
  21615. //=== NEEDBITS(here.bits + 7);
  21616. n = here_bits + 7;
  21617. while (bits < n) {
  21618. if (have === 0) { break inf_leave; }
  21619. have--;
  21620. hold += input[next++] << bits;
  21621. bits += 8;
  21622. }
  21623. //===//
  21624. //--- DROPBITS(here.bits) ---//
  21625. hold >>>= here_bits;
  21626. bits -= here_bits;
  21627. //---//
  21628. len = 0;
  21629. copy = 11 + (hold & 0x7f);//BITS(7);
  21630. //--- DROPBITS(7) ---//
  21631. hold >>>= 7;
  21632. bits -= 7;
  21633. //---//
  21634. }
  21635. if (state.have + copy > state.nlen + state.ndist) {
  21636. strm.msg = 'invalid bit length repeat';
  21637. state.mode = BAD;
  21638. break;
  21639. }
  21640. while (copy--) {
  21641. state.lens[state.have++] = len;
  21642. }
  21643. }
  21644. }
  21645. /* handle error breaks in while */
  21646. if (state.mode === BAD) { break; }
  21647. /* check for end-of-block code (better have one) */
  21648. if (state.lens[256] === 0) {
  21649. strm.msg = 'invalid code -- missing end-of-block';
  21650. state.mode = BAD;
  21651. break;
  21652. }
  21653. /* build code tables -- note: do not change the lenbits or distbits
  21654. values here (9 and 6) without reading the comments in inftrees.h
  21655. concerning the ENOUGH constants, which depend on those values */
  21656. state.lenbits = 9;
  21657. opts = {bits: state.lenbits};
  21658. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  21659. // We have separate tables & no pointers. 2 commented lines below not needed.
  21660. // state.next_index = opts.table_index;
  21661. state.lenbits = opts.bits;
  21662. // state.lencode = state.next;
  21663. if (ret) {
  21664. strm.msg = 'invalid literal/lengths set';
  21665. state.mode = BAD;
  21666. break;
  21667. }
  21668. state.distbits = 6;
  21669. //state.distcode.copy(state.codes);
  21670. // Switch to use dynamic table
  21671. state.distcode = state.distdyn;
  21672. opts = {bits: state.distbits};
  21673. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  21674. // We have separate tables & no pointers. 2 commented lines below not needed.
  21675. // state.next_index = opts.table_index;
  21676. state.distbits = opts.bits;
  21677. // state.distcode = state.next;
  21678. if (ret) {
  21679. strm.msg = 'invalid distances set';
  21680. state.mode = BAD;
  21681. break;
  21682. }
  21683. //Tracev((stderr, 'inflate: codes ok\n'));
  21684. state.mode = LEN_;
  21685. if (flush === Z_TREES) { break inf_leave; }
  21686. /* falls through */
  21687. case LEN_:
  21688. state.mode = LEN;
  21689. /* falls through */
  21690. case LEN:
  21691. if (have >= 6 && left >= 258) {
  21692. //--- RESTORE() ---
  21693. strm.next_out = put;
  21694. strm.avail_out = left;
  21695. strm.next_in = next;
  21696. strm.avail_in = have;
  21697. state.hold = hold;
  21698. state.bits = bits;
  21699. //---
  21700. inflate_fast(strm, _out);
  21701. //--- LOAD() ---
  21702. put = strm.next_out;
  21703. output = strm.output;
  21704. left = strm.avail_out;
  21705. next = strm.next_in;
  21706. input = strm.input;
  21707. have = strm.avail_in;
  21708. hold = state.hold;
  21709. bits = state.bits;
  21710. //---
  21711. if (state.mode === TYPE) {
  21712. state.back = -1;
  21713. }
  21714. break;
  21715. }
  21716. state.back = 0;
  21717. for (;;) {
  21718. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  21719. here_bits = here >>> 24;
  21720. here_op = (here >>> 16) & 0xff;
  21721. here_val = here & 0xffff;
  21722. if (here_bits <= bits) { break; }
  21723. //--- PULLBYTE() ---//
  21724. if (have === 0) { break inf_leave; }
  21725. have--;
  21726. hold += input[next++] << bits;
  21727. bits += 8;
  21728. //---//
  21729. }
  21730. if (here_op && (here_op & 0xf0) === 0) {
  21731. last_bits = here_bits;
  21732. last_op = here_op;
  21733. last_val = here_val;
  21734. for (;;) {
  21735. here = state.lencode[last_val +
  21736. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  21737. here_bits = here >>> 24;
  21738. here_op = (here >>> 16) & 0xff;
  21739. here_val = here & 0xffff;
  21740. if ((last_bits + here_bits) <= bits) { break; }
  21741. //--- PULLBYTE() ---//
  21742. if (have === 0) { break inf_leave; }
  21743. have--;
  21744. hold += input[next++] << bits;
  21745. bits += 8;
  21746. //---//
  21747. }
  21748. //--- DROPBITS(last.bits) ---//
  21749. hold >>>= last_bits;
  21750. bits -= last_bits;
  21751. //---//
  21752. state.back += last_bits;
  21753. }
  21754. //--- DROPBITS(here.bits) ---//
  21755. hold >>>= here_bits;
  21756. bits -= here_bits;
  21757. //---//
  21758. state.back += here_bits;
  21759. state.length = here_val;
  21760. if (here_op === 0) {
  21761. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21762. // "inflate: literal '%c'\n" :
  21763. // "inflate: literal 0x%02x\n", here.val));
  21764. state.mode = LIT;
  21765. break;
  21766. }
  21767. if (here_op & 32) {
  21768. //Tracevv((stderr, "inflate: end of block\n"));
  21769. state.back = -1;
  21770. state.mode = TYPE;
  21771. break;
  21772. }
  21773. if (here_op & 64) {
  21774. strm.msg = 'invalid literal/length code';
  21775. state.mode = BAD;
  21776. break;
  21777. }
  21778. state.extra = here_op & 15;
  21779. state.mode = LENEXT;
  21780. /* falls through */
  21781. case LENEXT:
  21782. if (state.extra) {
  21783. //=== NEEDBITS(state.extra);
  21784. n = state.extra;
  21785. while (bits < n) {
  21786. if (have === 0) { break inf_leave; }
  21787. have--;
  21788. hold += input[next++] << bits;
  21789. bits += 8;
  21790. }
  21791. //===//
  21792. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21793. //--- DROPBITS(state.extra) ---//
  21794. hold >>>= state.extra;
  21795. bits -= state.extra;
  21796. //---//
  21797. state.back += state.extra;
  21798. }
  21799. //Tracevv((stderr, "inflate: length %u\n", state.length));
  21800. state.was = state.length;
  21801. state.mode = DIST;
  21802. /* falls through */
  21803. case DIST:
  21804. for (;;) {
  21805. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  21806. here_bits = here >>> 24;
  21807. here_op = (here >>> 16) & 0xff;
  21808. here_val = here & 0xffff;
  21809. if ((here_bits) <= bits) { break; }
  21810. //--- PULLBYTE() ---//
  21811. if (have === 0) { break inf_leave; }
  21812. have--;
  21813. hold += input[next++] << bits;
  21814. bits += 8;
  21815. //---//
  21816. }
  21817. if ((here_op & 0xf0) === 0) {
  21818. last_bits = here_bits;
  21819. last_op = here_op;
  21820. last_val = here_val;
  21821. for (;;) {
  21822. here = state.distcode[last_val +
  21823. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  21824. here_bits = here >>> 24;
  21825. here_op = (here >>> 16) & 0xff;
  21826. here_val = here & 0xffff;
  21827. if ((last_bits + here_bits) <= bits) { break; }
  21828. //--- PULLBYTE() ---//
  21829. if (have === 0) { break inf_leave; }
  21830. have--;
  21831. hold += input[next++] << bits;
  21832. bits += 8;
  21833. //---//
  21834. }
  21835. //--- DROPBITS(last.bits) ---//
  21836. hold >>>= last_bits;
  21837. bits -= last_bits;
  21838. //---//
  21839. state.back += last_bits;
  21840. }
  21841. //--- DROPBITS(here.bits) ---//
  21842. hold >>>= here_bits;
  21843. bits -= here_bits;
  21844. //---//
  21845. state.back += here_bits;
  21846. if (here_op & 64) {
  21847. strm.msg = 'invalid distance code';
  21848. state.mode = BAD;
  21849. break;
  21850. }
  21851. state.offset = here_val;
  21852. state.extra = (here_op) & 15;
  21853. state.mode = DISTEXT;
  21854. /* falls through */
  21855. case DISTEXT:
  21856. if (state.extra) {
  21857. //=== NEEDBITS(state.extra);
  21858. n = state.extra;
  21859. while (bits < n) {
  21860. if (have === 0) { break inf_leave; }
  21861. have--;
  21862. hold += input[next++] << bits;
  21863. bits += 8;
  21864. }
  21865. //===//
  21866. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21867. //--- DROPBITS(state.extra) ---//
  21868. hold >>>= state.extra;
  21869. bits -= state.extra;
  21870. //---//
  21871. state.back += state.extra;
  21872. }
  21873. //#ifdef INFLATE_STRICT
  21874. if (state.offset > state.dmax) {
  21875. strm.msg = 'invalid distance too far back';
  21876. state.mode = BAD;
  21877. break;
  21878. }
  21879. //#endif
  21880. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  21881. state.mode = MATCH;
  21882. /* falls through */
  21883. case MATCH:
  21884. if (left === 0) { break inf_leave; }
  21885. copy = _out - left;
  21886. if (state.offset > copy) { /* copy from window */
  21887. copy = state.offset - copy;
  21888. if (copy > state.whave) {
  21889. if (state.sane) {
  21890. strm.msg = 'invalid distance too far back';
  21891. state.mode = BAD;
  21892. break;
  21893. }
  21894. // (!) This block is disabled in zlib defailts,
  21895. // don't enable it for binary compatibility
  21896. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21897. // Trace((stderr, "inflate.c too far\n"));
  21898. // copy -= state.whave;
  21899. // if (copy > state.length) { copy = state.length; }
  21900. // if (copy > left) { copy = left; }
  21901. // left -= copy;
  21902. // state.length -= copy;
  21903. // do {
  21904. // output[put++] = 0;
  21905. // } while (--copy);
  21906. // if (state.length === 0) { state.mode = LEN; }
  21907. // break;
  21908. //#endif
  21909. }
  21910. if (copy > state.wnext) {
  21911. copy -= state.wnext;
  21912. from = state.wsize - copy;
  21913. }
  21914. else {
  21915. from = state.wnext - copy;
  21916. }
  21917. if (copy > state.length) { copy = state.length; }
  21918. from_source = state.window;
  21919. }
  21920. else { /* copy from output */
  21921. from_source = output;
  21922. from = put - state.offset;
  21923. copy = state.length;
  21924. }
  21925. if (copy > left) { copy = left; }
  21926. left -= copy;
  21927. state.length -= copy;
  21928. do {
  21929. output[put++] = from_source[from++];
  21930. } while (--copy);
  21931. if (state.length === 0) { state.mode = LEN; }
  21932. break;
  21933. case LIT:
  21934. if (left === 0) { break inf_leave; }
  21935. output[put++] = state.length;
  21936. left--;
  21937. state.mode = LEN;
  21938. break;
  21939. case CHECK:
  21940. if (state.wrap) {
  21941. //=== NEEDBITS(32);
  21942. while (bits < 32) {
  21943. if (have === 0) { break inf_leave; }
  21944. have--;
  21945. // Use '|' insdead of '+' to make sure that result is signed
  21946. hold |= input[next++] << bits;
  21947. bits += 8;
  21948. }
  21949. //===//
  21950. _out -= left;
  21951. strm.total_out += _out;
  21952. state.total += _out;
  21953. if (_out) {
  21954. strm.adler = state.check =
  21955. /*UPDATE(state.check, put - _out, _out);*/
  21956. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  21957. }
  21958. _out = left;
  21959. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  21960. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  21961. strm.msg = 'incorrect data check';
  21962. state.mode = BAD;
  21963. break;
  21964. }
  21965. //=== INITBITS();
  21966. hold = 0;
  21967. bits = 0;
  21968. //===//
  21969. //Tracev((stderr, "inflate: check matches trailer\n"));
  21970. }
  21971. state.mode = LENGTH;
  21972. /* falls through */
  21973. case LENGTH:
  21974. if (state.wrap && state.flags) {
  21975. //=== NEEDBITS(32);
  21976. while (bits < 32) {
  21977. if (have === 0) { break inf_leave; }
  21978. have--;
  21979. hold += input[next++] << bits;
  21980. bits += 8;
  21981. }
  21982. //===//
  21983. if (hold !== (state.total & 0xffffffff)) {
  21984. strm.msg = 'incorrect length check';
  21985. state.mode = BAD;
  21986. break;
  21987. }
  21988. //=== INITBITS();
  21989. hold = 0;
  21990. bits = 0;
  21991. //===//
  21992. //Tracev((stderr, "inflate: length matches trailer\n"));
  21993. }
  21994. state.mode = DONE;
  21995. /* falls through */
  21996. case DONE:
  21997. ret = Z_STREAM_END;
  21998. break inf_leave;
  21999. case BAD:
  22000. ret = Z_DATA_ERROR;
  22001. break inf_leave;
  22002. case MEM:
  22003. return Z_MEM_ERROR;
  22004. case SYNC:
  22005. /* falls through */
  22006. default:
  22007. return Z_STREAM_ERROR;
  22008. }
  22009. }
  22010. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  22011. /*
  22012. Return from inflate(), updating the total counts and the check value.
  22013. If there was no progress during the inflate() call, return a buffer
  22014. error. Call updatewindow() to create and/or update the window state.
  22015. Note: a memory error from inflate() is non-recoverable.
  22016. */
  22017. //--- RESTORE() ---
  22018. strm.next_out = put;
  22019. strm.avail_out = left;
  22020. strm.next_in = next;
  22021. strm.avail_in = have;
  22022. state.hold = hold;
  22023. state.bits = bits;
  22024. //---
  22025. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  22026. (state.mode < CHECK || flush !== Z_FINISH))) {
  22027. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  22028. state.mode = MEM;
  22029. return Z_MEM_ERROR;
  22030. }
  22031. }
  22032. _in -= strm.avail_in;
  22033. _out -= strm.avail_out;
  22034. strm.total_in += _in;
  22035. strm.total_out += _out;
  22036. state.total += _out;
  22037. if (state.wrap && _out) {
  22038. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  22039. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  22040. }
  22041. strm.data_type = state.bits + (state.last ? 64 : 0) +
  22042. (state.mode === TYPE ? 128 : 0) +
  22043. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  22044. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  22045. ret = Z_BUF_ERROR;
  22046. }
  22047. return ret;
  22048. }
  22049. function inflateEnd(strm) {
  22050. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  22051. return Z_STREAM_ERROR;
  22052. }
  22053. var state = strm.state;
  22054. if (state.window) {
  22055. state.window = null;
  22056. }
  22057. strm.state = null;
  22058. return Z_OK;
  22059. }
  22060. function inflateGetHeader(strm, head) {
  22061. var state;
  22062. /* check state */
  22063. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22064. state = strm.state;
  22065. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  22066. /* save header structure */
  22067. state.head = head;
  22068. head.done = false;
  22069. return Z_OK;
  22070. }
  22071. exports.inflateReset = inflateReset;
  22072. exports.inflateReset2 = inflateReset2;
  22073. exports.inflateResetKeep = inflateResetKeep;
  22074. exports.inflateInit = inflateInit;
  22075. exports.inflateInit2 = inflateInit2;
  22076. exports.inflate = inflate;
  22077. exports.inflateEnd = inflateEnd;
  22078. exports.inflateGetHeader = inflateGetHeader;
  22079. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  22080. /* Not implemented
  22081. exports.inflateCopy = inflateCopy;
  22082. exports.inflateGetDictionary = inflateGetDictionary;
  22083. exports.inflateMark = inflateMark;
  22084. exports.inflatePrime = inflatePrime;
  22085. exports.inflateSetDictionary = inflateSetDictionary;
  22086. exports.inflateSync = inflateSync;
  22087. exports.inflateSyncPoint = inflateSyncPoint;
  22088. exports.inflateUndermine = inflateUndermine;
  22089. */
  22090. },{"../utils/common":67,"./adler32":69,"./crc32":71,"./inffast":74,"./inftrees":76}],76:[function(require,module,exports){
  22091. 'use strict';
  22092. var utils = require('../utils/common');
  22093. var MAXBITS = 15;
  22094. var ENOUGH_LENS = 852;
  22095. var ENOUGH_DISTS = 592;
  22096. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22097. var CODES = 0;
  22098. var LENS = 1;
  22099. var DISTS = 2;
  22100. var lbase = [ /* Length codes 257..285 base */
  22101. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  22102. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  22103. ];
  22104. var lext = [ /* Length codes 257..285 extra */
  22105. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  22106. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  22107. ];
  22108. var dbase = [ /* Distance codes 0..29 base */
  22109. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  22110. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  22111. 8193, 12289, 16385, 24577, 0, 0
  22112. ];
  22113. var dext = [ /* Distance codes 0..29 extra */
  22114. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  22115. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  22116. 28, 28, 29, 29, 64, 64
  22117. ];
  22118. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  22119. {
  22120. var bits = opts.bits;
  22121. //here = opts.here; /* table entry for duplication */
  22122. var len = 0; /* a code's length in bits */
  22123. var sym = 0; /* index of code symbols */
  22124. var min = 0, max = 0; /* minimum and maximum code lengths */
  22125. var root = 0; /* number of index bits for root table */
  22126. var curr = 0; /* number of index bits for current table */
  22127. var drop = 0; /* code bits to drop for sub-table */
  22128. var left = 0; /* number of prefix codes available */
  22129. var used = 0; /* code entries in table used */
  22130. var huff = 0; /* Huffman code */
  22131. var incr; /* for incrementing code, index */
  22132. var fill; /* index for replicating entries */
  22133. var low; /* low bits for current root entry */
  22134. var mask; /* mask for low root bits */
  22135. var next; /* next available space in table */
  22136. var base = null; /* base value table to use */
  22137. var base_index = 0;
  22138. // var shoextra; /* extra bits table to use */
  22139. var end; /* use base and extra for symbol > end */
  22140. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  22141. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  22142. var extra = null;
  22143. var extra_index = 0;
  22144. var here_bits, here_op, here_val;
  22145. /*
  22146. Process a set of code lengths to create a canonical Huffman code. The
  22147. code lengths are lens[0..codes-1]. Each length corresponds to the
  22148. symbols 0..codes-1. The Huffman code is generated by first sorting the
  22149. symbols by length from short to long, and retaining the symbol order
  22150. for codes with equal lengths. Then the code starts with all zero bits
  22151. for the first code of the shortest length, and the codes are integer
  22152. increments for the same length, and zeros are appended as the length
  22153. increases. For the deflate format, these bits are stored backwards
  22154. from their more natural integer increment ordering, and so when the
  22155. decoding tables are built in the large loop below, the integer codes
  22156. are incremented backwards.
  22157. This routine assumes, but does not check, that all of the entries in
  22158. lens[] are in the range 0..MAXBITS. The caller must assure this.
  22159. 1..MAXBITS is interpreted as that code length. zero means that that
  22160. symbol does not occur in this code.
  22161. The codes are sorted by computing a count of codes for each length,
  22162. creating from that a table of starting indices for each length in the
  22163. sorted table, and then entering the symbols in order in the sorted
  22164. table. The sorted table is work[], with that space being provided by
  22165. the caller.
  22166. The length counts are used for other purposes as well, i.e. finding
  22167. the minimum and maximum length codes, determining if there are any
  22168. codes at all, checking for a valid set of lengths, and looking ahead
  22169. at length counts to determine sub-table sizes when building the
  22170. decoding tables.
  22171. */
  22172. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  22173. for (len = 0; len <= MAXBITS; len++) {
  22174. count[len] = 0;
  22175. }
  22176. for (sym = 0; sym < codes; sym++) {
  22177. count[lens[lens_index + sym]]++;
  22178. }
  22179. /* bound code lengths, force root to be within code lengths */
  22180. root = bits;
  22181. for (max = MAXBITS; max >= 1; max--) {
  22182. if (count[max] !== 0) { break; }
  22183. }
  22184. if (root > max) {
  22185. root = max;
  22186. }
  22187. if (max === 0) { /* no symbols to code at all */
  22188. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  22189. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  22190. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  22191. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  22192. //table.op[opts.table_index] = 64;
  22193. //table.bits[opts.table_index] = 1;
  22194. //table.val[opts.table_index++] = 0;
  22195. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  22196. opts.bits = 1;
  22197. return 0; /* no symbols, but wait for decoding to report error */
  22198. }
  22199. for (min = 1; min < max; min++) {
  22200. if (count[min] !== 0) { break; }
  22201. }
  22202. if (root < min) {
  22203. root = min;
  22204. }
  22205. /* check for an over-subscribed or incomplete set of lengths */
  22206. left = 1;
  22207. for (len = 1; len <= MAXBITS; len++) {
  22208. left <<= 1;
  22209. left -= count[len];
  22210. if (left < 0) {
  22211. return -1;
  22212. } /* over-subscribed */
  22213. }
  22214. if (left > 0 && (type === CODES || max !== 1)) {
  22215. return -1; /* incomplete set */
  22216. }
  22217. /* generate offsets into symbol table for each length for sorting */
  22218. offs[1] = 0;
  22219. for (len = 1; len < MAXBITS; len++) {
  22220. offs[len + 1] = offs[len] + count[len];
  22221. }
  22222. /* sort symbols by length, by symbol order within each length */
  22223. for (sym = 0; sym < codes; sym++) {
  22224. if (lens[lens_index + sym] !== 0) {
  22225. work[offs[lens[lens_index + sym]]++] = sym;
  22226. }
  22227. }
  22228. /*
  22229. Create and fill in decoding tables. In this loop, the table being
  22230. filled is at next and has curr index bits. The code being used is huff
  22231. with length len. That code is converted to an index by dropping drop
  22232. bits off of the bottom. For codes where len is less than drop + curr,
  22233. those top drop + curr - len bits are incremented through all values to
  22234. fill the table with replicated entries.
  22235. root is the number of index bits for the root table. When len exceeds
  22236. root, sub-tables are created pointed to by the root entry with an index
  22237. of the low root bits of huff. This is saved in low to check for when a
  22238. new sub-table should be started. drop is zero when the root table is
  22239. being filled, and drop is root when sub-tables are being filled.
  22240. When a new sub-table is needed, it is necessary to look ahead in the
  22241. code lengths to determine what size sub-table is needed. The length
  22242. counts are used for this, and so count[] is decremented as codes are
  22243. entered in the tables.
  22244. used keeps track of how many table entries have been allocated from the
  22245. provided *table space. It is checked for LENS and DIST tables against
  22246. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  22247. the initial root table size constants. See the comments in inftrees.h
  22248. for more information.
  22249. sym increments through all symbols, and the loop terminates when
  22250. all codes of length max, i.e. all codes, have been processed. This
  22251. routine permits incomplete codes, so another loop after this one fills
  22252. in the rest of the decoding tables with invalid code markers.
  22253. */
  22254. /* set up for code type */
  22255. // poor man optimization - use if-else instead of switch,
  22256. // to avoid deopts in old v8
  22257. if (type === CODES) {
  22258. base = extra = work; /* dummy value--not used */
  22259. end = 19;
  22260. } else if (type === LENS) {
  22261. base = lbase;
  22262. base_index -= 257;
  22263. extra = lext;
  22264. extra_index -= 257;
  22265. end = 256;
  22266. } else { /* DISTS */
  22267. base = dbase;
  22268. extra = dext;
  22269. end = -1;
  22270. }
  22271. /* initialize opts for loop */
  22272. huff = 0; /* starting code */
  22273. sym = 0; /* starting code symbol */
  22274. len = min; /* starting code length */
  22275. next = table_index; /* current table to fill in */
  22276. curr = root; /* current table index bits */
  22277. drop = 0; /* current bits to drop from code for index */
  22278. low = -1; /* trigger new sub-table when len > root */
  22279. used = 1 << root; /* use root table entries */
  22280. mask = used - 1; /* mask for comparing low */
  22281. /* check available table space */
  22282. if ((type === LENS && used > ENOUGH_LENS) ||
  22283. (type === DISTS && used > ENOUGH_DISTS)) {
  22284. return 1;
  22285. }
  22286. var i=0;
  22287. /* process all codes and make table entries */
  22288. for (;;) {
  22289. i++;
  22290. /* create table entry */
  22291. here_bits = len - drop;
  22292. if (work[sym] < end) {
  22293. here_op = 0;
  22294. here_val = work[sym];
  22295. }
  22296. else if (work[sym] > end) {
  22297. here_op = extra[extra_index + work[sym]];
  22298. here_val = base[base_index + work[sym]];
  22299. }
  22300. else {
  22301. here_op = 32 + 64; /* end of block */
  22302. here_val = 0;
  22303. }
  22304. /* replicate for those indices with low len bits equal to huff */
  22305. incr = 1 << (len - drop);
  22306. fill = 1 << curr;
  22307. min = fill; /* save offset to next table */
  22308. do {
  22309. fill -= incr;
  22310. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  22311. } while (fill !== 0);
  22312. /* backwards increment the len-bit code huff */
  22313. incr = 1 << (len - 1);
  22314. while (huff & incr) {
  22315. incr >>= 1;
  22316. }
  22317. if (incr !== 0) {
  22318. huff &= incr - 1;
  22319. huff += incr;
  22320. } else {
  22321. huff = 0;
  22322. }
  22323. /* go to next symbol, update count, len */
  22324. sym++;
  22325. if (--count[len] === 0) {
  22326. if (len === max) { break; }
  22327. len = lens[lens_index + work[sym]];
  22328. }
  22329. /* create new sub-table if needed */
  22330. if (len > root && (huff & mask) !== low) {
  22331. /* if first time, transition to sub-tables */
  22332. if (drop === 0) {
  22333. drop = root;
  22334. }
  22335. /* increment past last table */
  22336. next += min; /* here min is 1 << curr */
  22337. /* determine length of next table */
  22338. curr = len - drop;
  22339. left = 1 << curr;
  22340. while (curr + drop < max) {
  22341. left -= count[curr + drop];
  22342. if (left <= 0) { break; }
  22343. curr++;
  22344. left <<= 1;
  22345. }
  22346. /* check for enough space */
  22347. used += 1 << curr;
  22348. if ((type === LENS && used > ENOUGH_LENS) ||
  22349. (type === DISTS && used > ENOUGH_DISTS)) {
  22350. return 1;
  22351. }
  22352. /* point entry in root table to sub-table */
  22353. low = huff & mask;
  22354. /*table.op[low] = curr;
  22355. table.bits[low] = root;
  22356. table.val[low] = next - opts.table_index;*/
  22357. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  22358. }
  22359. }
  22360. /* fill in remaining table entry if code is incomplete (guaranteed to have
  22361. at most one remaining entry, since if the code is incomplete, the
  22362. maximum code length that was allowed to get this far is one bit) */
  22363. if (huff !== 0) {
  22364. //table.op[next + huff] = 64; /* invalid code marker */
  22365. //table.bits[next + huff] = len - drop;
  22366. //table.val[next + huff] = 0;
  22367. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  22368. }
  22369. /* set return parameters */
  22370. //opts.table_index += used;
  22371. opts.bits = root;
  22372. return 0;
  22373. };
  22374. },{"../utils/common":67}],77:[function(require,module,exports){
  22375. 'use strict';
  22376. module.exports = {
  22377. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  22378. '1': 'stream end', /* Z_STREAM_END 1 */
  22379. '0': '', /* Z_OK 0 */
  22380. '-1': 'file error', /* Z_ERRNO (-1) */
  22381. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  22382. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  22383. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  22384. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  22385. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  22386. };
  22387. },{}],78:[function(require,module,exports){
  22388. 'use strict';
  22389. var utils = require('../utils/common');
  22390. /* Public constants ==========================================================*/
  22391. /* ===========================================================================*/
  22392. //var Z_FILTERED = 1;
  22393. //var Z_HUFFMAN_ONLY = 2;
  22394. //var Z_RLE = 3;
  22395. var Z_FIXED = 4;
  22396. //var Z_DEFAULT_STRATEGY = 0;
  22397. /* Possible values of the data_type field (though see inflate()) */
  22398. var Z_BINARY = 0;
  22399. var Z_TEXT = 1;
  22400. //var Z_ASCII = 1; // = Z_TEXT
  22401. var Z_UNKNOWN = 2;
  22402. /*============================================================================*/
  22403. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  22404. // From zutil.h
  22405. var STORED_BLOCK = 0;
  22406. var STATIC_TREES = 1;
  22407. var DYN_TREES = 2;
  22408. /* The three kinds of block type */
  22409. var MIN_MATCH = 3;
  22410. var MAX_MATCH = 258;
  22411. /* The minimum and maximum match lengths */
  22412. // From deflate.h
  22413. /* ===========================================================================
  22414. * Internal compression state.
  22415. */
  22416. var LENGTH_CODES = 29;
  22417. /* number of length codes, not counting the special END_BLOCK code */
  22418. var LITERALS = 256;
  22419. /* number of literal bytes 0..255 */
  22420. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  22421. /* number of Literal or Length codes, including the END_BLOCK code */
  22422. var D_CODES = 30;
  22423. /* number of distance codes */
  22424. var BL_CODES = 19;
  22425. /* number of codes used to transfer the bit lengths */
  22426. var HEAP_SIZE = 2*L_CODES + 1;
  22427. /* maximum heap size */
  22428. var MAX_BITS = 15;
  22429. /* All codes must not exceed MAX_BITS bits */
  22430. var Buf_size = 16;
  22431. /* size of bit buffer in bi_buf */
  22432. /* ===========================================================================
  22433. * Constants
  22434. */
  22435. var MAX_BL_BITS = 7;
  22436. /* Bit length codes must not exceed MAX_BL_BITS bits */
  22437. var END_BLOCK = 256;
  22438. /* end of block literal code */
  22439. var REP_3_6 = 16;
  22440. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  22441. var REPZ_3_10 = 17;
  22442. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  22443. var REPZ_11_138 = 18;
  22444. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  22445. var extra_lbits = /* extra bits for each length code */
  22446. [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];
  22447. var extra_dbits = /* extra bits for each distance code */
  22448. [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];
  22449. var extra_blbits = /* extra bits for each bit length code */
  22450. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  22451. var bl_order =
  22452. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  22453. /* The lengths of the bit length codes are sent in order of decreasing
  22454. * probability, to avoid transmitting the lengths for unused bit length codes.
  22455. */
  22456. /* ===========================================================================
  22457. * Local data. These are initialized only once.
  22458. */
  22459. // We pre-fill arrays with 0 to avoid uninitialized gaps
  22460. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  22461. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  22462. var static_ltree = new Array((L_CODES+2) * 2);
  22463. zero(static_ltree);
  22464. /* The static literal tree. Since the bit lengths are imposed, there is no
  22465. * need for the L_CODES extra codes used during heap construction. However
  22466. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  22467. * below).
  22468. */
  22469. var static_dtree = new Array(D_CODES * 2);
  22470. zero(static_dtree);
  22471. /* The static distance tree. (Actually a trivial tree since all codes use
  22472. * 5 bits.)
  22473. */
  22474. var _dist_code = new Array(DIST_CODE_LEN);
  22475. zero(_dist_code);
  22476. /* Distance codes. The first 256 values correspond to the distances
  22477. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  22478. * the 15 bit distances.
  22479. */
  22480. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  22481. zero(_length_code);
  22482. /* length code for each normalized match length (0 == MIN_MATCH) */
  22483. var base_length = new Array(LENGTH_CODES);
  22484. zero(base_length);
  22485. /* First normalized length for each code (0 = MIN_MATCH) */
  22486. var base_dist = new Array(D_CODES);
  22487. zero(base_dist);
  22488. /* First normalized distance for each code (0 = distance of 1) */
  22489. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  22490. this.static_tree = static_tree; /* static tree or NULL */
  22491. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  22492. this.extra_base = extra_base; /* base index for extra_bits */
  22493. this.elems = elems; /* max number of elements in the tree */
  22494. this.max_length = max_length; /* max bit length for the codes */
  22495. // show if `static_tree` has data or dummy - needed for monomorphic objects
  22496. this.has_stree = static_tree && static_tree.length;
  22497. };
  22498. var static_l_desc;
  22499. var static_d_desc;
  22500. var static_bl_desc;
  22501. var TreeDesc = function(dyn_tree, stat_desc) {
  22502. this.dyn_tree = dyn_tree; /* the dynamic tree */
  22503. this.max_code = 0; /* largest code with non zero frequency */
  22504. this.stat_desc = stat_desc; /* the corresponding static tree */
  22505. };
  22506. function d_code(dist) {
  22507. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  22508. }
  22509. /* ===========================================================================
  22510. * Output a short LSB first on the stream.
  22511. * IN assertion: there is enough room in pendingBuf.
  22512. */
  22513. function put_short (s, w) {
  22514. // put_byte(s, (uch)((w) & 0xff));
  22515. // put_byte(s, (uch)((ush)(w) >> 8));
  22516. s.pending_buf[s.pending++] = (w) & 0xff;
  22517. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  22518. }
  22519. /* ===========================================================================
  22520. * Send a value on a given number of bits.
  22521. * IN assertion: length <= 16 and value fits in length bits.
  22522. */
  22523. function send_bits(s, value, length) {
  22524. if (s.bi_valid > (Buf_size - length)) {
  22525. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  22526. put_short(s, s.bi_buf);
  22527. s.bi_buf = value >> (Buf_size - s.bi_valid);
  22528. s.bi_valid += length - Buf_size;
  22529. } else {
  22530. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  22531. s.bi_valid += length;
  22532. }
  22533. }
  22534. function send_code(s, c, tree) {
  22535. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  22536. }
  22537. /* ===========================================================================
  22538. * Reverse the first len bits of a code, using straightforward code (a faster
  22539. * method would use a table)
  22540. * IN assertion: 1 <= len <= 15
  22541. */
  22542. function bi_reverse(code, len) {
  22543. var res = 0;
  22544. do {
  22545. res |= code & 1;
  22546. code >>>= 1;
  22547. res <<= 1;
  22548. } while (--len > 0);
  22549. return res >>> 1;
  22550. }
  22551. /* ===========================================================================
  22552. * Flush the bit buffer, keeping at most 7 bits in it.
  22553. */
  22554. function bi_flush(s) {
  22555. if (s.bi_valid === 16) {
  22556. put_short(s, s.bi_buf);
  22557. s.bi_buf = 0;
  22558. s.bi_valid = 0;
  22559. } else if (s.bi_valid >= 8) {
  22560. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  22561. s.bi_buf >>= 8;
  22562. s.bi_valid -= 8;
  22563. }
  22564. }
  22565. /* ===========================================================================
  22566. * Compute the optimal bit lengths for a tree and update the total bit length
  22567. * for the current block.
  22568. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  22569. * above are the tree nodes sorted by increasing frequency.
  22570. * OUT assertions: the field len is set to the optimal bit length, the
  22571. * array bl_count contains the frequencies for each bit length.
  22572. * The length opt_len is updated; static_len is also updated if stree is
  22573. * not null.
  22574. */
  22575. function gen_bitlen(s, desc)
  22576. // deflate_state *s;
  22577. // tree_desc *desc; /* the tree descriptor */
  22578. {
  22579. var tree = desc.dyn_tree;
  22580. var max_code = desc.max_code;
  22581. var stree = desc.stat_desc.static_tree;
  22582. var has_stree = desc.stat_desc.has_stree;
  22583. var extra = desc.stat_desc.extra_bits;
  22584. var base = desc.stat_desc.extra_base;
  22585. var max_length = desc.stat_desc.max_length;
  22586. var h; /* heap index */
  22587. var n, m; /* iterate over the tree elements */
  22588. var bits; /* bit length */
  22589. var xbits; /* extra bits */
  22590. var f; /* frequency */
  22591. var overflow = 0; /* number of elements with bit length too large */
  22592. for (bits = 0; bits <= MAX_BITS; bits++) {
  22593. s.bl_count[bits] = 0;
  22594. }
  22595. /* In a first pass, compute the optimal bit lengths (which may
  22596. * overflow in the case of the bit length tree).
  22597. */
  22598. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  22599. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  22600. n = s.heap[h];
  22601. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  22602. if (bits > max_length) {
  22603. bits = max_length;
  22604. overflow++;
  22605. }
  22606. tree[n*2 + 1]/*.Len*/ = bits;
  22607. /* We overwrite tree[n].Dad which is no longer needed */
  22608. if (n > max_code) { continue; } /* not a leaf node */
  22609. s.bl_count[bits]++;
  22610. xbits = 0;
  22611. if (n >= base) {
  22612. xbits = extra[n-base];
  22613. }
  22614. f = tree[n * 2]/*.Freq*/;
  22615. s.opt_len += f * (bits + xbits);
  22616. if (has_stree) {
  22617. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  22618. }
  22619. }
  22620. if (overflow === 0) { return; }
  22621. // Trace((stderr,"\nbit length overflow\n"));
  22622. /* This happens for example on obj2 and pic of the Calgary corpus */
  22623. /* Find the first bit length which could increase: */
  22624. do {
  22625. bits = max_length-1;
  22626. while (s.bl_count[bits] === 0) { bits--; }
  22627. s.bl_count[bits]--; /* move one leaf down the tree */
  22628. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  22629. s.bl_count[max_length]--;
  22630. /* The brother of the overflow item also moves one step up,
  22631. * but this does not affect bl_count[max_length]
  22632. */
  22633. overflow -= 2;
  22634. } while (overflow > 0);
  22635. /* Now recompute all bit lengths, scanning in increasing frequency.
  22636. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  22637. * lengths instead of fixing only the wrong ones. This idea is taken
  22638. * from 'ar' written by Haruhiko Okumura.)
  22639. */
  22640. for (bits = max_length; bits !== 0; bits--) {
  22641. n = s.bl_count[bits];
  22642. while (n !== 0) {
  22643. m = s.heap[--h];
  22644. if (m > max_code) { continue; }
  22645. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  22646. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  22647. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  22648. tree[m*2 + 1]/*.Len*/ = bits;
  22649. }
  22650. n--;
  22651. }
  22652. }
  22653. }
  22654. /* ===========================================================================
  22655. * Generate the codes for a given tree and bit counts (which need not be
  22656. * optimal).
  22657. * IN assertion: the array bl_count contains the bit length statistics for
  22658. * the given tree and the field len is set for all tree elements.
  22659. * OUT assertion: the field code is set for all tree elements of non
  22660. * zero code length.
  22661. */
  22662. function gen_codes(tree, max_code, bl_count)
  22663. // ct_data *tree; /* the tree to decorate */
  22664. // int max_code; /* largest code with non zero frequency */
  22665. // ushf *bl_count; /* number of codes at each bit length */
  22666. {
  22667. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  22668. var code = 0; /* running code value */
  22669. var bits; /* bit index */
  22670. var n; /* code index */
  22671. /* The distribution counts are first used to generate the code values
  22672. * without bit reversal.
  22673. */
  22674. for (bits = 1; bits <= MAX_BITS; bits++) {
  22675. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  22676. }
  22677. /* Check that the bit counts in bl_count are consistent. The last code
  22678. * must be all ones.
  22679. */
  22680. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  22681. // "inconsistent bit counts");
  22682. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  22683. for (n = 0; n <= max_code; n++) {
  22684. var len = tree[n*2 + 1]/*.Len*/;
  22685. if (len === 0) { continue; }
  22686. /* Now reverse the bits */
  22687. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  22688. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  22689. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  22690. }
  22691. }
  22692. /* ===========================================================================
  22693. * Initialize the various 'constant' tables.
  22694. */
  22695. function tr_static_init() {
  22696. var n; /* iterates over tree elements */
  22697. var bits; /* bit counter */
  22698. var length; /* length value */
  22699. var code; /* code value */
  22700. var dist; /* distance index */
  22701. var bl_count = new Array(MAX_BITS+1);
  22702. /* number of codes at each bit length for an optimal tree */
  22703. // do check in _tr_init()
  22704. //if (static_init_done) return;
  22705. /* For some embedded targets, global variables are not initialized: */
  22706. /*#ifdef NO_INIT_GLOBAL_POINTERS
  22707. static_l_desc.static_tree = static_ltree;
  22708. static_l_desc.extra_bits = extra_lbits;
  22709. static_d_desc.static_tree = static_dtree;
  22710. static_d_desc.extra_bits = extra_dbits;
  22711. static_bl_desc.extra_bits = extra_blbits;
  22712. #endif*/
  22713. /* Initialize the mapping length (0..255) -> length code (0..28) */
  22714. length = 0;
  22715. for (code = 0; code < LENGTH_CODES-1; code++) {
  22716. base_length[code] = length;
  22717. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  22718. _length_code[length++] = code;
  22719. }
  22720. }
  22721. //Assert (length == 256, "tr_static_init: length != 256");
  22722. /* Note that the length 255 (match length 258) can be represented
  22723. * in two different ways: code 284 + 5 bits or code 285, so we
  22724. * overwrite length_code[255] to use the best encoding:
  22725. */
  22726. _length_code[length-1] = code;
  22727. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  22728. dist = 0;
  22729. for (code = 0 ; code < 16; code++) {
  22730. base_dist[code] = dist;
  22731. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  22732. _dist_code[dist++] = code;
  22733. }
  22734. }
  22735. //Assert (dist == 256, "tr_static_init: dist != 256");
  22736. dist >>= 7; /* from now on, all distances are divided by 128 */
  22737. for ( ; code < D_CODES; code++) {
  22738. base_dist[code] = dist << 7;
  22739. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  22740. _dist_code[256 + dist++] = code;
  22741. }
  22742. }
  22743. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  22744. /* Construct the codes of the static literal tree */
  22745. for (bits = 0; bits <= MAX_BITS; bits++) {
  22746. bl_count[bits] = 0;
  22747. }
  22748. n = 0;
  22749. while (n <= 143) {
  22750. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22751. n++;
  22752. bl_count[8]++;
  22753. }
  22754. while (n <= 255) {
  22755. static_ltree[n*2 + 1]/*.Len*/ = 9;
  22756. n++;
  22757. bl_count[9]++;
  22758. }
  22759. while (n <= 279) {
  22760. static_ltree[n*2 + 1]/*.Len*/ = 7;
  22761. n++;
  22762. bl_count[7]++;
  22763. }
  22764. while (n <= 287) {
  22765. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22766. n++;
  22767. bl_count[8]++;
  22768. }
  22769. /* Codes 286 and 287 do not exist, but we must include them in the
  22770. * tree construction to get a canonical Huffman tree (longest code
  22771. * all ones)
  22772. */
  22773. gen_codes(static_ltree, L_CODES+1, bl_count);
  22774. /* The static distance tree is trivial: */
  22775. for (n = 0; n < D_CODES; n++) {
  22776. static_dtree[n*2 + 1]/*.Len*/ = 5;
  22777. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  22778. }
  22779. // Now data ready and we can init static trees
  22780. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  22781. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  22782. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  22783. //static_init_done = true;
  22784. }
  22785. /* ===========================================================================
  22786. * Initialize a new block.
  22787. */
  22788. function init_block(s) {
  22789. var n; /* iterates over tree elements */
  22790. /* Initialize the trees. */
  22791. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  22792. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  22793. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  22794. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  22795. s.opt_len = s.static_len = 0;
  22796. s.last_lit = s.matches = 0;
  22797. }
  22798. /* ===========================================================================
  22799. * Flush the bit buffer and align the output on a byte boundary
  22800. */
  22801. function bi_windup(s)
  22802. {
  22803. if (s.bi_valid > 8) {
  22804. put_short(s, s.bi_buf);
  22805. } else if (s.bi_valid > 0) {
  22806. //put_byte(s, (Byte)s->bi_buf);
  22807. s.pending_buf[s.pending++] = s.bi_buf;
  22808. }
  22809. s.bi_buf = 0;
  22810. s.bi_valid = 0;
  22811. }
  22812. /* ===========================================================================
  22813. * Copy a stored block, storing first the length and its
  22814. * one's complement if requested.
  22815. */
  22816. function copy_block(s, buf, len, header)
  22817. //DeflateState *s;
  22818. //charf *buf; /* the input data */
  22819. //unsigned len; /* its length */
  22820. //int header; /* true if block header must be written */
  22821. {
  22822. bi_windup(s); /* align on byte boundary */
  22823. if (header) {
  22824. put_short(s, len);
  22825. put_short(s, ~len);
  22826. }
  22827. // while (len--) {
  22828. // put_byte(s, *buf++);
  22829. // }
  22830. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  22831. s.pending += len;
  22832. }
  22833. /* ===========================================================================
  22834. * Compares to subtrees, using the tree depth as tie breaker when
  22835. * the subtrees have equal frequency. This minimizes the worst case length.
  22836. */
  22837. function smaller(tree, n, m, depth) {
  22838. var _n2 = n*2;
  22839. var _m2 = m*2;
  22840. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  22841. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  22842. }
  22843. /* ===========================================================================
  22844. * Restore the heap property by moving down the tree starting at node k,
  22845. * exchanging a node with the smallest of its two sons if necessary, stopping
  22846. * when the heap property is re-established (each father smaller than its
  22847. * two sons).
  22848. */
  22849. function pqdownheap(s, tree, k)
  22850. // deflate_state *s;
  22851. // ct_data *tree; /* the tree to restore */
  22852. // int k; /* node to move down */
  22853. {
  22854. var v = s.heap[k];
  22855. var j = k << 1; /* left son of k */
  22856. while (j <= s.heap_len) {
  22857. /* Set j to the smallest of the two sons: */
  22858. if (j < s.heap_len &&
  22859. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  22860. j++;
  22861. }
  22862. /* Exit if v is smaller than both sons */
  22863. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  22864. /* Exchange v with the smallest son */
  22865. s.heap[k] = s.heap[j];
  22866. k = j;
  22867. /* And continue down the tree, setting j to the left son of k */
  22868. j <<= 1;
  22869. }
  22870. s.heap[k] = v;
  22871. }
  22872. // inlined manually
  22873. // var SMALLEST = 1;
  22874. /* ===========================================================================
  22875. * Send the block data compressed using the given Huffman trees
  22876. */
  22877. function compress_block(s, ltree, dtree)
  22878. // deflate_state *s;
  22879. // const ct_data *ltree; /* literal tree */
  22880. // const ct_data *dtree; /* distance tree */
  22881. {
  22882. var dist; /* distance of matched string */
  22883. var lc; /* match length or unmatched char (if dist == 0) */
  22884. var lx = 0; /* running index in l_buf */
  22885. var code; /* the code to send */
  22886. var extra; /* number of extra bits to send */
  22887. if (s.last_lit !== 0) {
  22888. do {
  22889. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  22890. lc = s.pending_buf[s.l_buf + lx];
  22891. lx++;
  22892. if (dist === 0) {
  22893. send_code(s, lc, ltree); /* send a literal byte */
  22894. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  22895. } else {
  22896. /* Here, lc is the match length - MIN_MATCH */
  22897. code = _length_code[lc];
  22898. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  22899. extra = extra_lbits[code];
  22900. if (extra !== 0) {
  22901. lc -= base_length[code];
  22902. send_bits(s, lc, extra); /* send the extra length bits */
  22903. }
  22904. dist--; /* dist is now the match distance - 1 */
  22905. code = d_code(dist);
  22906. //Assert (code < D_CODES, "bad d_code");
  22907. send_code(s, code, dtree); /* send the distance code */
  22908. extra = extra_dbits[code];
  22909. if (extra !== 0) {
  22910. dist -= base_dist[code];
  22911. send_bits(s, dist, extra); /* send the extra distance bits */
  22912. }
  22913. } /* literal or match pair ? */
  22914. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  22915. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  22916. // "pendingBuf overflow");
  22917. } while (lx < s.last_lit);
  22918. }
  22919. send_code(s, END_BLOCK, ltree);
  22920. }
  22921. /* ===========================================================================
  22922. * Construct one Huffman tree and assigns the code bit strings and lengths.
  22923. * Update the total bit length for the current block.
  22924. * IN assertion: the field freq is set for all tree elements.
  22925. * OUT assertions: the fields len and code are set to the optimal bit length
  22926. * and corresponding code. The length opt_len is updated; static_len is
  22927. * also updated if stree is not null. The field max_code is set.
  22928. */
  22929. function build_tree(s, desc)
  22930. // deflate_state *s;
  22931. // tree_desc *desc; /* the tree descriptor */
  22932. {
  22933. var tree = desc.dyn_tree;
  22934. var stree = desc.stat_desc.static_tree;
  22935. var has_stree = desc.stat_desc.has_stree;
  22936. var elems = desc.stat_desc.elems;
  22937. var n, m; /* iterate over heap elements */
  22938. var max_code = -1; /* largest code with non zero frequency */
  22939. var node; /* new node being created */
  22940. /* Construct the initial heap, with least frequent element in
  22941. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  22942. * heap[0] is not used.
  22943. */
  22944. s.heap_len = 0;
  22945. s.heap_max = HEAP_SIZE;
  22946. for (n = 0; n < elems; n++) {
  22947. if (tree[n * 2]/*.Freq*/ !== 0) {
  22948. s.heap[++s.heap_len] = max_code = n;
  22949. s.depth[n] = 0;
  22950. } else {
  22951. tree[n*2 + 1]/*.Len*/ = 0;
  22952. }
  22953. }
  22954. /* The pkzip format requires that at least one distance code exists,
  22955. * and that at least one bit should be sent even if there is only one
  22956. * possible code. So to avoid special checks later on we force at least
  22957. * two codes of non zero frequency.
  22958. */
  22959. while (s.heap_len < 2) {
  22960. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  22961. tree[node * 2]/*.Freq*/ = 1;
  22962. s.depth[node] = 0;
  22963. s.opt_len--;
  22964. if (has_stree) {
  22965. s.static_len -= stree[node*2 + 1]/*.Len*/;
  22966. }
  22967. /* node is 0 or 1 so it does not have extra bits */
  22968. }
  22969. desc.max_code = max_code;
  22970. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  22971. * establish sub-heaps of increasing lengths:
  22972. */
  22973. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22974. /* Construct the Huffman tree by repeatedly combining the least two
  22975. * frequent nodes.
  22976. */
  22977. node = elems; /* next internal node of the tree */
  22978. do {
  22979. //pqremove(s, tree, n); /* n = node of least frequency */
  22980. /*** pqremove ***/
  22981. n = s.heap[1/*SMALLEST*/];
  22982. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22983. pqdownheap(s, tree, 1/*SMALLEST*/);
  22984. /***/
  22985. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22986. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22987. s.heap[--s.heap_max] = m;
  22988. /* Create a new node father of n and m */
  22989. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22990. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22991. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  22992. /* and insert the new node in the heap */
  22993. s.heap[1/*SMALLEST*/] = node++;
  22994. pqdownheap(s, tree, 1/*SMALLEST*/);
  22995. } while (s.heap_len >= 2);
  22996. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22997. /* At this point, the fields freq and dad are set. We can now
  22998. * generate the bit lengths.
  22999. */
  23000. gen_bitlen(s, desc);
  23001. /* The field len is now set, we can generate the bit codes */
  23002. gen_codes(tree, max_code, s.bl_count);
  23003. }
  23004. /* ===========================================================================
  23005. * Scan a literal or distance tree to determine the frequencies of the codes
  23006. * in the bit length tree.
  23007. */
  23008. function scan_tree(s, tree, max_code)
  23009. // deflate_state *s;
  23010. // ct_data *tree; /* the tree to be scanned */
  23011. // int max_code; /* and its largest code of non zero frequency */
  23012. {
  23013. var n; /* iterates over all tree elements */
  23014. var prevlen = -1; /* last emitted length */
  23015. var curlen; /* length of current code */
  23016. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23017. var count = 0; /* repeat count of the current code */
  23018. var max_count = 7; /* max repeat count */
  23019. var min_count = 4; /* min repeat count */
  23020. if (nextlen === 0) {
  23021. max_count = 138;
  23022. min_count = 3;
  23023. }
  23024. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  23025. for (n = 0; n <= max_code; n++) {
  23026. curlen = nextlen;
  23027. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23028. if (++count < max_count && curlen === nextlen) {
  23029. continue;
  23030. } else if (count < min_count) {
  23031. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  23032. } else if (curlen !== 0) {
  23033. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  23034. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  23035. } else if (count <= 10) {
  23036. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  23037. } else {
  23038. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  23039. }
  23040. count = 0;
  23041. prevlen = curlen;
  23042. if (nextlen === 0) {
  23043. max_count = 138;
  23044. min_count = 3;
  23045. } else if (curlen === nextlen) {
  23046. max_count = 6;
  23047. min_count = 3;
  23048. } else {
  23049. max_count = 7;
  23050. min_count = 4;
  23051. }
  23052. }
  23053. }
  23054. /* ===========================================================================
  23055. * Send a literal or distance tree in compressed form, using the codes in
  23056. * bl_tree.
  23057. */
  23058. function send_tree(s, tree, max_code)
  23059. // deflate_state *s;
  23060. // ct_data *tree; /* the tree to be scanned */
  23061. // int max_code; /* and its largest code of non zero frequency */
  23062. {
  23063. var n; /* iterates over all tree elements */
  23064. var prevlen = -1; /* last emitted length */
  23065. var curlen; /* length of current code */
  23066. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23067. var count = 0; /* repeat count of the current code */
  23068. var max_count = 7; /* max repeat count */
  23069. var min_count = 4; /* min repeat count */
  23070. /* tree[max_code+1].Len = -1; */ /* guard already set */
  23071. if (nextlen === 0) {
  23072. max_count = 138;
  23073. min_count = 3;
  23074. }
  23075. for (n = 0; n <= max_code; n++) {
  23076. curlen = nextlen;
  23077. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23078. if (++count < max_count && curlen === nextlen) {
  23079. continue;
  23080. } else if (count < min_count) {
  23081. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  23082. } else if (curlen !== 0) {
  23083. if (curlen !== prevlen) {
  23084. send_code(s, curlen, s.bl_tree);
  23085. count--;
  23086. }
  23087. //Assert(count >= 3 && count <= 6, " 3_6?");
  23088. send_code(s, REP_3_6, s.bl_tree);
  23089. send_bits(s, count-3, 2);
  23090. } else if (count <= 10) {
  23091. send_code(s, REPZ_3_10, s.bl_tree);
  23092. send_bits(s, count-3, 3);
  23093. } else {
  23094. send_code(s, REPZ_11_138, s.bl_tree);
  23095. send_bits(s, count-11, 7);
  23096. }
  23097. count = 0;
  23098. prevlen = curlen;
  23099. if (nextlen === 0) {
  23100. max_count = 138;
  23101. min_count = 3;
  23102. } else if (curlen === nextlen) {
  23103. max_count = 6;
  23104. min_count = 3;
  23105. } else {
  23106. max_count = 7;
  23107. min_count = 4;
  23108. }
  23109. }
  23110. }
  23111. /* ===========================================================================
  23112. * Construct the Huffman tree for the bit lengths and return the index in
  23113. * bl_order of the last bit length code to send.
  23114. */
  23115. function build_bl_tree(s) {
  23116. var max_blindex; /* index of last bit length code of non zero freq */
  23117. /* Determine the bit length frequencies for literal and distance trees */
  23118. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  23119. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  23120. /* Build the bit length tree: */
  23121. build_tree(s, s.bl_desc);
  23122. /* opt_len now includes the length of the tree representations, except
  23123. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  23124. */
  23125. /* Determine the number of bit length codes to send. The pkzip format
  23126. * requires that at least 4 bit length codes be sent. (appnote.txt says
  23127. * 3 but the actual value used is 4.)
  23128. */
  23129. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  23130. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  23131. break;
  23132. }
  23133. }
  23134. /* Update opt_len to include the bit length tree and counts */
  23135. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  23136. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  23137. // s->opt_len, s->static_len));
  23138. return max_blindex;
  23139. }
  23140. /* ===========================================================================
  23141. * Send the header for a block using dynamic Huffman trees: the counts, the
  23142. * lengths of the bit length codes, the literal tree and the distance tree.
  23143. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  23144. */
  23145. function send_all_trees(s, lcodes, dcodes, blcodes)
  23146. // deflate_state *s;
  23147. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  23148. {
  23149. var rank; /* index in bl_order */
  23150. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  23151. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  23152. // "too many codes");
  23153. //Tracev((stderr, "\nbl counts: "));
  23154. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  23155. send_bits(s, dcodes-1, 5);
  23156. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  23157. for (rank = 0; rank < blcodes; rank++) {
  23158. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  23159. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  23160. }
  23161. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  23162. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  23163. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  23164. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  23165. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  23166. }
  23167. /* ===========================================================================
  23168. * Check if the data type is TEXT or BINARY, using the following algorithm:
  23169. * - TEXT if the two conditions below are satisfied:
  23170. * a) There are no non-portable control characters belonging to the
  23171. * "black list" (0..6, 14..25, 28..31).
  23172. * b) There is at least one printable character belonging to the
  23173. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  23174. * - BINARY otherwise.
  23175. * - The following partially-portable control characters form a
  23176. * "gray list" that is ignored in this detection algorithm:
  23177. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  23178. * IN assertion: the fields Freq of dyn_ltree are set.
  23179. */
  23180. function detect_data_type(s) {
  23181. /* black_mask is the bit mask of black-listed bytes
  23182. * set bits 0..6, 14..25, and 28..31
  23183. * 0xf3ffc07f = binary 11110011111111111100000001111111
  23184. */
  23185. var black_mask = 0xf3ffc07f;
  23186. var n;
  23187. /* Check for non-textual ("black-listed") bytes. */
  23188. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  23189. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  23190. return Z_BINARY;
  23191. }
  23192. }
  23193. /* Check for textual ("white-listed") bytes. */
  23194. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  23195. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  23196. return Z_TEXT;
  23197. }
  23198. for (n = 32; n < LITERALS; n++) {
  23199. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  23200. return Z_TEXT;
  23201. }
  23202. }
  23203. /* There are no "black-listed" or "white-listed" bytes:
  23204. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  23205. */
  23206. return Z_BINARY;
  23207. }
  23208. var static_init_done = false;
  23209. /* ===========================================================================
  23210. * Initialize the tree data structures for a new zlib stream.
  23211. */
  23212. function _tr_init(s)
  23213. {
  23214. if (!static_init_done) {
  23215. tr_static_init();
  23216. static_init_done = true;
  23217. }
  23218. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  23219. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  23220. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  23221. s.bi_buf = 0;
  23222. s.bi_valid = 0;
  23223. /* Initialize the first block of the first file: */
  23224. init_block(s);
  23225. }
  23226. /* ===========================================================================
  23227. * Send a stored block
  23228. */
  23229. function _tr_stored_block(s, buf, stored_len, last)
  23230. //DeflateState *s;
  23231. //charf *buf; /* input block */
  23232. //ulg stored_len; /* length of input block */
  23233. //int last; /* one if this is the last block for a file */
  23234. {
  23235. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  23236. copy_block(s, buf, stored_len, true); /* with header */
  23237. }
  23238. /* ===========================================================================
  23239. * Send one empty static block to give enough lookahead for inflate.
  23240. * This takes 10 bits, of which 7 may remain in the bit buffer.
  23241. */
  23242. function _tr_align(s) {
  23243. send_bits(s, STATIC_TREES<<1, 3);
  23244. send_code(s, END_BLOCK, static_ltree);
  23245. bi_flush(s);
  23246. }
  23247. /* ===========================================================================
  23248. * Determine the best encoding for the current block: dynamic trees, static
  23249. * trees or store, and output the encoded block to the zip file.
  23250. */
  23251. function _tr_flush_block(s, buf, stored_len, last)
  23252. //DeflateState *s;
  23253. //charf *buf; /* input block, or NULL if too old */
  23254. //ulg stored_len; /* length of input block */
  23255. //int last; /* one if this is the last block for a file */
  23256. {
  23257. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  23258. var max_blindex = 0; /* index of last bit length code of non zero freq */
  23259. /* Build the Huffman trees unless a stored block is forced */
  23260. if (s.level > 0) {
  23261. /* Check if the file is binary or text */
  23262. if (s.strm.data_type === Z_UNKNOWN) {
  23263. s.strm.data_type = detect_data_type(s);
  23264. }
  23265. /* Construct the literal and distance trees */
  23266. build_tree(s, s.l_desc);
  23267. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  23268. // s->static_len));
  23269. build_tree(s, s.d_desc);
  23270. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  23271. // s->static_len));
  23272. /* At this point, opt_len and static_len are the total bit lengths of
  23273. * the compressed block data, excluding the tree representations.
  23274. */
  23275. /* Build the bit length tree for the above two trees, and get the index
  23276. * in bl_order of the last bit length code to send.
  23277. */
  23278. max_blindex = build_bl_tree(s);
  23279. /* Determine the best encoding. Compute the block lengths in bytes. */
  23280. opt_lenb = (s.opt_len+3+7) >>> 3;
  23281. static_lenb = (s.static_len+3+7) >>> 3;
  23282. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  23283. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  23284. // s->last_lit));
  23285. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  23286. } else {
  23287. // Assert(buf != (char*)0, "lost buf");
  23288. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  23289. }
  23290. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  23291. /* 4: two words for the lengths */
  23292. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  23293. * Otherwise we can't have processed more than WSIZE input bytes since
  23294. * the last block flush, because compression would have been
  23295. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  23296. * transform a block into a stored block.
  23297. */
  23298. _tr_stored_block(s, buf, stored_len, last);
  23299. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  23300. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  23301. compress_block(s, static_ltree, static_dtree);
  23302. } else {
  23303. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  23304. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  23305. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  23306. }
  23307. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  23308. /* The above check is made mod 2^32, for files larger than 512 MB
  23309. * and uLong implemented on 32 bits.
  23310. */
  23311. init_block(s);
  23312. if (last) {
  23313. bi_windup(s);
  23314. }
  23315. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  23316. // s->compressed_len-7*last));
  23317. }
  23318. /* ===========================================================================
  23319. * Save the match info and tally the frequency counts. Return true if
  23320. * the current block must be flushed.
  23321. */
  23322. function _tr_tally(s, dist, lc)
  23323. // deflate_state *s;
  23324. // unsigned dist; /* distance of matched string */
  23325. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  23326. {
  23327. //var out_length, in_length, dcode;
  23328. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  23329. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  23330. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  23331. s.last_lit++;
  23332. if (dist === 0) {
  23333. /* lc is the unmatched char */
  23334. s.dyn_ltree[lc*2]/*.Freq*/++;
  23335. } else {
  23336. s.matches++;
  23337. /* Here, lc is the match length - MIN_MATCH */
  23338. dist--; /* dist = match distance - 1 */
  23339. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  23340. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  23341. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  23342. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  23343. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  23344. }
  23345. // (!) This block is disabled in zlib defailts,
  23346. // don't enable it for binary compatibility
  23347. //#ifdef TRUNCATE_BLOCK
  23348. // /* Try to guess if it is profitable to stop the current block here */
  23349. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  23350. // /* Compute an upper bound for the compressed length */
  23351. // out_length = s.last_lit*8;
  23352. // in_length = s.strstart - s.block_start;
  23353. //
  23354. // for (dcode = 0; dcode < D_CODES; dcode++) {
  23355. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  23356. // }
  23357. // out_length >>>= 3;
  23358. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  23359. // // s->last_lit, in_length, out_length,
  23360. // // 100L - out_length*100L/in_length));
  23361. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  23362. // return true;
  23363. // }
  23364. // }
  23365. //#endif
  23366. return (s.last_lit === s.lit_bufsize-1);
  23367. /* We avoid equality with lit_bufsize because of wraparound at 64K
  23368. * on 16 bit machines and because stored blocks are restricted to
  23369. * 64K-1 bytes.
  23370. */
  23371. }
  23372. exports._tr_init = _tr_init;
  23373. exports._tr_stored_block = _tr_stored_block;
  23374. exports._tr_flush_block = _tr_flush_block;
  23375. exports._tr_tally = _tr_tally;
  23376. exports._tr_align = _tr_align;
  23377. },{"../utils/common":67}],79:[function(require,module,exports){
  23378. 'use strict';
  23379. function ZStream() {
  23380. /* next input byte */
  23381. this.input = null; // JS specific, because we have no pointers
  23382. this.next_in = 0;
  23383. /* number of bytes available at input */
  23384. this.avail_in = 0;
  23385. /* total number of input bytes read so far */
  23386. this.total_in = 0;
  23387. /* next output byte should be put there */
  23388. this.output = null; // JS specific, because we have no pointers
  23389. this.next_out = 0;
  23390. /* remaining free space at output */
  23391. this.avail_out = 0;
  23392. /* total number of bytes output so far */
  23393. this.total_out = 0;
  23394. /* last error message, NULL if no error */
  23395. this.msg = ''/*Z_NULL*/;
  23396. /* not visible by applications */
  23397. this.state = null;
  23398. /* best guess about the data type: binary or text */
  23399. this.data_type = 2/*Z_UNKNOWN*/;
  23400. /* adler32 value of the uncompressed data */
  23401. this.adler = 0;
  23402. }
  23403. module.exports = ZStream;
  23404. },{}],80:[function(require,module,exports){
  23405. module.exports = require('./lib/retry');
  23406. },{"./lib/retry":81}],81:[function(require,module,exports){
  23407. var RetryOperation = require('./retry_operation');
  23408. exports.operation = function(options) {
  23409. var timeouts = exports.timeouts(options);
  23410. return new RetryOperation(timeouts);
  23411. };
  23412. exports.timeouts = function(options) {
  23413. if (options instanceof Array) {
  23414. return [].concat(options);
  23415. }
  23416. var opts = {
  23417. retries: 10,
  23418. factor: 2,
  23419. minTimeout: 1 * 1000,
  23420. maxTimeout: Infinity,
  23421. randomize: false
  23422. };
  23423. for (var key in options) {
  23424. opts[key] = options[key];
  23425. }
  23426. if (opts.minTimeout > opts.maxTimeout) {
  23427. throw new Error('minTimeout is greater than maxTimeout');
  23428. }
  23429. var timeouts = [];
  23430. for (var i = 0; i < opts.retries; i++) {
  23431. timeouts.push(this._createTimeout(i, opts));
  23432. }
  23433. // sort the array numerically ascending
  23434. timeouts.sort(function(a,b) {
  23435. return a - b;
  23436. });
  23437. return timeouts;
  23438. };
  23439. exports._createTimeout = function(attempt, opts) {
  23440. var random = (opts.randomize)
  23441. ? (Math.random() + 1)
  23442. : 1;
  23443. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  23444. timeout = Math.min(timeout, opts.maxTimeout);
  23445. return timeout;
  23446. };
  23447. },{"./retry_operation":82}],82:[function(require,module,exports){
  23448. function RetryOperation(timeouts) {
  23449. this._timeouts = timeouts;
  23450. this._fn = null;
  23451. this._errors = [];
  23452. this._attempts = 1;
  23453. this._operationTimeout = null;
  23454. this._operationTimeoutCb = null;
  23455. this._timeout = null;
  23456. }
  23457. module.exports = RetryOperation;
  23458. RetryOperation.prototype.retry = function(err) {
  23459. if (this._timeout) {
  23460. clearTimeout(this._timeout);
  23461. }
  23462. if (!err) {
  23463. return false;
  23464. }
  23465. this._errors.push(err);
  23466. var timeout = this._timeouts.shift();
  23467. if (timeout === undefined) {
  23468. return false;
  23469. }
  23470. this._attempts++;
  23471. var self = this;
  23472. setTimeout(function() {
  23473. self._fn(self._attempts);
  23474. if (self._operationTimeoutCb) {
  23475. self._timeout = setTimeout(function() {
  23476. self._operationTimeoutCb(self._attempts);
  23477. }, self._operationTimeout);
  23478. }
  23479. }, timeout);
  23480. return true;
  23481. };
  23482. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  23483. this._fn = fn;
  23484. if (timeoutOps) {
  23485. if (timeoutOps.timeout) {
  23486. this._operationTimeout = timeoutOps.timeout;
  23487. }
  23488. if (timeoutOps.cb) {
  23489. this._operationTimeoutCb = timeoutOps.cb;
  23490. }
  23491. }
  23492. this._fn(this._attempts);
  23493. var self = this;
  23494. if (this._operationTimeoutCb) {
  23495. this._timeout = setTimeout(function() {
  23496. self._operationTimeoutCb();
  23497. }, self._operationTimeout);
  23498. }
  23499. };
  23500. RetryOperation.prototype.try = function(fn) {
  23501. console.log('Using RetryOperation.try() is deprecated');
  23502. this.attempt(fn);
  23503. };
  23504. RetryOperation.prototype.start = function(fn) {
  23505. console.log('Using RetryOperation.start() is deprecated');
  23506. this.attempt(fn);
  23507. };
  23508. RetryOperation.prototype.start = RetryOperation.prototype.try;
  23509. RetryOperation.prototype.errors = function() {
  23510. return this._errors;
  23511. };
  23512. RetryOperation.prototype.attempts = function() {
  23513. return this._attempts;
  23514. };
  23515. RetryOperation.prototype.mainError = function() {
  23516. if (this._errors.length === 0) {
  23517. return null;
  23518. }
  23519. var counts = {};
  23520. var mainError = null;
  23521. var mainErrorCount = 0;
  23522. for (var i = 0; i < this._errors.length; i++) {
  23523. var error = this._errors[i];
  23524. var message = error.message;
  23525. var count = (counts[message] || 0) + 1;
  23526. counts[message] = count;
  23527. if (count >= mainErrorCount) {
  23528. mainError = error;
  23529. mainErrorCount = count;
  23530. }
  23531. }
  23532. return mainError;
  23533. };
  23534. },{}],83:[function(require,module,exports){
  23535. module.exports = function arrayEquals(array) {
  23536. // if the other array is a falsy value, return
  23537. if (!array)
  23538. return false;
  23539. // compare lengths - can save a lot of time
  23540. if (this.length != array.length)
  23541. return false;
  23542. for (var i = 0, l = this.length; i < l; i++) {
  23543. // Check if we have nested arrays
  23544. if (this[i] instanceof Array && array[i] instanceof Array) {
  23545. // recurse into the nested arrays
  23546. if (!arrayEquals.apply(this[i], [array[i]]))
  23547. return false;
  23548. } else if (this[i] != array[i]) {
  23549. // Warning - two different object instances will never be equal:
  23550. // {x:20} != {x:20}
  23551. return false;
  23552. }
  23553. }
  23554. return true;
  23555. }
  23556. },{}],84:[function(require,module,exports){
  23557. exports.Interop = require('./interop');
  23558. },{"./interop":85}],85:[function(require,module,exports){
  23559. "use strict";
  23560. var transform = require('./transform');
  23561. var arrayEquals = require('./array-equals');
  23562. function Interop() {
  23563. /**
  23564. * This map holds the most recent Unified Plan offer/answer SDP that was
  23565. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  23566. * the SDP string as values.
  23567. *
  23568. * @type {{}}
  23569. */
  23570. this.cache = {};
  23571. }
  23572. module.exports = Interop;
  23573. /**
  23574. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  23575. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  23576. * application.
  23577. *
  23578. * @param desc
  23579. * @returns {*}
  23580. */
  23581. Interop.prototype.toPlanB = function(desc) {
  23582. //#region Preliminary input validation.
  23583. if (typeof desc !== 'object' || desc === null ||
  23584. typeof desc.sdp !== 'string') {
  23585. console.warn('An empty description was passed as an argument.');
  23586. return desc;
  23587. }
  23588. // Objectify the SDP for easier manipulation.
  23589. var session = transform.parse(desc.sdp);
  23590. // If the SDP contains no media, there's nothing to transform.
  23591. if (typeof session.media === 'undefined' ||
  23592. !Array.isArray(session.media) || session.media.length === 0) {
  23593. console.warn('The description has no media.');
  23594. return desc;
  23595. }
  23596. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  23597. // SDP has a video, an audio and a data "channel" at most.
  23598. if (session.media.length <= 3 && session.media.every(function(m) {
  23599. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  23600. })) {
  23601. console.warn('This description does not look like Unified Plan.');
  23602. return desc;
  23603. }
  23604. //#endregion
  23605. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  23606. // -> Unified Plan transformation.
  23607. this.cache[desc.type] = desc.sdp;
  23608. //#region Convert from Unified Plan to Plan B.
  23609. // We rebuild the session.media array.
  23610. var media = session.media;
  23611. session.media = [];
  23612. // Associative array that maps channel types to channel objects for fast
  23613. // access to channel objects by their type, e.g. type2bl['audio']->channel
  23614. // obj.
  23615. var type2bl = {};
  23616. // Used to build the group:BUNDLE value after the channels construction
  23617. // loop.
  23618. var types = [];
  23619. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  23620. media.forEach(function(unifiedLine) {
  23621. // rtcp-mux is required in the Plan B SDP.
  23622. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  23623. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  23624. unifiedLine.direction !== 'inactive') {
  23625. throw new Error('Cannot convert to Plan B because m-lines ' +
  23626. 'without the rtcp-mux attribute were found.');
  23627. }
  23628. if (unifiedLine.type === 'application') {
  23629. session.media.push(unifiedLine);
  23630. types.push(unifiedLine.mid);
  23631. return;
  23632. }
  23633. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  23634. // as the channel basis.
  23635. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  23636. type2bl[unifiedLine.type] = unifiedLine;
  23637. }
  23638. // Add sources to the channel and handle a=msid.
  23639. if (typeof unifiedLine.sources === 'object') {
  23640. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  23641. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  23642. type2bl[unifiedLine.type].sources = {};
  23643. // Assign the sources to the channel.
  23644. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  23645. if (typeof unifiedLine.msid !== 'undefined') {
  23646. // In Plan B the msid is an SSRC attribute. Also, we don't
  23647. // care about the obsolete label and mslabel attributes.
  23648. //
  23649. // Note that it is not guaranteed that the unifiedLine will have
  23650. // an msid. recvonly channels in particular don't have one.
  23651. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  23652. }
  23653. // NOTE ssrcs in ssrc groups will share msids, as
  23654. // draft-uberti-rtcweb-plan-00 mandates.
  23655. });
  23656. }
  23657. // Add ssrc groups to the channel.
  23658. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  23659. Array.isArray(unifiedLine.ssrcGroups)) {
  23660. // Create the ssrcGroups array, if it's not defined.
  23661. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  23662. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  23663. type2bl[unifiedLine.type].ssrcGroups = [];
  23664. }
  23665. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  23666. }
  23667. if (type2bl[unifiedLine.type] === unifiedLine) {
  23668. // Copy ICE related stuff from the principal media line.
  23669. unifiedLine.candidates = media[0].candidates;
  23670. unifiedLine.iceUfrag = media[0].iceUfrag;
  23671. unifiedLine.icePwd = media[0].icePwd;
  23672. unifiedLine.fingerprint = media[0].fingerprint;
  23673. // Plan B mids are in ['audio', 'video', 'data']
  23674. unifiedLine.mid = unifiedLine.type;
  23675. // Plan B doesn't support/need the bundle-only attribute.
  23676. delete unifiedLine.bundleOnly;
  23677. // In Plan B the msid is an SSRC attribute.
  23678. delete unifiedLine.msid;
  23679. // Used to build the group:BUNDLE value after this loop.
  23680. types.push(unifiedLine.type);
  23681. // Add the channel to the new media array.
  23682. session.media.push(unifiedLine);
  23683. }
  23684. });
  23685. // We regenerate the BUNDLE group with the new mids.
  23686. session.groups.some(function(group) {
  23687. if (group.type === 'BUNDLE') {
  23688. group.mids = types.join(' ');
  23689. return true;
  23690. }
  23691. });
  23692. // msid semantic
  23693. session.msidSemantic = {
  23694. semantic: 'WMS',
  23695. token: '*'
  23696. };
  23697. var resStr = transform.write(session);
  23698. return new RTCSessionDescription({
  23699. type: desc.type,
  23700. sdp: resStr
  23701. });
  23702. //#endregion
  23703. };
  23704. /**
  23705. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  23706. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  23707. * to FF.
  23708. *
  23709. * @param desc
  23710. * @returns {*}
  23711. */
  23712. Interop.prototype.toUnifiedPlan = function(desc) {
  23713. //#region Preliminary input validation.
  23714. if (typeof desc !== 'object' || desc === null ||
  23715. typeof desc.sdp !== 'string') {
  23716. console.warn('An empty description was passed as an argument.');
  23717. return desc;
  23718. }
  23719. var session = transform.parse(desc.sdp);
  23720. // If the SDP contains no media, there's nothing to transform.
  23721. if (typeof session.media === 'undefined' ||
  23722. !Array.isArray(session.media) || session.media.length === 0) {
  23723. console.warn('The description has no media.');
  23724. return desc;
  23725. }
  23726. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  23727. // a video, an audio and a data "channel" at most.
  23728. if (session.media.length > 3 || !session.media.every(function(m) {
  23729. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  23730. })) {
  23731. console.warn('This description does not look like Plan B.');
  23732. return desc;
  23733. }
  23734. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  23735. var mids = [];
  23736. session.media.forEach(function(m) {
  23737. mids.push(m.mid);
  23738. });
  23739. var hasBundle = false;
  23740. if (typeof session.groups !== 'undefined' &&
  23741. Array.isArray(session.groups)) {
  23742. hasBundle = session.groups.every(function(g) {
  23743. return g.type !== 'BUNDLE' ||
  23744. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  23745. });
  23746. }
  23747. if (!hasBundle) {
  23748. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  23749. " are not bundled were found.");
  23750. }
  23751. //#endregion
  23752. //#region Convert from Plan B to Unified Plan.
  23753. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  23754. // rebuild an equivalent Unified Plan offer/answer.
  23755. //
  23756. // For example, if this is a local answer (in Unified Plan style) that we
  23757. // convert to Plan B prior to handing it over to the application (the
  23758. // PeerConnection wrapper called us, for instance, after a successful
  23759. // createAnswer), we want to remember the m-line at which we've seen the
  23760. // (local) SSRC. That's because when the application wants to do call the
  23761. // SLD method, forcing us to do the inverse transformation (from Plan B to
  23762. // Unified Plan), we need to know to which m-line to assign the (local)
  23763. // SSRC. We also need to know all the other m-lines that the original
  23764. // answer had and include them in the transformed answer as well.
  23765. //
  23766. // Another example is if this is a remote offer that we convert to Plan B
  23767. // prior to giving it to the application, we want to remember the mid at
  23768. // which we've seen the (remote) SSRC.
  23769. //
  23770. // In the iteration that follows, we use the cached Unified Plan (if it
  23771. // exists) to assign mids to ssrcs.
  23772. var cached;
  23773. if (typeof this.cache[desc.type] !== 'undefined') {
  23774. cached = transform.parse(this.cache[desc.type]);
  23775. }
  23776. // A helper map that sends mids to m-line objects. We use it later to
  23777. // rebuild the Unified Plan style session.media array.
  23778. var mid2ul = {};
  23779. session.media.forEach(function(bLine) {
  23780. if ((typeof bLine.rtcpMux !== 'string' ||
  23781. bLine.rtcpMux !== 'rtcp-mux') &&
  23782. bLine.direction !== 'inactive') {
  23783. throw new Error("Cannot convert to Unified Plan because m-lines " +
  23784. "without the rtcp-mux attribute were found.");
  23785. }
  23786. if (bLine.type === 'application') {
  23787. mid2ul[bLine.mid] = bLine;
  23788. return;
  23789. }
  23790. // With rtcp-mux and bundle all the channels should have the same ICE
  23791. // stuff.
  23792. var sources = bLine.sources;
  23793. var ssrcGroups = bLine.ssrcGroups;
  23794. var candidates = bLine.candidates;
  23795. var iceUfrag = bLine.iceUfrag;
  23796. var icePwd = bLine.icePwd;
  23797. var fingerprint = bLine.fingerprint;
  23798. var port = bLine.port;
  23799. // We'll use the "bLine" object as a prototype for each new "mLine"
  23800. // that we create, but first we need to clean it up a bit.
  23801. delete bLine.sources;
  23802. delete bLine.ssrcGroups;
  23803. delete bLine.candidates;
  23804. delete bLine.iceUfrag;
  23805. delete bLine.icePwd;
  23806. delete bLine.fingerprint;
  23807. delete bLine.port;
  23808. delete bLine.mid;
  23809. // inverted ssrc group map
  23810. var ssrc2group = {};
  23811. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  23812. ssrcGroups.forEach(function (ssrcGroup) {
  23813. // TODO(gp) find out how to receive simulcast with FF. For the
  23814. // time being, hide it.
  23815. if (ssrcGroup.semantics === 'SIM') {
  23816. return;
  23817. }
  23818. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  23819. Array.isArray(ssrcGroup.ssrcs)) {
  23820. ssrcGroup.ssrcs.forEach(function (ssrc) {
  23821. if (typeof ssrc2group[ssrc] === 'undefined') {
  23822. ssrc2group[ssrc] = [];
  23823. }
  23824. ssrc2group[ssrc].push(ssrcGroup);
  23825. });
  23826. }
  23827. });
  23828. }
  23829. // ssrc to m-line index.
  23830. var ssrc2ml = {};
  23831. if (typeof sources === 'object') {
  23832. // Explode the Plan B channel sources with one m-line per source.
  23833. Object.keys(sources).forEach(function(ssrc) {
  23834. // The (unified) m-line for this SSRC. We either create it from
  23835. // scratch or, if it's a grouped SSRC, we re-use a related
  23836. // mline. In other words, if the source is grouped with another
  23837. // source, put the two together in the same m-line.
  23838. var unifiedLine;
  23839. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  23840. Array.isArray(ssrc2group[ssrc])) {
  23841. ssrc2group[ssrc].some(function (ssrcGroup) {
  23842. // ssrcGroup.ssrcs *is* an Array, no need to check
  23843. // again here.
  23844. return ssrcGroup.ssrcs.some(function (related) {
  23845. if (typeof ssrc2ml[related] === 'object') {
  23846. unifiedLine = ssrc2ml[related];
  23847. return true;
  23848. }
  23849. });
  23850. });
  23851. }
  23852. if (typeof unifiedLine === 'object') {
  23853. // the m-line already exists. Just add the source.
  23854. unifiedLine.sources[ssrc] = sources[ssrc];
  23855. delete sources[ssrc].msid;
  23856. } else {
  23857. // Use the "bLine" as a prototype for the "unifiedLine".
  23858. unifiedLine = Object.create(bLine);
  23859. ssrc2ml[ssrc] = unifiedLine;
  23860. if (typeof sources[ssrc].msid !== 'undefined') {
  23861. // Assign the msid of the source to the m-line. Note
  23862. // that it is not guaranteed that the source will have
  23863. // msid. In particular "recvonly" sources don't have an
  23864. // msid. Note that "recvonly" is a term only defined
  23865. // for m-lines.
  23866. unifiedLine.msid = sources[ssrc].msid;
  23867. delete sources[ssrc].msid;
  23868. }
  23869. // We assign one SSRC per media line.
  23870. unifiedLine.sources = {};
  23871. unifiedLine.sources[ssrc] = sources[ssrc];
  23872. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  23873. // Use the cached Unified Plan SDP (if it exists) to assign
  23874. // SSRCs to mids.
  23875. if (typeof cached !== 'undefined' &&
  23876. typeof cached.media !== 'undefined' &&
  23877. Array.isArray(cached.media)) {
  23878. cached.media.forEach(function (m) {
  23879. if (typeof m.sources === 'object') {
  23880. Object.keys(m.sources).forEach(function (s) {
  23881. if (s === ssrc) {
  23882. unifiedLine.mid = m.mid;
  23883. }
  23884. });
  23885. }
  23886. });
  23887. }
  23888. if (typeof unifiedLine.mid === 'undefined') {
  23889. // If this is an SSRC that we see for the first time
  23890. // assign it a new mid. This is typically the case when
  23891. // this method is called to transform a remote
  23892. // description for the first time or when there is a
  23893. // new SSRC in the remote description because a new
  23894. // peer has joined the conference. Local SSRCs should
  23895. // have already been added to the map in the toPlanB
  23896. // method.
  23897. //
  23898. // Because FF generates answers in Unified Plan style,
  23899. // we MUST already have a cached answer with all the
  23900. // local SSRCs mapped to some m-line/mid.
  23901. if (desc.type === 'answer') {
  23902. throw new Error("An unmapped SSRC was found.");
  23903. }
  23904. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  23905. }
  23906. // Include the candidates in the 1st media line.
  23907. unifiedLine.candidates = candidates;
  23908. unifiedLine.iceUfrag = iceUfrag;
  23909. unifiedLine.icePwd = icePwd;
  23910. unifiedLine.fingerprint = fingerprint;
  23911. unifiedLine.port = port;
  23912. mid2ul[unifiedLine.mid] = unifiedLine;
  23913. }
  23914. });
  23915. }
  23916. });
  23917. // Rebuild the media array in the right order and add the missing mLines
  23918. // (missing from the Plan B SDP).
  23919. session.media = [];
  23920. mids = []; // reuse
  23921. if (desc.type === 'answer') {
  23922. // The media lines in the answer must match the media lines in the
  23923. // offer. The order is important too. Here we assume that Firefox is the
  23924. // answerer, so we merely have to use the reconstructed (unified) answer
  23925. // to update the cached (unified) answer accordingly.
  23926. //
  23927. // In the general case, one would have to use the cached (unified) offer
  23928. // to find the m-lines that are missing from the reconstructed answer,
  23929. // potentially grabbing them from the cached (unified) answer. One has
  23930. // to be carefull with this approach because inactive m-lines do not
  23931. // always have an mid, making it tricky (impossible?) to find where
  23932. // exactly and which m-lines are missing from the reconstructed answer.
  23933. for (var i = 0; i < cached.media.length; i++) {
  23934. var unifiedLine = cached.media[i];
  23935. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  23936. // The mid isn't in the reconstructed (unified) answer.
  23937. // This is either a (unified) m-line containing a remote
  23938. // track only, or a (unified) m-line containing a remote
  23939. // track and a local track that has been removed.
  23940. // In either case, it MUST exist in the cached
  23941. // (unified) answer.
  23942. //
  23943. // In case this is a removed local track, clean-up
  23944. // the (unified) m-line and make sure it's 'recvonly' or
  23945. // 'inactive'.
  23946. delete unifiedLine.msid;
  23947. delete unifiedLine.sources;
  23948. delete unifiedLine.ssrcGroups;
  23949. if (!unifiedLine.direction
  23950. || unifiedLine.direction === 'sendrecv')
  23951. unifiedLine.direction = 'recvonly';
  23952. if (!unifiedLine.direction
  23953. || unifiedLine.direction === 'sendonly')
  23954. unifiedLine.direction = 'inactive';
  23955. } else {
  23956. // This is an (unified) m-line/channel that contains a local
  23957. // track (sendrecv or sendonly channel) or it's a unified
  23958. // recvonly m-line/channel. In either case, since we're
  23959. // going from PlanB -> Unified Plan this m-line MUST
  23960. // exist in the cached answer.
  23961. }
  23962. session.media.push(unifiedLine);
  23963. if (typeof unifiedLine.mid === 'string') {
  23964. // inactive lines don't/may not have an mid.
  23965. mids.push(unifiedLine.mid);
  23966. }
  23967. }
  23968. } else {
  23969. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  23970. // under any circumstances. If we are no longer interested in sending a
  23971. // track, we just remove the msid and ssrc attributes and set it to
  23972. // either a=recvonly (as the reofferer, we must use recvonly if the
  23973. // other side was previously sending on the m-section, but we can also
  23974. // leave the possibility open if it wasn't previously in use), or
  23975. // a=inacive.
  23976. if (typeof cached !== 'undefined' &&
  23977. typeof cached.media !== 'undefined' &&
  23978. Array.isArray(cached.media)) {
  23979. cached.media.forEach(function(unifiedLine) {
  23980. mids.push(unifiedLine.mid);
  23981. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  23982. session.media.push(mid2ul[unifiedLine.mid]);
  23983. } else {
  23984. delete unifiedLine.msid;
  23985. delete unifiedLine.sources;
  23986. delete unifiedLine.ssrcGroups;
  23987. if (!unifiedLine.direction
  23988. || unifiedLine.direction === 'sendrecv')
  23989. unifiedLine.direction = 'recvonly';
  23990. if (!unifiedLine.direction
  23991. || unifiedLine.direction === 'sendonly')
  23992. unifiedLine.direction = 'inactive';
  23993. session.media.push(unifiedLine);
  23994. }
  23995. });
  23996. }
  23997. // Add all the remaining (new) m-lines of the transformed SDP.
  23998. Object.keys(mid2ul).forEach(function(mid) {
  23999. if (mids.indexOf(mid) === -1) {
  24000. mids.push(mid);
  24001. if (typeof mid2ul[mid].direction === 'recvonly') {
  24002. // This is a remote recvonly channel. Add its SSRC to the
  24003. // appropriate sendrecv or sendonly channel.
  24004. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  24005. session.media.some(function (unifiedLine) {
  24006. if ((unifiedLine.direction === 'sendrecv' ||
  24007. unifiedLine.direction === 'sendonly') &&
  24008. unifiedLine.type === mid2ul[mid].type) {
  24009. // mid2ul[mid] shouldn't have any ssrc-groups
  24010. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  24011. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  24012. });
  24013. return true;
  24014. }
  24015. });
  24016. } else {
  24017. session.media.push(mid2ul[mid]);
  24018. }
  24019. }
  24020. });
  24021. }
  24022. // We regenerate the BUNDLE group (since we regenerated the mids)
  24023. session.groups.some(function(group) {
  24024. if (group.type === 'BUNDLE') {
  24025. group.mids = mids.join(' ');
  24026. return true;
  24027. }
  24028. });
  24029. // msid semantic
  24030. session.msidSemantic = {
  24031. semantic: 'WMS',
  24032. token: '*'
  24033. };
  24034. var resStr = transform.write(session);
  24035. // Cache the transformed SDP (Unified Plan) for later re-use in this
  24036. // function.
  24037. this.cache[desc.type] = resStr;
  24038. return new RTCSessionDescription({
  24039. type: desc.type,
  24040. sdp: resStr
  24041. });
  24042. //#endregion
  24043. };
  24044. },{"./array-equals":83,"./transform":86}],86:[function(require,module,exports){
  24045. var transform = require('sdp-transform');
  24046. exports.write = function(session, opts) {
  24047. if (typeof session !== 'undefined' &&
  24048. typeof session.media !== 'undefined' &&
  24049. Array.isArray(session.media)) {
  24050. session.media.forEach(function (mLine) {
  24051. // expand sources to ssrcs
  24052. if (typeof mLine.sources !== 'undefined' &&
  24053. Object.keys(mLine.sources).length !== 0) {
  24054. mLine.ssrcs = [];
  24055. Object.keys(mLine.sources).forEach(function (ssrc) {
  24056. var source = mLine.sources[ssrc];
  24057. Object.keys(source).forEach(function (attribute) {
  24058. mLine.ssrcs.push({
  24059. id: ssrc,
  24060. attribute: attribute,
  24061. value: source[attribute]
  24062. });
  24063. });
  24064. });
  24065. delete mLine.sources;
  24066. }
  24067. // join ssrcs in ssrc groups
  24068. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24069. Array.isArray(mLine.ssrcGroups)) {
  24070. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24071. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24072. Array.isArray(ssrcGroup.ssrcs)) {
  24073. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  24074. }
  24075. });
  24076. }
  24077. });
  24078. }
  24079. // join group mids
  24080. if (typeof session !== 'undefined' &&
  24081. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  24082. session.groups.forEach(function (g) {
  24083. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  24084. g.mids = g.mids.join(' ');
  24085. }
  24086. });
  24087. }
  24088. return transform.write(session, opts);
  24089. };
  24090. exports.parse = function(sdp) {
  24091. var session = transform.parse(sdp);
  24092. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  24093. Array.isArray(session.media)) {
  24094. session.media.forEach(function (mLine) {
  24095. // group sources attributes by ssrc
  24096. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  24097. mLine.sources = {};
  24098. mLine.ssrcs.forEach(function (ssrc) {
  24099. if (!mLine.sources[ssrc.id])
  24100. mLine.sources[ssrc.id] = {};
  24101. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  24102. });
  24103. delete mLine.ssrcs;
  24104. }
  24105. // split ssrcs in ssrc groups
  24106. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24107. Array.isArray(mLine.ssrcGroups)) {
  24108. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24109. if (typeof ssrcGroup.ssrcs === 'string') {
  24110. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  24111. }
  24112. });
  24113. }
  24114. });
  24115. }
  24116. // split group mids
  24117. if (typeof session !== 'undefined' &&
  24118. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  24119. session.groups.forEach(function (g) {
  24120. if (typeof g.mids === 'string') {
  24121. g.mids = g.mids.split(' ');
  24122. }
  24123. });
  24124. }
  24125. return session;
  24126. };
  24127. },{"sdp-transform":88}],87:[function(require,module,exports){
  24128. var grammar = module.exports = {
  24129. v: [{
  24130. name: 'version',
  24131. reg: /^(\d*)$/
  24132. }],
  24133. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  24134. // NB: sessionId will be a String in most cases because it is huge
  24135. name: 'origin',
  24136. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  24137. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  24138. format: "%s %s %d %s IP%d %s"
  24139. }],
  24140. // default parsing of these only (though some of these feel outdated)
  24141. s: [{ name: 'name' }],
  24142. i: [{ name: 'description' }],
  24143. u: [{ name: 'uri' }],
  24144. e: [{ name: 'email' }],
  24145. p: [{ name: 'phone' }],
  24146. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  24147. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  24148. //k: [{}], // outdated thing ignored
  24149. t: [{ //t=0 0
  24150. name: 'timing',
  24151. reg: /^(\d*) (\d*)/,
  24152. names: ['start', 'stop'],
  24153. format: "%d %d"
  24154. }],
  24155. c: [{ //c=IN IP4 10.47.197.26
  24156. name: 'connection',
  24157. reg: /^IN IP(\d) (\S*)/,
  24158. names: ['version', 'ip'],
  24159. format: "IN IP%d %s"
  24160. }],
  24161. b: [{ //b=AS:4000
  24162. push: 'bandwidth',
  24163. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  24164. names: ['type', 'limit'],
  24165. format: "%s:%s"
  24166. }],
  24167. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  24168. // NB: special - pushes to session
  24169. // TODO: rtp/fmtp should be filtered by the payloads found here?
  24170. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  24171. names: ['type', 'port', 'protocol', 'payloads'],
  24172. format: "%s %d %s %s"
  24173. }],
  24174. a: [
  24175. { //a=rtpmap:110 opus/48000/2
  24176. push: 'rtp',
  24177. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  24178. names: ['payload', 'codec', 'rate', 'encoding'],
  24179. format: function (o) {
  24180. return (o.encoding) ?
  24181. "rtpmap:%d %s/%s/%s":
  24182. "rtpmap:%d %s/%s";
  24183. }
  24184. },
  24185. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  24186. push: 'fmtp',
  24187. reg: /^fmtp:(\d*) (\S*)/,
  24188. names: ['payload', 'config'],
  24189. format: "fmtp:%d %s"
  24190. },
  24191. { //a=control:streamid=0
  24192. name: 'control',
  24193. reg: /^control:(.*)/,
  24194. format: "control:%s"
  24195. },
  24196. { //a=rtcp:65179 IN IP4 193.84.77.194
  24197. name: 'rtcp',
  24198. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  24199. names: ['port', 'netType', 'ipVer', 'address'],
  24200. format: function (o) {
  24201. return (o.address != null) ?
  24202. "rtcp:%d %s IP%d %s":
  24203. "rtcp:%d";
  24204. }
  24205. },
  24206. { //a=rtcp-fb:98 trr-int 100
  24207. push: 'rtcpFbTrrInt',
  24208. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  24209. names: ['payload', 'value'],
  24210. format: "rtcp-fb:%d trr-int %d"
  24211. },
  24212. { //a=rtcp-fb:98 nack rpsi
  24213. push: 'rtcpFb',
  24214. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  24215. names: ['payload', 'type', 'subtype'],
  24216. format: function (o) {
  24217. return (o.subtype != null) ?
  24218. "rtcp-fb:%s %s %s":
  24219. "rtcp-fb:%s %s";
  24220. }
  24221. },
  24222. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  24223. //a=extmap:1/recvonly URI-gps-string
  24224. push: 'ext',
  24225. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  24226. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  24227. format: function (o) {
  24228. return (o.config != null) ?
  24229. "extmap:%s %s %s":
  24230. "extmap:%s %s";
  24231. }
  24232. },
  24233. {
  24234. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  24235. push: 'crypto',
  24236. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  24237. names: ['id', 'suite', 'config', 'sessionConfig'],
  24238. format: function (o) {
  24239. return (o.sessionConfig != null) ?
  24240. "crypto:%d %s %s %s":
  24241. "crypto:%d %s %s";
  24242. }
  24243. },
  24244. { //a=setup:actpass
  24245. name: 'setup',
  24246. reg: /^setup:(\w*)/,
  24247. format: "setup:%s"
  24248. },
  24249. { //a=mid:1
  24250. name: 'mid',
  24251. reg: /^mid:([^\s]*)/,
  24252. format: "mid:%s"
  24253. },
  24254. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  24255. name: 'msid',
  24256. reg: /^msid:(.*)/,
  24257. format: "msid:%s"
  24258. },
  24259. { //a=ptime:20
  24260. name: 'ptime',
  24261. reg: /^ptime:(\d*)/,
  24262. format: "ptime:%d"
  24263. },
  24264. { //a=maxptime:60
  24265. name: 'maxptime',
  24266. reg: /^maxptime:(\d*)/,
  24267. format: "maxptime:%d"
  24268. },
  24269. { //a=sendrecv
  24270. name: 'direction',
  24271. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  24272. },
  24273. { //a=ice-lite
  24274. name: 'icelite',
  24275. reg: /^(ice-lite)/
  24276. },
  24277. { //a=ice-ufrag:F7gI
  24278. name: 'iceUfrag',
  24279. reg: /^ice-ufrag:(\S*)/,
  24280. format: "ice-ufrag:%s"
  24281. },
  24282. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  24283. name: 'icePwd',
  24284. reg: /^ice-pwd:(\S*)/,
  24285. format: "ice-pwd:%s"
  24286. },
  24287. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  24288. name: 'fingerprint',
  24289. reg: /^fingerprint:(\S*) (\S*)/,
  24290. names: ['type', 'hash'],
  24291. format: "fingerprint:%s %s"
  24292. },
  24293. {
  24294. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  24295. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  24296. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  24297. push:'candidates',
  24298. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  24299. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  24300. format: function (o) {
  24301. var str = "candidate:%s %d %s %d %s %d typ %s";
  24302. // NB: candidate has two optional chunks, so %void middle one if it's missing
  24303. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  24304. if (o.generation != null) {
  24305. str += " generation %d";
  24306. }
  24307. return str;
  24308. }
  24309. },
  24310. { //a=end-of-candidates (keep after the candidates line for readability)
  24311. name: 'endOfCandidates',
  24312. reg: /^(end-of-candidates)/
  24313. },
  24314. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  24315. name: 'remoteCandidates',
  24316. reg: /^remote-candidates:(.*)/,
  24317. format: "remote-candidates:%s"
  24318. },
  24319. { //a=ice-options:google-ice
  24320. name: 'iceOptions',
  24321. reg: /^ice-options:(\S*)/,
  24322. format: "ice-options:%s"
  24323. },
  24324. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  24325. push: "ssrcs",
  24326. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  24327. names: ['id', 'attribute', 'value'],
  24328. format: "ssrc:%d %s:%s"
  24329. },
  24330. { //a=ssrc-group:FEC 1 2
  24331. push: "ssrcGroups",
  24332. reg: /^ssrc-group:(\w*) (.*)/,
  24333. names: ['semantics', 'ssrcs'],
  24334. format: "ssrc-group:%s %s"
  24335. },
  24336. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  24337. name: "msidSemantic",
  24338. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  24339. names: ['semantic', 'token'],
  24340. format: "msid-semantic: %s %s" // space after ":" is not accidental
  24341. },
  24342. { //a=group:BUNDLE audio video
  24343. push: 'groups',
  24344. reg: /^group:(\w*) (.*)/,
  24345. names: ['type', 'mids'],
  24346. format: "group:%s %s"
  24347. },
  24348. { //a=rtcp-mux
  24349. name: 'rtcpMux',
  24350. reg: /^(rtcp-mux)/
  24351. },
  24352. { //a=rtcp-rsize
  24353. name: 'rtcpRsize',
  24354. reg: /^(rtcp-rsize)/
  24355. },
  24356. { // any a= that we don't understand is kepts verbatim on media.invalid
  24357. push: 'invalid',
  24358. names: ["value"]
  24359. }
  24360. ]
  24361. };
  24362. // set sensible defaults to avoid polluting the grammar with boring details
  24363. Object.keys(grammar).forEach(function (key) {
  24364. var objs = grammar[key];
  24365. objs.forEach(function (obj) {
  24366. if (!obj.reg) {
  24367. obj.reg = /(.*)/;
  24368. }
  24369. if (!obj.format) {
  24370. obj.format = "%s";
  24371. }
  24372. });
  24373. });
  24374. },{}],88:[function(require,module,exports){
  24375. var parser = require('./parser');
  24376. var writer = require('./writer');
  24377. exports.write = writer;
  24378. exports.parse = parser.parse;
  24379. exports.parseFmtpConfig = parser.parseFmtpConfig;
  24380. exports.parsePayloads = parser.parsePayloads;
  24381. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  24382. },{"./parser":89,"./writer":90}],89:[function(require,module,exports){
  24383. var toIntIfInt = function (v) {
  24384. return String(Number(v)) === v ? Number(v) : v;
  24385. };
  24386. var attachProperties = function (match, location, names, rawName) {
  24387. if (rawName && !names) {
  24388. location[rawName] = toIntIfInt(match[1]);
  24389. }
  24390. else {
  24391. for (var i = 0; i < names.length; i += 1) {
  24392. if (match[i+1] != null) {
  24393. location[names[i]] = toIntIfInt(match[i+1]);
  24394. }
  24395. }
  24396. }
  24397. };
  24398. var parseReg = function (obj, location, content) {
  24399. var needsBlank = obj.name && obj.names;
  24400. if (obj.push && !location[obj.push]) {
  24401. location[obj.push] = [];
  24402. }
  24403. else if (needsBlank && !location[obj.name]) {
  24404. location[obj.name] = {};
  24405. }
  24406. var keyLocation = obj.push ?
  24407. {} : // blank object that will be pushed
  24408. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  24409. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  24410. if (obj.push) {
  24411. location[obj.push].push(keyLocation);
  24412. }
  24413. };
  24414. var grammar = require('./grammar');
  24415. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  24416. exports.parse = function (sdp) {
  24417. var session = {}
  24418. , media = []
  24419. , location = session; // points at where properties go under (one of the above)
  24420. // parse lines we understand
  24421. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  24422. var type = l[0];
  24423. var content = l.slice(2);
  24424. if (type === 'm') {
  24425. media.push({rtp: [], fmtp: []});
  24426. location = media[media.length-1]; // point at latest media line
  24427. }
  24428. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  24429. var obj = grammar[type][j];
  24430. if (obj.reg.test(content)) {
  24431. return parseReg(obj, location, content);
  24432. }
  24433. }
  24434. });
  24435. session.media = media; // link it up
  24436. return session;
  24437. };
  24438. var fmtpReducer = function (acc, expr) {
  24439. var s = expr.split('=');
  24440. if (s.length === 2) {
  24441. acc[s[0]] = toIntIfInt(s[1]);
  24442. }
  24443. return acc;
  24444. };
  24445. exports.parseFmtpConfig = function (str) {
  24446. return str.split(';').reduce(fmtpReducer, {});
  24447. };
  24448. exports.parsePayloads = function (str) {
  24449. return str.split(' ').map(Number);
  24450. };
  24451. exports.parseRemoteCandidates = function (str) {
  24452. var candidates = [];
  24453. var parts = str.split(' ').map(toIntIfInt);
  24454. for (var i = 0; i < parts.length; i += 3) {
  24455. candidates.push({
  24456. component: parts[i],
  24457. ip: parts[i + 1],
  24458. port: parts[i + 2]
  24459. });
  24460. }
  24461. return candidates;
  24462. };
  24463. },{"./grammar":87}],90:[function(require,module,exports){
  24464. var grammar = require('./grammar');
  24465. // customized util.format - discards excess arguments and can void middle ones
  24466. var formatRegExp = /%[sdv%]/g;
  24467. var format = function (formatStr) {
  24468. var i = 1;
  24469. var args = arguments;
  24470. var len = args.length;
  24471. return formatStr.replace(formatRegExp, function (x) {
  24472. if (i >= len) {
  24473. return x; // missing argument
  24474. }
  24475. var arg = args[i];
  24476. i += 1;
  24477. switch (x) {
  24478. case '%%':
  24479. return '%';
  24480. case '%s':
  24481. return String(arg);
  24482. case '%d':
  24483. return Number(arg);
  24484. case '%v':
  24485. return '';
  24486. }
  24487. });
  24488. // NB: we discard excess arguments - they are typically undefined from makeLine
  24489. };
  24490. var makeLine = function (type, obj, location) {
  24491. var str = obj.format instanceof Function ?
  24492. (obj.format(obj.push ? location : location[obj.name])) :
  24493. obj.format;
  24494. var args = [type + '=' + str];
  24495. if (obj.names) {
  24496. for (var i = 0; i < obj.names.length; i += 1) {
  24497. var n = obj.names[i];
  24498. if (obj.name) {
  24499. args.push(location[obj.name][n]);
  24500. }
  24501. else { // for mLine and push attributes
  24502. args.push(location[obj.names[i]]);
  24503. }
  24504. }
  24505. }
  24506. else {
  24507. args.push(location[obj.name]);
  24508. }
  24509. return format.apply(null, args);
  24510. };
  24511. // RFC specified order
  24512. // TODO: extend this with all the rest
  24513. var defaultOuterOrder = [
  24514. 'v', 'o', 's', 'i',
  24515. 'u', 'e', 'p', 'c',
  24516. 'b', 't', 'r', 'z', 'a'
  24517. ];
  24518. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  24519. module.exports = function (session, opts) {
  24520. opts = opts || {};
  24521. // ensure certain properties exist
  24522. if (session.version == null) {
  24523. session.version = 0; // "v=0" must be there (only defined version atm)
  24524. }
  24525. if (session.name == null) {
  24526. session.name = " "; // "s= " must be there if no meaningful name set
  24527. }
  24528. session.media.forEach(function (mLine) {
  24529. if (mLine.payloads == null) {
  24530. mLine.payloads = "";
  24531. }
  24532. });
  24533. var outerOrder = opts.outerOrder || defaultOuterOrder;
  24534. var innerOrder = opts.innerOrder || defaultInnerOrder;
  24535. var sdp = [];
  24536. // loop through outerOrder for matching properties on session
  24537. outerOrder.forEach(function (type) {
  24538. grammar[type].forEach(function (obj) {
  24539. if (obj.name in session && session[obj.name] != null) {
  24540. sdp.push(makeLine(type, obj, session));
  24541. }
  24542. else if (obj.push in session && session[obj.push] != null) {
  24543. session[obj.push].forEach(function (el) {
  24544. sdp.push(makeLine(type, obj, el));
  24545. });
  24546. }
  24547. });
  24548. });
  24549. // then for each media line, follow the innerOrder
  24550. session.media.forEach(function (mLine) {
  24551. sdp.push(makeLine('m', grammar.m[0], mLine));
  24552. innerOrder.forEach(function (type) {
  24553. grammar[type].forEach(function (obj) {
  24554. if (obj.name in mLine && mLine[obj.name] != null) {
  24555. sdp.push(makeLine(type, obj, mLine));
  24556. }
  24557. else if (obj.push in mLine && mLine[obj.push] != null) {
  24558. mLine[obj.push].forEach(function (el) {
  24559. sdp.push(makeLine(type, obj, el));
  24560. });
  24561. }
  24562. });
  24563. });
  24564. });
  24565. return sdp.join('\r\n') + '\r\n';
  24566. };
  24567. },{"./grammar":87}],91:[function(require,module,exports){
  24568. var transform = require('sdp-transform');
  24569. var transformUtils = require('./transform-utils');
  24570. var parseSsrcs = transformUtils.parseSsrcs;
  24571. var writeSsrcs = transformUtils.writeSsrcs;
  24572. //region Constants
  24573. var DEFAULT_NUM_OF_LAYERS = 3;
  24574. //endregion
  24575. //region Ctor
  24576. function Simulcast(options) {
  24577. this.options = options ? options : {};
  24578. if (!this.options.numOfLayers) {
  24579. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  24580. }
  24581. this.layers = [];
  24582. }
  24583. //endregion
  24584. //region Stateless private utility functions
  24585. /**
  24586. * Returns a random integer between min (included) and max (excluded)
  24587. * Using Math.round() gives a non-uniform distribution!
  24588. * @returns {number}
  24589. */
  24590. function generateSSRC() {
  24591. var min = 0, max = 0xffffffff;
  24592. return Math.floor(Math.random() * (max - min)) + min;
  24593. };
  24594. function processVideo(session, action) {
  24595. if (session == null || !Array.isArray(session.media)) {
  24596. return;
  24597. }
  24598. session.media.forEach(function (mLine) {
  24599. if (mLine.type === 'video') {
  24600. action(mLine);
  24601. }
  24602. });
  24603. }
  24604. function validateDescription(desc)
  24605. {
  24606. return desc && desc != null
  24607. && desc.type && desc.type != ''
  24608. && desc.sdp && desc.sdp != '';
  24609. }
  24610. function explodeRemoteSimulcast(mLine) {
  24611. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  24612. return;
  24613. }
  24614. var sources = parseSsrcs(mLine);
  24615. var order = [];
  24616. // Find the SIM group and explode its sources.
  24617. var j = mLine.ssrcGroups.length;
  24618. while (j--) {
  24619. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  24620. continue;
  24621. }
  24622. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  24623. for (var i = 0; i < simulcastSsrcs.length; i++) {
  24624. var ssrc = simulcastSsrcs[i];
  24625. order.push(ssrc);
  24626. var parts = sources[ssrc].msid.split(' ');
  24627. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  24628. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  24629. // Remove all the groups that this SSRC participates in.
  24630. mLine.ssrcGroups.forEach(function (relatedGroup) {
  24631. if (relatedGroup.semantics === 'SIM') {
  24632. return;
  24633. }
  24634. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  24635. if (relatedSsrcs.indexOf(ssrc) === -1) {
  24636. return;
  24637. }
  24638. // Nuke all the related SSRCs.
  24639. relatedSsrcs.forEach(function (relatedSSRC) {
  24640. sources[relatedSSRC].msid = sources[ssrc].msid;
  24641. sources[relatedSSRC].cname = sources[ssrc].cname;
  24642. if (relatedSSRC !== ssrc) {
  24643. order.push(relatedSSRC);
  24644. }
  24645. });
  24646. // Schedule the related group for nuking.
  24647. })
  24648. }
  24649. mLine.ssrcs = writeSsrcs(sources, order);
  24650. mLine.ssrcGroups.splice(j, 1);
  24651. };
  24652. }
  24653. function squeezeRemoteSimulcast(mLine) {
  24654. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  24655. return;
  24656. }
  24657. var sources = parseSsrcs(mLine);
  24658. // Find the SIM group and nuke it.
  24659. mLine.ssrcGroups.some(function (simulcastGroup) {
  24660. if (simulcastGroup.semantics !== 'SIM') {
  24661. return false;
  24662. }
  24663. // Schedule the SIM group for nuking.
  24664. simulcastGroup.nuke = true;
  24665. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  24666. // Nuke all the higher layer SSRCs.
  24667. for (var i = 1; i < simulcastSsrcs.length; i++) {
  24668. var ssrc = simulcastSsrcs[i];
  24669. delete sources[ssrc];
  24670. // Remove all the groups that this SSRC participates in.
  24671. mLine.ssrcGroups.forEach(function (relatedGroup) {
  24672. if (relatedGroup.semantics === 'SIM') {
  24673. return;
  24674. }
  24675. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  24676. if (relatedSsrcs.indexOf(ssrc) === -1) {
  24677. return;
  24678. }
  24679. // Nuke all the related SSRCs.
  24680. relatedSsrcs.forEach(function (relatedSSRC) {
  24681. delete sources[relatedSSRC];
  24682. });
  24683. // Schedule the related group for nuking.
  24684. relatedGroup.nuke = true;
  24685. })
  24686. }
  24687. return true;
  24688. });
  24689. mLine.ssrcs = writeSsrcs(sources);
  24690. // Nuke all the scheduled groups.
  24691. var i = mLine.ssrcGroups.length;
  24692. while (i--) {
  24693. if (mLine.ssrcGroups[i].nuke) {
  24694. mLine.ssrcGroups.splice(i, 1);
  24695. }
  24696. }
  24697. }
  24698. function removeGoogConference(mLine) {
  24699. if (!mLine || !Array.isArray(mLine.invalid)) {
  24700. return;
  24701. }
  24702. var i = mLine.invalid.length;
  24703. while (i--) {
  24704. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  24705. mLine.invalid.splice(i, 1);
  24706. }
  24707. }
  24708. }
  24709. function assertGoogConference(mLine) {
  24710. if (!mLine) {
  24711. return;
  24712. }
  24713. if (!Array.isArray(mLine.invalid)) {
  24714. mLine.invalid = [];
  24715. }
  24716. if (!mLine.invalid.some(
  24717. function (i) { return i.value === 'x-google-flag:conference' })) {
  24718. mLine.invalid.push({'value': 'x-google-flag:conference'});
  24719. }
  24720. }
  24721. //endregion
  24722. //region "Private" functions
  24723. /**
  24724. *
  24725. * @param mLine
  24726. * @private
  24727. */
  24728. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  24729. if (!mLine || mLine.type !== 'video') {
  24730. return;
  24731. }
  24732. var sources = parseSsrcs(mLine);
  24733. if (Object.keys(sources).length === 0) {
  24734. // no sources, disable simulcast.
  24735. if (this.layers.length !== 0) {
  24736. this.layers = [];
  24737. }
  24738. return;
  24739. }
  24740. // find the base layer (we'll reuse its msid and cname).
  24741. var baseLayerSSRC = Object.keys(sources)[0];
  24742. var baseLayer = sources[baseLayerSSRC];
  24743. // todo(gp) handle screen sharing.
  24744. // check if base CNAME has changed and reinitialise layers.
  24745. if (this.layers.length > 0
  24746. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  24747. this.layers = [];
  24748. }
  24749. // (re)initialise layers
  24750. if (this.layers.length < 1) {
  24751. // first push the base layer.
  24752. this.layers.push({
  24753. ssrc: baseLayerSSRC,
  24754. msid: baseLayer.msid,
  24755. cname: baseLayer.cname
  24756. });
  24757. var rtx = false; // RFC 4588
  24758. if (Array.isArray(mLine.rtp)) {
  24759. rtx = mLine.rtp.some(
  24760. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  24761. }
  24762. if (rtx) {
  24763. this.layers[0].rtx = generateSSRC();
  24764. }
  24765. // now push additional layers.
  24766. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  24767. var layer = { ssrc: generateSSRC() };
  24768. if (rtx) {
  24769. layer.rtx = generateSSRC();
  24770. }
  24771. this.layers.push(layer);
  24772. }
  24773. }
  24774. };
  24775. /**
  24776. *
  24777. * @param mLine
  24778. * @private
  24779. */
  24780. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  24781. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  24782. var sources = {};
  24783. var msid = this.layers[0].msid;
  24784. var cname = this.layers[0].cname;
  24785. var simulcastSsrcs = [];
  24786. var ssrcGroups = [];
  24787. for (var i = 0; i < this.layers.length; i++) {
  24788. var layer = this.layers[i];
  24789. sources[layer.ssrc] = { msid: msid, cname: cname };
  24790. simulcastSsrcs.push(layer.ssrc);
  24791. if (layer.rtx) {
  24792. sources[layer.rtx] = {
  24793. msid: msid,
  24794. cname: cname
  24795. }
  24796. ssrcGroups.push({
  24797. semantics: 'FID',
  24798. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  24799. });
  24800. }
  24801. }
  24802. ssrcGroups.push({
  24803. semantics: 'SIM',
  24804. ssrcs: simulcastSsrcs.join(' ')
  24805. });
  24806. mLine.ssrcGroups = ssrcGroups;
  24807. mLine.ssrcs = writeSsrcs(sources);
  24808. }
  24809. }
  24810. //endregion
  24811. //region "Public" functions
  24812. Simulcast.prototype.isSupported = function () {
  24813. return window.chrome;
  24814. // TODO this needs improvements. For example I doubt that Chrome in Android
  24815. // has simulcast support. Also, only recent versions of Chromium have native
  24816. // simulcast support.
  24817. }
  24818. /**
  24819. *
  24820. * @param desc
  24821. * @returns {RTCSessionDescription}
  24822. */
  24823. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  24824. if (!validateDescription(desc)) {
  24825. return desc;
  24826. }
  24827. var session = transform.parse(desc.sdp);
  24828. var self = this;
  24829. processVideo(session, function (mLine) {
  24830. // Handle simulcast reception.
  24831. if (self.options.explodeRemoteSimulcast) {
  24832. explodeRemoteSimulcast(mLine);
  24833. } else {
  24834. squeezeRemoteSimulcast(mLine);
  24835. }
  24836. // If native simulcast is enabled, we must append the x-goog-conference
  24837. // attribute to the SDP.
  24838. if (self.layers.length < 1) {
  24839. removeGoogConference(mLine);
  24840. } else {
  24841. assertGoogConference(mLine);
  24842. }
  24843. });
  24844. return new RTCSessionDescription({
  24845. type: desc.type,
  24846. sdp: transform.write(session)
  24847. });
  24848. };
  24849. /**
  24850. *
  24851. * @param desc
  24852. * @returns {RTCSessionDescription}
  24853. */
  24854. Simulcast.prototype.mungeLocalDescription = function (desc) {
  24855. if (!validateDescription(desc) || !this.isSupported()) {
  24856. return desc;
  24857. }
  24858. var session = transform.parse(desc.sdp);
  24859. var self = this;
  24860. processVideo(session, function (mLine) {
  24861. // Initialize native simulcast layers, if not already done.
  24862. self._maybeInitializeLayers(mLine);
  24863. // Update the SDP with the simulcast layers.
  24864. self._restoreSimulcastView(mLine);
  24865. });
  24866. return new RTCSessionDescription({
  24867. type: desc.type,
  24868. sdp: transform.write(session)
  24869. });
  24870. };
  24871. //endregion
  24872. module.exports = Simulcast;
  24873. },{"./transform-utils":92,"sdp-transform":94}],92:[function(require,module,exports){
  24874. exports.writeSsrcs = function(sources, order) {
  24875. var ssrcs = [];
  24876. // expand sources to ssrcs
  24877. if (typeof sources !== 'undefined' &&
  24878. Object.keys(sources).length !== 0) {
  24879. if (Array.isArray(order)) {
  24880. for (var i = 0; i < order.length; i++) {
  24881. var ssrc = order[i];
  24882. var source = sources[ssrc];
  24883. Object.keys(source).forEach(function (attribute) {
  24884. ssrcs.push({
  24885. id: ssrc,
  24886. attribute: attribute,
  24887. value: source[attribute]
  24888. });
  24889. });
  24890. }
  24891. } else {
  24892. Object.keys(sources).forEach(function (ssrc) {
  24893. var source = sources[ssrc];
  24894. Object.keys(source).forEach(function (attribute) {
  24895. ssrcs.push({
  24896. id: ssrc,
  24897. attribute: attribute,
  24898. value: source[attribute]
  24899. });
  24900. });
  24901. });
  24902. }
  24903. }
  24904. return ssrcs;
  24905. };
  24906. exports.parseSsrcs = function (mLine) {
  24907. var sources = {};
  24908. // group sources attributes by ssrc.
  24909. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  24910. mLine.ssrcs.forEach(function (ssrc) {
  24911. if (!sources[ssrc.id])
  24912. sources[ssrc.id] = {};
  24913. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  24914. });
  24915. }
  24916. return sources;
  24917. };
  24918. },{}],93:[function(require,module,exports){
  24919. arguments[4][87][0].apply(exports,arguments)
  24920. },{"dup":87}],94:[function(require,module,exports){
  24921. arguments[4][88][0].apply(exports,arguments)
  24922. },{"./parser":95,"./writer":96,"dup":88}],95:[function(require,module,exports){
  24923. arguments[4][89][0].apply(exports,arguments)
  24924. },{"./grammar":93,"dup":89}],96:[function(require,module,exports){
  24925. arguments[4][90][0].apply(exports,arguments)
  24926. },{"./grammar":93,"dup":90}],97:[function(require,module,exports){
  24927. var grammar = module.exports = {
  24928. v: [{
  24929. name: 'version',
  24930. reg: /^(\d*)$/
  24931. }],
  24932. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  24933. // NB: sessionId will be a String in most cases because it is huge
  24934. name: 'origin',
  24935. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  24936. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  24937. format: "%s %s %d %s IP%d %s"
  24938. }],
  24939. // default parsing of these only (though some of these feel outdated)
  24940. s: [{ name: 'name' }],
  24941. i: [{ name: 'description' }],
  24942. u: [{ name: 'uri' }],
  24943. e: [{ name: 'email' }],
  24944. p: [{ name: 'phone' }],
  24945. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  24946. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  24947. //k: [{}], // outdated thing ignored
  24948. t: [{ //t=0 0
  24949. name: 'timing',
  24950. reg: /^(\d*) (\d*)/,
  24951. names: ['start', 'stop'],
  24952. format: "%d %d"
  24953. }],
  24954. c: [{ //c=IN IP4 10.47.197.26
  24955. name: 'connection',
  24956. reg: /^IN IP(\d) (\S*)/,
  24957. names: ['version', 'ip'],
  24958. format: "IN IP%d %s"
  24959. }],
  24960. b: [{ //b=AS:4000
  24961. push: 'bandwidth',
  24962. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  24963. names: ['type', 'limit'],
  24964. format: "%s:%s"
  24965. }],
  24966. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  24967. // NB: special - pushes to session
  24968. // TODO: rtp/fmtp should be filtered by the payloads found here?
  24969. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  24970. names: ['type', 'port', 'protocol', 'payloads'],
  24971. format: "%s %d %s %s"
  24972. }],
  24973. a: [
  24974. { //a=rtpmap:110 opus/48000/2
  24975. push: 'rtp',
  24976. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  24977. names: ['payload', 'codec', 'rate', 'encoding'],
  24978. format: function (o) {
  24979. return (o.encoding) ?
  24980. "rtpmap:%d %s/%s/%s":
  24981. "rtpmap:%d %s/%s";
  24982. }
  24983. },
  24984. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  24985. push: 'fmtp',
  24986. reg: /^fmtp:(\d*) (\S*)/,
  24987. names: ['payload', 'config'],
  24988. format: "fmtp:%d %s"
  24989. },
  24990. { //a=control:streamid=0
  24991. name: 'control',
  24992. reg: /^control:(.*)/,
  24993. format: "control:%s"
  24994. },
  24995. { //a=rtcp:65179 IN IP4 193.84.77.194
  24996. name: 'rtcp',
  24997. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  24998. names: ['port', 'netType', 'ipVer', 'address'],
  24999. format: function (o) {
  25000. return (o.address != null) ?
  25001. "rtcp:%d %s IP%d %s":
  25002. "rtcp:%d";
  25003. }
  25004. },
  25005. { //a=rtcp-fb:98 trr-int 100
  25006. push: 'rtcpFbTrrInt',
  25007. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25008. names: ['payload', 'value'],
  25009. format: "rtcp-fb:%d trr-int %d"
  25010. },
  25011. { //a=rtcp-fb:98 nack rpsi
  25012. push: 'rtcpFb',
  25013. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25014. names: ['payload', 'type', 'subtype'],
  25015. format: function (o) {
  25016. return (o.subtype != null) ?
  25017. "rtcp-fb:%s %s %s":
  25018. "rtcp-fb:%s %s";
  25019. }
  25020. },
  25021. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25022. //a=extmap:1/recvonly URI-gps-string
  25023. push: 'ext',
  25024. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25025. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25026. format: function (o) {
  25027. return (o.config != null) ?
  25028. "extmap:%s %s %s":
  25029. "extmap:%s %s";
  25030. }
  25031. },
  25032. {
  25033. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25034. push: 'crypto',
  25035. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25036. names: ['id', 'suite', 'config', 'sessionConfig'],
  25037. format: function (o) {
  25038. return (o.sessionConfig != null) ?
  25039. "crypto:%d %s %s %s":
  25040. "crypto:%d %s %s";
  25041. }
  25042. },
  25043. { //a=setup:actpass
  25044. name: 'setup',
  25045. reg: /^setup:(\w*)/,
  25046. format: "setup:%s"
  25047. },
  25048. { //a=mid:1
  25049. name: 'mid',
  25050. reg: /^mid:([^\s]*)/,
  25051. format: "mid:%s"
  25052. },
  25053. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25054. name: 'msid',
  25055. reg: /^msid:(.*)/,
  25056. format: "msid:%s"
  25057. },
  25058. { //a=ptime:20
  25059. name: 'ptime',
  25060. reg: /^ptime:(\d*)/,
  25061. format: "ptime:%d"
  25062. },
  25063. { //a=maxptime:60
  25064. name: 'maxptime',
  25065. reg: /^maxptime:(\d*)/,
  25066. format: "maxptime:%d"
  25067. },
  25068. { //a=sendrecv
  25069. name: 'direction',
  25070. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25071. },
  25072. { //a=ice-lite
  25073. name: 'icelite',
  25074. reg: /^(ice-lite)/
  25075. },
  25076. { //a=ice-ufrag:F7gI
  25077. name: 'iceUfrag',
  25078. reg: /^ice-ufrag:(\S*)/,
  25079. format: "ice-ufrag:%s"
  25080. },
  25081. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25082. name: 'icePwd',
  25083. reg: /^ice-pwd:(\S*)/,
  25084. format: "ice-pwd:%s"
  25085. },
  25086. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25087. name: 'fingerprint',
  25088. reg: /^fingerprint:(\S*) (\S*)/,
  25089. names: ['type', 'hash'],
  25090. format: "fingerprint:%s %s"
  25091. },
  25092. {
  25093. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25094. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25095. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25096. push:'candidates',
  25097. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  25098. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  25099. format: function (o) {
  25100. var str = "candidate:%s %d %s %d %s %d typ %s";
  25101. // NB: candidate has two optional chunks, so %void middle one if it's missing
  25102. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25103. if (o.generation != null) {
  25104. str += " generation %d";
  25105. }
  25106. return str;
  25107. }
  25108. },
  25109. { //a=end-of-candidates (keep after the candidates line for readability)
  25110. name: 'endOfCandidates',
  25111. reg: /^(end-of-candidates)/
  25112. },
  25113. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25114. name: 'remoteCandidates',
  25115. reg: /^remote-candidates:(.*)/,
  25116. format: "remote-candidates:%s"
  25117. },
  25118. { //a=ice-options:google-ice
  25119. name: 'iceOptions',
  25120. reg: /^ice-options:(\S*)/,
  25121. format: "ice-options:%s"
  25122. },
  25123. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25124. push: "ssrcs",
  25125. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25126. names: ['id', 'attribute', 'value'],
  25127. format: "ssrc:%d %s:%s"
  25128. },
  25129. { //a=ssrc-group:FEC 1 2
  25130. push: "ssrcGroups",
  25131. reg: /^ssrc-group:(\w*) (.*)/,
  25132. names: ['semantics', 'ssrcs'],
  25133. format: "ssrc-group:%s %s"
  25134. },
  25135. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25136. name: "msidSemantic",
  25137. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25138. names: ['semantic', 'token'],
  25139. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25140. },
  25141. { //a=group:BUNDLE audio video
  25142. push: 'groups',
  25143. reg: /^group:(\w*) (.*)/,
  25144. names: ['type', 'mids'],
  25145. format: "group:%s %s"
  25146. },
  25147. { //a=rtcp-mux
  25148. name: 'rtcpMux',
  25149. reg: /^(rtcp-mux)/
  25150. },
  25151. { // any a= that we don't understand is kepts verbatim on media.invalid
  25152. push: 'invalid',
  25153. names: ["value"]
  25154. }
  25155. ]
  25156. };
  25157. // set sensible defaults to avoid polluting the grammar with boring details
  25158. Object.keys(grammar).forEach(function (key) {
  25159. var objs = grammar[key];
  25160. objs.forEach(function (obj) {
  25161. if (!obj.reg) {
  25162. obj.reg = /(.*)/;
  25163. }
  25164. if (!obj.format) {
  25165. obj.format = "%s";
  25166. }
  25167. });
  25168. });
  25169. },{}],98:[function(require,module,exports){
  25170. arguments[4][88][0].apply(exports,arguments)
  25171. },{"./parser":99,"./writer":100,"dup":88}],99:[function(require,module,exports){
  25172. arguments[4][89][0].apply(exports,arguments)
  25173. },{"./grammar":97,"dup":89}],100:[function(require,module,exports){
  25174. arguments[4][90][0].apply(exports,arguments)
  25175. },{"./grammar":97,"dup":90}],101:[function(require,module,exports){
  25176. var MediaStreamType = {
  25177. VIDEO_TYPE: "Video",
  25178. AUDIO_TYPE: "Audio"
  25179. };
  25180. module.exports = MediaStreamType;
  25181. },{}],102:[function(require,module,exports){
  25182. var RTCBrowserType = {
  25183. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  25184. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  25185. };
  25186. module.exports = RTCBrowserType;
  25187. },{}],103:[function(require,module,exports){
  25188. var RTCEvents = {
  25189. LASTN_CHANGED: "rtc.lastn_changed",
  25190. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  25191. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  25192. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  25193. };
  25194. module.exports = RTCEvents;
  25195. },{}],104:[function(require,module,exports){
  25196. var Resolutions = {
  25197. "1080": {
  25198. width: 1920,
  25199. height: 1080,
  25200. order: 7
  25201. },
  25202. "fullhd": {
  25203. width: 1920,
  25204. height: 1080,
  25205. order: 7
  25206. },
  25207. "720": {
  25208. width: 1280,
  25209. height: 720,
  25210. order: 6
  25211. },
  25212. "hd": {
  25213. width: 1280,
  25214. height: 720,
  25215. order: 6
  25216. },
  25217. "960": {
  25218. width: 960,
  25219. height: 720,
  25220. order: 5
  25221. },
  25222. "640": {
  25223. width: 640,
  25224. height: 480,
  25225. order: 4
  25226. },
  25227. "vga": {
  25228. width: 640,
  25229. height: 480,
  25230. order: 4
  25231. },
  25232. "360": {
  25233. width: 640,
  25234. height: 360,
  25235. order: 3
  25236. },
  25237. "320": {
  25238. width: 320,
  25239. height: 240,
  25240. order: 2
  25241. },
  25242. "180": {
  25243. width: 320,
  25244. height: 180,
  25245. order: 1
  25246. }
  25247. };
  25248. module.exports = Resolutions;
  25249. },{}],105:[function(require,module,exports){
  25250. var StreamEventTypes = {
  25251. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  25252. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  25253. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  25254. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  25255. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  25256. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  25257. };
  25258. module.exports = StreamEventTypes;
  25259. },{}],106:[function(require,module,exports){
  25260. var UIEvents = {
  25261. NICKNAME_CHANGED: "UI.nickname_changed",
  25262. SELECTED_ENDPOINT: "UI.selected_endpoint",
  25263. PINNED_ENDPOINT: "UI.pinned_endpoint"
  25264. };
  25265. module.exports = UIEvents;
  25266. },{}],107:[function(require,module,exports){
  25267. var AuthenticationEvents = {
  25268. /**
  25269. * Event callback arguments:
  25270. * function(authenticationEnabled, userIdentity)
  25271. * authenticationEnabled - indicates whether authentication has been enabled
  25272. * in this session
  25273. * userIdentity - if user has been logged in then it contains user name. If
  25274. * contains 'null' or 'undefined' then user is not logged in.
  25275. */
  25276. IDENTITY_UPDATED: "authentication.identity_updated"
  25277. };
  25278. module.exports = AuthenticationEvents;
  25279. },{}],108:[function(require,module,exports){
  25280. var CQEvents = {
  25281. LOCALSTATS_UPDATED: "cq.localstats_updated",
  25282. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  25283. STOP: "cq.stop"
  25284. };
  25285. module.exports = CQEvents;
  25286. },{}],109:[function(require,module,exports){
  25287. var DesktopSharingEventTypes = {
  25288. INIT: "ds.init",
  25289. SWITCHING_DONE: "ds.switching_done",
  25290. NEW_STREAM_CREATED: "ds.new_stream_created"
  25291. };
  25292. module.exports = DesktopSharingEventTypes;
  25293. },{}],110:[function(require,module,exports){
  25294. var Events = {
  25295. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  25296. };
  25297. module.exports = Events;
  25298. },{}],111:[function(require,module,exports){
  25299. module.exports = {
  25300. getLanguages : function () {
  25301. var languages = [];
  25302. for(var lang in this)
  25303. {
  25304. if(typeof this[lang] === "string")
  25305. languages.push(this[lang]);
  25306. }
  25307. return languages;
  25308. },
  25309. EN: "en",
  25310. BG: "bg",
  25311. DE: "de",
  25312. TR: "tr",
  25313. FR: "fr"
  25314. }
  25315. },{}],112:[function(require,module,exports){
  25316. var XMPPEvents = {
  25317. CONNECTION_FAILED: "xmpp.connection.failed",
  25318. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  25319. CALL_TERMINATED: "xmpp.callterminated.jingle",
  25320. CALL_INCOMING: "xmpp.callincoming.jingle",
  25321. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  25322. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  25323. KICKED: "xmpp.kicked",
  25324. BRIDGE_DOWN: "xmpp.bridge_down",
  25325. USER_ID_CHANGED: "xmpp.user_id_changed",
  25326. STREAMS_CHANGED: "xmpp.streams_changed",
  25327. // We joined the MUC
  25328. MUC_JOINED: "xmpp.muc_joined",
  25329. // A member joined the MUC
  25330. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  25331. // A member left the MUC
  25332. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  25333. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  25334. MUC_DESTROYED: "xmpp.muc_destroyed",
  25335. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  25336. REMOTE_STATS: "xmpp.remote_stats",
  25337. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  25338. PRESENCE_STATUS: "xmpp.presence_status",
  25339. RESERVATION_ERROR: "xmpp.room_reservation_error",
  25340. SUBJECT_CHANGED: "xmpp.subject_changed",
  25341. MESSAGE_RECEIVED: "xmpp.message_received",
  25342. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  25343. PASSWORD_REQUIRED: "xmpp.password_required",
  25344. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  25345. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  25346. ETHERPAD: "xmpp.etherpad",
  25347. DEVICE_AVAILABLE: "xmpp.device_available",
  25348. START_MUTED: "xmpp.start_muted"
  25349. };
  25350. module.exports = XMPPEvents;
  25351. },{}]},{},[1])(1)
  25352. });