Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

app.bundle.js 1018KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.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.desktopsharing.init();
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. APP.keyboardshortcut.init();
  28. APP.members.start();
  29. }
  30. $(document).ready(function () {
  31. var URLProcessor = require("./modules/URLProcessor/URLProcessor");
  32. URLProcessor.setConfigParametersFromUrl();
  33. APP.init();
  34. APP.translation.init();
  35. if(APP.API.isEnabled())
  36. APP.API.init();
  37. APP.UI.start(init);
  38. });
  39. $(window).bind('beforeunload', function () {
  40. if(APP.API.isEnabled())
  41. APP.API.dispose();
  42. });
  43. module.exports = APP;
  44. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":11,"./modules/URLProcessor/URLProcessor":42,"./modules/connectionquality/connectionquality":43,"./modules/desktopsharing/desktopsharing":44,"./modules/keyboardshortcut/keyboardshortcut":45,"./modules/members/MemberList":46,"./modules/settings/Settings":47,"./modules/statistics/statistics":51,"./modules/translation/translation":52,"./modules/xmpp/xmpp":67}],2:[function(require,module,exports){
  45. /* global APP */
  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. * toggleAudio: toggleAudio,
  57. * toggleVideo: toggleVideo,
  58. * toggleFilmStrip: toggleFilmStrip,
  59. * toggleChat: toggleChat,
  60. * toggleContactList: toggleContactList
  61. * }}
  62. */
  63. var commands = {};
  64. function initCommands() {
  65. commands = {
  66. displayName: APP.UI.inputDisplayNameHandler,
  67. toggleAudio: APP.UI.toggleAudio,
  68. toggleVideo: APP.UI.toggleVideo,
  69. toggleFilmStrip: APP.UI.toggleFilmStrip,
  70. toggleChat: APP.UI.toggleChat,
  71. toggleContactList: APP.UI.toggleContactList
  72. };
  73. }
  74. /**
  75. * Maps the supported events and their status
  76. * (true it the event is enabled and false if it is disabled)
  77. * @type {{
  78. * incomingMessage: boolean,
  79. * outgoingMessage: boolean,
  80. * displayNameChange: boolean,
  81. * participantJoined: boolean,
  82. * participantLeft: boolean
  83. * }}
  84. */
  85. var events = {
  86. incomingMessage: false,
  87. outgoingMessage:false,
  88. displayNameChange: false,
  89. participantJoined: false,
  90. participantLeft: false
  91. };
  92. var displayName = {};
  93. /**
  94. * Processes commands from external application.
  95. * @param message the object with the command
  96. */
  97. function processCommand(message) {
  98. if (message.action != "execute") {
  99. console.error("Unknown action of the message");
  100. return;
  101. }
  102. for (var key in message) {
  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. console.error("Event with no action is received.");
  114. return;
  115. }
  116. var i = 0;
  117. switch(event.action) {
  118. case "add":
  119. for (; i < event.events.length; i++) {
  120. events[event.events[i]] = true;
  121. }
  122. break;
  123. case "remove":
  124. for (; i < event.events.length; i++) {
  125. events[event.events[i]] = false;
  126. }
  127. break;
  128. default:
  129. console.error("Unknown action for event.");
  130. }
  131. }
  132. /**
  133. * Sends message to the external application.
  134. * @param object
  135. */
  136. function sendMessage(object) {
  137. window.parent.postMessage(JSON.stringify(object), "*");
  138. }
  139. /**
  140. * Processes a message event from the external application
  141. * @param event the message event
  142. */
  143. function processMessage(event) {
  144. var message;
  145. try {
  146. message = JSON.parse(event.data);
  147. } catch (e) {}
  148. if(!message.type)
  149. return;
  150. switch (message.type) {
  151. case "command":
  152. processCommand(message);
  153. break;
  154. case "event":
  155. processEvent(message);
  156. break;
  157. default:
  158. console.error("Unknown type of the message");
  159. return;
  160. }
  161. }
  162. function setupListeners() {
  163. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  164. API.triggerEvent("participantJoined", {jid: from});
  165. });
  166. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  167. if (from != myjid)
  168. API.triggerEvent("incomingMessage",
  169. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  170. });
  171. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  172. API.triggerEvent("participantLeft", {jid: jid});
  173. });
  174. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  175. var name = displayName[jid];
  176. if(!name || name != newDisplayName) {
  177. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  178. displayName[jid] = newDisplayName;
  179. }
  180. });
  181. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  182. APP.API.triggerEvent("outgoingMessage", {"message": body});
  183. });
  184. }
  185. var API = {
  186. /**
  187. * Check whether the API should be enabled or not.
  188. * @returns {boolean}
  189. */
  190. isEnabled: function () {
  191. var hash = location.hash;
  192. if (hash && hash.indexOf("external") > -1 && window.postMessage)
  193. return true;
  194. return false;
  195. },
  196. /**
  197. * Initializes the APIConnector. Setups message event listeners that will
  198. * receive information from external applications that embed Jitsi Meet.
  199. * It also sends a message to the external application that APIConnector
  200. * is initialized.
  201. */
  202. init: function () {
  203. initCommands();
  204. if (window.addEventListener) {
  205. window.addEventListener('message',
  206. processMessage, false);
  207. }
  208. else {
  209. window.attachEvent('onmessage', processMessage);
  210. }
  211. sendMessage({type: "system", loaded: true});
  212. setupListeners();
  213. },
  214. /**
  215. * Checks whether the event is enabled ot not.
  216. * @param name the name of the event.
  217. * @returns {*}
  218. */
  219. isEventEnabled: function (name) {
  220. return events[name];
  221. },
  222. /**
  223. * Sends event object to the external application that has been subscribed
  224. * for that event.
  225. * @param name the name event
  226. * @param object data associated with the event
  227. */
  228. triggerEvent: function (name, object) {
  229. if(this.isEnabled() && this.isEventEnabled(name))
  230. sendMessage({
  231. type: "event", action: "result", event: name, result: object});
  232. },
  233. /**
  234. * Removes the listeners.
  235. */
  236. dispose: function () {
  237. if(window.removeEventListener) {
  238. window.removeEventListener("message",
  239. processMessage, false);
  240. }
  241. else {
  242. window.detachEvent('onmessage', processMessage);
  243. }
  244. }
  245. };
  246. module.exports = API;
  247. },{"../../service/xmpp/XMPPEvents":113}],3:[function(require,module,exports){
  248. /* global APP */
  249. /**
  250. * A module for sending DTMF tones.
  251. */
  252. var DTMFSender;
  253. var initDtmfSender = function() {
  254. // TODO: This needs to reset this if the peerconnection changes
  255. // (e.g. the call is re-made)
  256. if (DTMFSender)
  257. return;
  258. var localAudio = APP.RTC.localAudio;
  259. if (localAudio && localAudio.getTracks().length > 0)
  260. {
  261. var peerconnection
  262. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  263. if (peerconnection) {
  264. DTMFSender =
  265. peerconnection.peerconnection
  266. .createDTMFSender(localAudio.getTracks()[0]);
  267. console.log("Initialized DTMFSender");
  268. }
  269. else {
  270. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  271. }
  272. }
  273. else {
  274. console.log("Failed to initialize DTMFSender: no audio track.");
  275. }
  276. };
  277. var DTMF = {
  278. sendTones: function (tones, duration, pause) {
  279. if (!DTMFSender)
  280. initDtmfSender();
  281. if (DTMFSender){
  282. DTMFSender.insertDTMF(tones,
  283. (duration || 200),
  284. (pause || 200));
  285. }
  286. }
  287. };
  288. module.exports = DTMF;
  289. },{}],4:[function(require,module,exports){
  290. /* global config, APP, Strophe */
  291. // cache datachannels to avoid garbage collection
  292. // https://code.google.com/p/chromium/issues/detail?id=405545
  293. var RTCEvents = require("../../service/RTC/RTCEvents");
  294. var _dataChannels = [];
  295. var eventEmitter = null;
  296. var DataChannels = {
  297. /**
  298. * Callback triggered by PeerConnection when new data channel is opened
  299. * on the bridge.
  300. * @param event the event info object.
  301. */
  302. onDataChannel: function (event) {
  303. var dataChannel = event.channel;
  304. dataChannel.onopen = function () {
  305. console.info("Data channel opened by the Videobridge!", dataChannel);
  306. // Code sample for sending string and/or binary data
  307. // Sends String message to the bridge
  308. //dataChannel.send("Hello bridge!");
  309. // Sends 12 bytes binary message to the bridge
  310. //dataChannel.send(new ArrayBuffer(12));
  311. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  312. };
  313. dataChannel.onerror = function (error) {
  314. console.error("Data Channel Error:", error, dataChannel);
  315. };
  316. dataChannel.onmessage = function (event) {
  317. var data = event.data;
  318. // JSON
  319. var obj;
  320. try {
  321. obj = JSON.parse(data);
  322. }
  323. catch (e) {
  324. console.error(
  325. "Failed to parse data channel message as JSON: ",
  326. data,
  327. dataChannel);
  328. }
  329. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  330. var colibriClass = obj.colibriClass;
  331. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  332. // Endpoint ID from the Videobridge.
  333. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  334. console.info(
  335. "Data channel new dominant speaker event: ",
  336. dominantSpeakerEndpoint);
  337. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  338. }
  339. else if ("InLastNChangeEvent" === colibriClass) {
  340. var oldValue = obj.oldValue;
  341. var newValue = obj.newValue;
  342. // Make sure that oldValue and newValue are of type boolean.
  343. var type;
  344. if ((type = typeof oldValue) !== 'boolean') {
  345. if (type === 'string') {
  346. oldValue = (oldValue == "true");
  347. } else {
  348. oldValue = new Boolean(oldValue).valueOf();
  349. }
  350. }
  351. if ((type = typeof newValue) !== 'boolean') {
  352. if (type === 'string') {
  353. newValue = (newValue == "true");
  354. } else {
  355. newValue = new Boolean(newValue).valueOf();
  356. }
  357. }
  358. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  359. }
  360. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  361. // The new/latest list of last-n endpoint IDs.
  362. var lastNEndpoints = obj.lastNEndpoints;
  363. // The list of endpoint IDs which are entering the list of
  364. // last-n at this time i.e. were not in the old list of last-n
  365. // endpoint IDs.
  366. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  367. console.log(
  368. "Data channel new last-n event: ",
  369. lastNEndpoints, endpointsEnteringLastN, obj);
  370. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  371. lastNEndpoints, endpointsEnteringLastN, obj);
  372. }
  373. else {
  374. console.debug("Data channel JSON-formatted message: ", obj);
  375. }
  376. }
  377. };
  378. dataChannel.onclose = function () {
  379. console.info("The Data Channel closed", dataChannel);
  380. var idx = _dataChannels.indexOf(dataChannel);
  381. if (idx > -1)
  382. _dataChannels = _dataChannels.splice(idx, 1);
  383. };
  384. _dataChannels.push(dataChannel);
  385. },
  386. /**
  387. * Binds "ondatachannel" event listener to given PeerConnection instance.
  388. * @param peerConnection WebRTC peer connection instance.
  389. */
  390. init: function (peerConnection, emitter) {
  391. if(!config.openSctp)
  392. return;
  393. peerConnection.ondatachannel = this.onDataChannel;
  394. eventEmitter = emitter;
  395. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  396. // Although it's not a requirement to open separate channels from both bridge
  397. // and peer as single channel can be used for sending and receiving data.
  398. // So either channel opened by the bridge or the one opened here is enough
  399. // for communication with the bridge.
  400. /*var dataChannelOptions =
  401. {
  402. reliable: true
  403. };
  404. var dataChannel
  405. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  406. // Can be used only when is in open state
  407. dataChannel.onopen = function ()
  408. {
  409. dataChannel.send("My channel !!!");
  410. };
  411. dataChannel.onmessage = function (event)
  412. {
  413. var msgData = event.data;
  414. console.info("Got My Data Channel Message:", msgData, dataChannel);
  415. };*/
  416. },
  417. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  418. handlePinnedEndpointEvent: onPinnedEndpointChanged
  419. };
  420. function onSelectedEndpointChanged(userResource) {
  421. console.log('selected endpoint changed: ', userResource);
  422. if (_dataChannels && _dataChannels.length != 0) {
  423. _dataChannels.some(function (dataChannel) {
  424. if (dataChannel.readyState == 'open') {
  425. console.log('sending selected endpoint changed ' +
  426. 'notification to the bridge: ', userResource);
  427. dataChannel.send(JSON.stringify({
  428. 'colibriClass': 'SelectedEndpointChangedEvent',
  429. 'selectedEndpoint':
  430. (!userResource || userResource === null)?
  431. null : userResource
  432. }));
  433. return true;
  434. }
  435. });
  436. }
  437. }
  438. function onPinnedEndpointChanged(userResource) {
  439. console.log('pinned endpoint changed: ', userResource);
  440. if (_dataChannels && _dataChannels.length != 0) {
  441. _dataChannels.some(function (dataChannel) {
  442. if (dataChannel.readyState == 'open') {
  443. dataChannel.send(JSON.stringify({
  444. 'colibriClass': 'PinnedEndpointChangedEvent',
  445. 'pinnedEndpoint':
  446. (!userResource || userResource == null)?
  447. null : userResource
  448. }));
  449. return true;
  450. }
  451. });
  452. }
  453. }
  454. module.exports = DataChannels;
  455. },{"../../service/RTC/RTCEvents":104}],5:[function(require,module,exports){
  456. /* global APP */
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. var RTCEvents = require("../../service/RTC/RTCEvents");
  459. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  460. this.stream = stream;
  461. this.eventEmitter = eventEmitter;
  462. this.type = type;
  463. this.videoType = videoType;
  464. this.isGUMStream = true;
  465. if(isGUMStream === false)
  466. this.isGUMStream = isGUMStream;
  467. var self = this;
  468. if(type == "audio") {
  469. this.getTracks = function () {
  470. return self.stream.getAudioTracks();
  471. };
  472. } else {
  473. this.getTracks = function () {
  474. return self.stream.getVideoTracks();
  475. };
  476. }
  477. this.stream.onended = function() {
  478. self.streamEnded();
  479. };
  480. }
  481. LocalStream.prototype.streamEnded = function () {
  482. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  483. };
  484. LocalStream.prototype.getOriginalStream = function()
  485. {
  486. return this.stream;
  487. };
  488. LocalStream.prototype.isAudioStream = function () {
  489. return this.type === "audio";
  490. };
  491. LocalStream.prototype.setMute = function (mute)
  492. {
  493. var isAudio = this.isAudioStream();
  494. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  495. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  496. (isAudio && this.isGUMStream) || this.videoType === "screen") {
  497. var tracks = this.getTracks();
  498. for (var idx = 0; idx < tracks.length; idx++) {
  499. tracks[idx].enabled = !mute;
  500. }
  501. this.eventEmitter.emit(eventType, mute);
  502. } else {
  503. if (mute) {
  504. APP.xmpp.removeStream(this.stream);
  505. this.stream.stop();
  506. this.eventEmitter.emit(eventType, true);
  507. } else {
  508. var self = this;
  509. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  510. (this.isAudioStream() ? ["audio"] : ["video"]),
  511. function (stream) {
  512. if (isAudio) {
  513. APP.RTC.changeLocalAudio(stream,
  514. function () {
  515. self.eventEmitter.emit(eventType, false);
  516. });
  517. } else {
  518. APP.RTC.changeLocalVideo(stream, false,
  519. function () {
  520. self.eventEmitter.emit(eventType, false);
  521. });
  522. }
  523. });
  524. }
  525. }
  526. };
  527. LocalStream.prototype.isMuted = function () {
  528. var tracks = [];
  529. if (this.isAudioStream()) {
  530. tracks = this.stream.getAudioTracks();
  531. } else {
  532. if (this.stream.ended)
  533. return true;
  534. tracks = this.stream.getVideoTracks();
  535. }
  536. for (var idx = 0; idx < tracks.length; idx++) {
  537. if(tracks[idx].enabled)
  538. return false;
  539. }
  540. return true;
  541. };
  542. LocalStream.prototype.getId = function () {
  543. return this.stream.getTracks()[0].id;
  544. };
  545. module.exports = LocalStream;
  546. },{"../../service/RTC/RTCEvents":104,"../../service/RTC/StreamEventTypes.js":106}],6:[function(require,module,exports){
  547. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  548. /**
  549. * Creates a MediaStream object for the given data, session id and ssrc.
  550. * It is a wrapper class for the MediaStream.
  551. *
  552. * @param data the data object from which we obtain the stream,
  553. * the peerjid, etc.
  554. * @param sid the session id
  555. * @param ssrc the ssrc corresponding to this MediaStream
  556. *
  557. * @constructor
  558. */
  559. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  560. // XXX(gp) to minimize headaches in the future, we should build our
  561. // abstractions around tracks and not streams. ORTC is track based API.
  562. // Mozilla expects m-lines to represent media tracks.
  563. //
  564. // Practically, what I'm saying is that we should have a MediaTrack class
  565. // and not a MediaStream class.
  566. //
  567. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  568. // a track might have an associated RTX and FEC sources.
  569. this.sid = sid;
  570. this.stream = data.stream;
  571. this.peerjid = data.peerjid;
  572. this.videoType = data.videoType;
  573. this.ssrc = ssrc;
  574. this.type = (this.stream.getVideoTracks().length > 0)?
  575. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  576. this.muted = false;
  577. this.eventEmitter = eventEmitter;
  578. }
  579. MediaStream.prototype.getOriginalStream = function() {
  580. return this.stream;
  581. };
  582. MediaStream.prototype.setMute = function (value) {
  583. this.stream.muted = value;
  584. this.muted = value;
  585. };
  586. module.exports = MediaStream;
  587. },{"../../service/RTC/MediaStreamTypes":103}],7:[function(require,module,exports){
  588. /* global APP */
  589. var EventEmitter = require("events");
  590. var RTCBrowserType = require("./RTCBrowserType");
  591. var RTCUtils = require("./RTCUtils.js");
  592. var LocalStream = require("./LocalStream.js");
  593. var DataChannels = require("./DataChannels");
  594. var MediaStream = require("./MediaStream.js");
  595. var DesktopSharingEventTypes
  596. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  597. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  598. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  599. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  600. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  601. var UIEvents = require("../../service/UI/UIEvents");
  602. var eventEmitter = new EventEmitter();
  603. function getMediaStreamUsage()
  604. {
  605. var result = {
  606. audio: true,
  607. video: true
  608. };
  609. /** There are some issues with the desktop sharing
  610. * when this property is enabled.
  611. * WARNING: We must change the implementation to start video/audio if we
  612. * receive from the focus that the peer is not muted.
  613. var isSecureConnection = window.location.protocol == "https:";
  614. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  615. {
  616. result = {
  617. audio: false,
  618. video: false
  619. };
  620. }
  621. **/
  622. return result;
  623. }
  624. var RTC = {
  625. rtcUtils: null,
  626. devices: {
  627. audio: true,
  628. video: true
  629. },
  630. localStreams: [],
  631. remoteStreams: {},
  632. localAudio: null,
  633. localVideo: null,
  634. addStreamListener: function (listener, eventType) {
  635. eventEmitter.on(eventType, listener);
  636. },
  637. addListener: function (type, listener) {
  638. eventEmitter.on(type, listener);
  639. },
  640. removeStreamListener: function (listener, eventType) {
  641. if(!(eventType instanceof StreamEventTypes))
  642. throw "Illegal argument";
  643. eventEmitter.removeListener(eventType, listener);
  644. },
  645. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  646. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  647. //in firefox we have only one stream object
  648. if(this.localStreams.length == 0 ||
  649. this.localStreams[0].getOriginalStream() != stream)
  650. this.localStreams.push(localStream);
  651. if(isMuted === true)
  652. localStream.setMute(true);
  653. if(type == "audio") {
  654. this.localAudio = localStream;
  655. } else {
  656. this.localVideo = localStream;
  657. }
  658. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  659. if(change)
  660. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  661. eventEmitter.emit(eventType, localStream, isMuted);
  662. return localStream;
  663. },
  664. removeLocalStream: function (stream) {
  665. for(var i = 0; i < this.localStreams.length; i++) {
  666. if(this.localStreams[i].getOriginalStream() === stream) {
  667. delete this.localStreams[i];
  668. return;
  669. }
  670. }
  671. },
  672. createRemoteStream: function (data, sid, thessrc) {
  673. var remoteStream = new MediaStream(data, sid, thessrc,
  674. RTCBrowserType.getBrowserType(), eventEmitter);
  675. var jid = data.peerjid || APP.xmpp.myJid();
  676. if(!this.remoteStreams[jid]) {
  677. this.remoteStreams[jid] = {};
  678. }
  679. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  680. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  681. return remoteStream;
  682. },
  683. getPCConstraints: function () {
  684. return this.rtcUtils.pc_constraints;
  685. },
  686. getUserMediaWithConstraints:function(um, success_callback,
  687. failure_callback, resolution,
  688. bandwidth, fps, desktopStream)
  689. {
  690. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  691. failure_callback, resolution, bandwidth, fps, desktopStream);
  692. },
  693. attachMediaStream: function (elSelector, stream) {
  694. this.rtcUtils.attachMediaStream(elSelector, stream);
  695. },
  696. getStreamID: function (stream) {
  697. return this.rtcUtils.getStreamID(stream);
  698. },
  699. getVideoSrc: function (element) {
  700. return this.rtcUtils.getVideoSrc(element);
  701. },
  702. setVideoSrc: function (element, src) {
  703. this.rtcUtils.setVideoSrc(element, src);
  704. },
  705. getVideoElementName: function () {
  706. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  707. },
  708. dispose: function() {
  709. if (this.rtcUtils) {
  710. this.rtcUtils = null;
  711. }
  712. },
  713. stop: function () {
  714. this.dispose();
  715. },
  716. start: function () {
  717. var self = this;
  718. APP.desktopsharing.addListener(
  719. function (stream, isUsingScreenStream, callback) {
  720. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  721. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  722. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  723. DataChannels.init(event.peerconnection, eventEmitter);
  724. });
  725. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  726. DataChannels.handleSelectedEndpointEvent);
  727. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  728. DataChannels.handlePinnedEndpointEvent);
  729. // In case of IE we continue from 'onReady' callback
  730. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  731. // once it is initialized.
  732. var onReady = function () {
  733. eventEmitter.emit(RTCEvents.RTC_READY, true);
  734. self.rtcUtils.obtainAudioAndVideoPermissions(
  735. null, null, getMediaStreamUsage());
  736. };
  737. this.rtcUtils = new RTCUtils(this, onReady);
  738. // Call onReady() if Temasys plugin is not used
  739. if (!RTCBrowserType.isTemasysPluginUsed()) {
  740. onReady();
  741. }
  742. },
  743. muteRemoteVideoStream: function (jid, value) {
  744. var stream;
  745. if(this.remoteStreams[jid] &&
  746. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  747. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  748. }
  749. if(!stream)
  750. return true;
  751. if (value != stream.muted) {
  752. stream.setMute(value);
  753. return true;
  754. }
  755. return false;
  756. },
  757. switchVideoStreams: function (new_stream) {
  758. this.localVideo.stream = new_stream;
  759. this.localStreams = [];
  760. //in firefox we have only one stream object
  761. if (this.localAudio.getOriginalStream() != new_stream)
  762. this.localStreams.push(this.localAudio);
  763. this.localStreams.push(this.localVideo);
  764. },
  765. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  766. var oldStream = this.localVideo.getOriginalStream();
  767. var type = (isUsingScreenStream ? "screen" : "camera");
  768. var localCallback = callback;
  769. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  770. localCallback = function() {
  771. APP.xmpp.setVideoMute(false, function(mute) {
  772. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  773. });
  774. callback();
  775. };
  776. }
  777. // FIXME: Workaround for FF/IE/Safari
  778. if (stream && stream.videoStream) {
  779. stream = stream.videoStream;
  780. }
  781. var videoStream = this.rtcUtils.createStream(stream, true);
  782. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  783. // Stop the stream to trigger onended event for old stream
  784. oldStream.stop();
  785. this.switchVideoStreams(videoStream, oldStream);
  786. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  787. },
  788. changeLocalAudio: function (stream, callback) {
  789. var oldStream = this.localAudio.getOriginalStream();
  790. var newStream = this.rtcUtils.createStream(stream);
  791. this.localAudio = this.createLocalStream(newStream, "audio", true);
  792. // Stop the stream to trigger onended event for old stream
  793. oldStream.stop();
  794. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  795. },
  796. isVideoMuted: function (jid) {
  797. if (jid === APP.xmpp.myJid()) {
  798. var localVideo = APP.RTC.localVideo;
  799. return (!localVideo || localVideo.isMuted());
  800. } else {
  801. if (!APP.RTC.remoteStreams[jid] ||
  802. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  803. return null;
  804. }
  805. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  806. }
  807. },
  808. setVideoMute: function (mute, callback, options) {
  809. if (!this.localVideo)
  810. return;
  811. if (mute == APP.RTC.localVideo.isMuted())
  812. {
  813. APP.xmpp.sendVideoInfoPresence(mute);
  814. if (callback)
  815. callback(mute);
  816. }
  817. else
  818. {
  819. APP.RTC.localVideo.setMute(mute);
  820. APP.xmpp.setVideoMute(
  821. mute,
  822. callback,
  823. options);
  824. }
  825. },
  826. setDeviceAvailability: function (devices) {
  827. if(!devices)
  828. return;
  829. if(devices.audio === true || devices.audio === false)
  830. this.devices.audio = devices.audio;
  831. if(devices.video === true || devices.video === false)
  832. this.devices.video = devices.video;
  833. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  834. }
  835. };
  836. module.exports = RTC;
  837. },{"../../service/RTC/MediaStreamTypes":103,"../../service/RTC/RTCEvents.js":104,"../../service/RTC/StreamEventTypes.js":106,"../../service/UI/UIEvents":107,"../../service/desktopsharing/DesktopSharingEventTypes":110,"../../service/xmpp/XMPPEvents":113,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":114}],8:[function(require,module,exports){
  838. var currentBrowser;
  839. var browserVersion;
  840. var RTCBrowserType = {
  841. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  842. RTC_BROWSER_OPERA: "rtc_browser.opera",
  843. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  844. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  845. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  846. getBrowserType: function () {
  847. return currentBrowser;
  848. },
  849. isChrome: function () {
  850. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  851. },
  852. isOpera: function () {
  853. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  854. },
  855. isFirefox: function () {
  856. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  857. },
  858. isIExplorer: function () {
  859. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  860. },
  861. isSafari: function () {
  862. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  863. },
  864. isTemasysPluginUsed: function () {
  865. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  866. },
  867. getFirefoxVersion: function () {
  868. return RTCBrowserType.isFirefox() ? browserVersion : null;
  869. },
  870. getChromeVersion: function () {
  871. return RTCBrowserType.isChrome() ? browserVersion : null;
  872. },
  873. usesPlanB: function() {
  874. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  875. RTCBrowserType.isTemasysPluginUsed();
  876. },
  877. usesUnifiedPlan: function() {
  878. return RTCBrowserType.isFirefox();
  879. }
  880. // Add version getters for other browsers when needed
  881. };
  882. // detectOpera() must be called before detectChrome() !!!
  883. // otherwise Opera wil be detected as Chrome
  884. function detectChrome() {
  885. if (navigator.webkitGetUserMedia) {
  886. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  887. var userAgent = navigator.userAgent.toLowerCase();
  888. // We can assume that user agent is chrome, because it's
  889. // enforced when 'ext' streaming method is set
  890. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  891. console.log("This appears to be Chrome, ver: " + ver);
  892. return ver;
  893. }
  894. return null;
  895. }
  896. function detectOpera() {
  897. var userAgent = navigator.userAgent;
  898. if (userAgent.match(/Opera|OPR/)) {
  899. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  900. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  901. console.info("This appears to be Opera, ver: " + version);
  902. return version;
  903. }
  904. return null;
  905. }
  906. function detectFirefox() {
  907. if (navigator.mozGetUserMedia) {
  908. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  909. var version = parseInt(
  910. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  911. console.log('This appears to be Firefox, ver: ' + version);
  912. return version;
  913. }
  914. return null;
  915. }
  916. function detectSafari() {
  917. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  918. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  919. console.info("This appears to be Safari");
  920. // FIXME detect Safari version when needed
  921. return 1;
  922. }
  923. return null;
  924. }
  925. function detectIE() {
  926. var version;
  927. var ua = window.navigator.userAgent;
  928. var msie = ua.indexOf('MSIE ');
  929. if (msie > 0) {
  930. // IE 10 or older => return version number
  931. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  932. }
  933. var trident = ua.indexOf('Trident/');
  934. if (!version && trident > 0) {
  935. // IE 11 => return version number
  936. var rv = ua.indexOf('rv:');
  937. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  938. }
  939. var edge = ua.indexOf('Edge/');
  940. if (!version && edge > 0) {
  941. // IE 12 => return version number
  942. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  943. }
  944. if (version) {
  945. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  946. console.info("This appears to be IExplorer, ver: " + version);
  947. }
  948. return version;
  949. }
  950. function detectBrowser() {
  951. var version;
  952. var detectors = [
  953. detectOpera,
  954. detectChrome,
  955. detectFirefox,
  956. detectIE,
  957. detectSafari
  958. ];
  959. // Try all browser detectors
  960. for (var i = 0; i < detectors.length; i++) {
  961. version = detectors[i]();
  962. if (version)
  963. return version;
  964. }
  965. console.error("Failed to detect browser type");
  966. return undefined;
  967. }
  968. browserVersion = detectBrowser();
  969. module.exports = RTCBrowserType;
  970. },{}],9:[function(require,module,exports){
  971. /* global config, require, attachMediaStream, getUserMedia */
  972. var RTCBrowserType = require("./RTCBrowserType");
  973. var Resolutions = require("../../service/RTC/Resolutions");
  974. var AdapterJS = require("./adapter.screenshare");
  975. var SDPUtil = require("../xmpp/SDPUtil");
  976. var currentResolution = null;
  977. function getPreviousResolution(resolution) {
  978. if(!Resolutions[resolution])
  979. return null;
  980. var order = Resolutions[resolution].order;
  981. var res = null;
  982. var resName = null;
  983. for(var i in Resolutions) {
  984. var tmp = Resolutions[i];
  985. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  986. resName = i;
  987. res = tmp;
  988. }
  989. }
  990. return resName;
  991. }
  992. function setResolutionConstraints(constraints, resolution, isAndroid) {
  993. if (resolution && !constraints.video || isAndroid) {
  994. // same behaviour as true
  995. constraints.video = { mandatory: {}, optional: [] };
  996. }
  997. if(Resolutions[resolution]) {
  998. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  999. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1000. }
  1001. else {
  1002. if (isAndroid) {
  1003. constraints.video.mandatory.minWidth = 320;
  1004. constraints.video.mandatory.minHeight = 240;
  1005. constraints.video.mandatory.maxFrameRate = 15;
  1006. }
  1007. }
  1008. if (constraints.video.mandatory.minWidth)
  1009. constraints.video.mandatory.maxWidth =
  1010. constraints.video.mandatory.minWidth;
  1011. if (constraints.video.mandatory.minHeight)
  1012. constraints.video.mandatory.maxHeight =
  1013. constraints.video.mandatory.minHeight;
  1014. }
  1015. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1016. {
  1017. var constraints = {audio: false, video: false};
  1018. if (um.indexOf('video') >= 0) {
  1019. // same behaviour as true
  1020. constraints.video = { mandatory: {}, optional: [] };
  1021. }
  1022. if (um.indexOf('audio') >= 0) {
  1023. // same behaviour as true
  1024. constraints.audio = { mandatory: {}, optional: []};
  1025. }
  1026. if (um.indexOf('screen') >= 0) {
  1027. if (RTCBrowserType.isChrome()) {
  1028. constraints.video = {
  1029. mandatory: {
  1030. chromeMediaSource: "screen",
  1031. googLeakyBucket: true,
  1032. maxWidth: window.screen.width,
  1033. maxHeight: window.screen.height,
  1034. maxFrameRate: 3
  1035. },
  1036. optional: []
  1037. };
  1038. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1039. constraints.video = {
  1040. optional: [
  1041. {
  1042. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1043. }
  1044. ]
  1045. };
  1046. } else {
  1047. console.error(
  1048. "'screen' WebRTC media source is supported only in Chrome" +
  1049. " and with Temasys plugin");
  1050. }
  1051. }
  1052. if (um.indexOf('desktop') >= 0) {
  1053. constraints.video = {
  1054. mandatory: {
  1055. chromeMediaSource: "desktop",
  1056. chromeMediaSourceId: desktopStream,
  1057. googLeakyBucket: true,
  1058. maxWidth: window.screen.width,
  1059. maxHeight: window.screen.height,
  1060. maxFrameRate: 3
  1061. },
  1062. optional: []
  1063. };
  1064. }
  1065. if (constraints.audio) {
  1066. // if it is good enough for hangouts...
  1067. constraints.audio.optional.push(
  1068. {googEchoCancellation: true},
  1069. {googAutoGainControl: true},
  1070. {googNoiseSupression: true},
  1071. {googHighpassFilter: true},
  1072. {googNoisesuppression2: true},
  1073. {googEchoCancellation2: true},
  1074. {googAutoGainControl2: true}
  1075. );
  1076. }
  1077. if (constraints.video) {
  1078. if (um.indexOf('video') >= 0) {
  1079. constraints.video.optional.push(
  1080. {googLeakyBucket: true}
  1081. );
  1082. }
  1083. }
  1084. if (um.indexOf('video') >= 0) {
  1085. setResolutionConstraints(constraints, resolution, isAndroid);
  1086. }
  1087. if (bandwidth) {
  1088. if (!constraints.video) {
  1089. //same behaviour as true
  1090. constraints.video = {mandatory: {}, optional: []};
  1091. }
  1092. constraints.video.optional.push({bandwidth: bandwidth});
  1093. }
  1094. if (fps) {
  1095. // for some cameras it might be necessary to request 30fps
  1096. // so they choose 30fps mjpg over 10fps yuy2
  1097. if (!constraints.video) {
  1098. // same behaviour as true;
  1099. constraints.video = {mandatory: {}, optional: []};
  1100. }
  1101. constraints.video.mandatory.minFrameRate = fps;
  1102. }
  1103. return constraints;
  1104. }
  1105. function RTCUtils(RTCService, onTemasysPluginReady)
  1106. {
  1107. var self = this;
  1108. this.service = RTCService;
  1109. if (RTCBrowserType.isFirefox()) {
  1110. var FFversion = RTCBrowserType.getFirefoxVersion();
  1111. if (FFversion >= 40) {
  1112. this.peerconnection = mozRTCPeerConnection;
  1113. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1114. this.pc_constraints = {};
  1115. this.attachMediaStream = function (element, stream) {
  1116. // srcObject is being standardized and FF will eventually
  1117. // support that unprefixed. FF also supports the
  1118. // "element.src = URL.createObjectURL(...)" combo, but that
  1119. // will be deprecated in favour of srcObject.
  1120. //
  1121. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1122. // https://github.com/webrtc/samples/issues/302
  1123. if(!element[0])
  1124. return;
  1125. element[0].mozSrcObject = stream;
  1126. element[0].play();
  1127. };
  1128. this.getStreamID = function (stream) {
  1129. var id = stream.id;
  1130. if (!id) {
  1131. var tracks = stream.getVideoTracks();
  1132. if (!tracks || tracks.length === 0) {
  1133. tracks = stream.getAudioTracks();
  1134. }
  1135. id = tracks[0].id;
  1136. }
  1137. return SDPUtil.filter_special_chars(id);
  1138. };
  1139. this.getVideoSrc = function (element) {
  1140. if(!element)
  1141. return null;
  1142. return element.mozSrcObject;
  1143. };
  1144. this.setVideoSrc = function (element, src) {
  1145. if(element)
  1146. element.mozSrcObject = src;
  1147. };
  1148. RTCSessionDescription = mozRTCSessionDescription;
  1149. RTCIceCandidate = mozRTCIceCandidate;
  1150. } else {
  1151. console.error(
  1152. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1153. window.location.href = 'unsupported_browser.html';
  1154. return;
  1155. }
  1156. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1157. this.peerconnection = webkitRTCPeerConnection;
  1158. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1159. this.attachMediaStream = function (element, stream) {
  1160. element.attr('src', webkitURL.createObjectURL(stream));
  1161. };
  1162. this.getStreamID = function (stream) {
  1163. // streams from FF endpoints have the characters '{' and '}'
  1164. // that make jQuery choke.
  1165. return SDPUtil.filter_special_chars(stream.id);
  1166. };
  1167. this.getVideoSrc = function (element) {
  1168. if(!element)
  1169. return null;
  1170. return element.getAttribute("src");
  1171. };
  1172. this.setVideoSrc = function (element, src) {
  1173. if(element)
  1174. element.setAttribute("src", src);
  1175. };
  1176. // DTLS should now be enabled by default but..
  1177. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1178. if (navigator.userAgent.indexOf('Android') != -1) {
  1179. this.pc_constraints = {}; // disable DTLS on Android
  1180. }
  1181. if (!webkitMediaStream.prototype.getVideoTracks) {
  1182. webkitMediaStream.prototype.getVideoTracks = function () {
  1183. return this.videoTracks;
  1184. };
  1185. }
  1186. if (!webkitMediaStream.prototype.getAudioTracks) {
  1187. webkitMediaStream.prototype.getAudioTracks = function () {
  1188. return this.audioTracks;
  1189. };
  1190. }
  1191. }
  1192. // Detect IE/Safari
  1193. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1194. //AdapterJS.WebRTCPlugin.setLogLevel(
  1195. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1196. AdapterJS.webRTCReady(function (isPlugin) {
  1197. self.peerconnection = RTCPeerConnection;
  1198. self.getUserMedia = getUserMedia;
  1199. self.attachMediaStream = function (elSel, stream) {
  1200. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1201. return;
  1202. }
  1203. attachMediaStream(elSel[0], stream);
  1204. };
  1205. self.getStreamID = function (stream) {
  1206. var id = SDPUtil.filter_special_chars(stream.label);
  1207. return id;
  1208. };
  1209. self.getVideoSrc = function (element) {
  1210. if (!element) {
  1211. console.warn("Attempt to get video SRC of null element");
  1212. return null;
  1213. }
  1214. var children = element.children;
  1215. for (var i = 0; i !== children.length; ++i) {
  1216. if (children[i].name === 'streamId') {
  1217. return children[i].value;
  1218. }
  1219. }
  1220. //console.info(element.id + " SRC: " + src);
  1221. return null;
  1222. };
  1223. self.setVideoSrc = function (element, src) {
  1224. //console.info("Set video src: ", element, src);
  1225. if (!src) {
  1226. console.warn("Not attaching video stream, 'src' is null");
  1227. return;
  1228. }
  1229. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1230. var stream = AdapterJS.WebRTCPlugin.plugin
  1231. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1232. attachMediaStream(element, stream);
  1233. };
  1234. onTemasysPluginReady(isPlugin);
  1235. });
  1236. } else {
  1237. try {
  1238. console.log('Browser does not appear to be WebRTC-capable');
  1239. } catch (e) { }
  1240. window.location.href = 'unsupported_browser.html';
  1241. }
  1242. }
  1243. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1244. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1245. desktopStream) {
  1246. currentResolution = resolution;
  1247. // Check if we are running on Android device
  1248. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1249. var constraints = getConstraints(
  1250. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1251. console.info("Get media constraints", constraints);
  1252. var self = this;
  1253. try {
  1254. this.getUserMedia(constraints,
  1255. function (stream) {
  1256. console.log('onUserMediaSuccess');
  1257. self.setAvailableDevices(um, true);
  1258. success_callback(stream);
  1259. },
  1260. function (error) {
  1261. self.setAvailableDevices(um, false);
  1262. console.warn('Failed to get access to local media. Error ',
  1263. error, constraints);
  1264. if (failure_callback) {
  1265. failure_callback(error);
  1266. }
  1267. });
  1268. } catch (e) {
  1269. console.error('GUM failed: ', e);
  1270. if(failure_callback) {
  1271. failure_callback(e);
  1272. }
  1273. }
  1274. };
  1275. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1276. var devices = {};
  1277. if(um.indexOf("video") != -1) {
  1278. devices.video = available;
  1279. }
  1280. if(um.indexOf("audio") != -1) {
  1281. devices.audio = available;
  1282. }
  1283. this.service.setDeviceAvailability(devices);
  1284. };
  1285. /**
  1286. * We ask for audio and video combined stream in order to get permissions and
  1287. * not to ask twice.
  1288. */
  1289. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1290. function(devices, callback, usageOptions)
  1291. {
  1292. var self = this;
  1293. // Get AV
  1294. var successCallback = function (stream) {
  1295. if(callback)
  1296. callback(stream, usageOptions);
  1297. else
  1298. self.successCallback(stream, usageOptions);
  1299. };
  1300. if(!devices)
  1301. devices = ['audio', 'video'];
  1302. var newDevices = [];
  1303. if(usageOptions)
  1304. for(var i = 0; i < devices.length; i++) {
  1305. var device = devices[i];
  1306. if(usageOptions[device] === true)
  1307. newDevices.push(device);
  1308. }
  1309. else
  1310. newDevices = devices;
  1311. if(newDevices.length === 0) {
  1312. successCallback();
  1313. return;
  1314. }
  1315. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1316. // With FF/IE we can't split the stream into audio and video because FF
  1317. // doesn't support media stream constructors. So, we need to get the
  1318. // audio stream separately from the video stream using two distinct GUM
  1319. // calls. Not very user friendly :-( but we don't have many other
  1320. // options neither.
  1321. //
  1322. // Note that we pack those 2 streams in a single object and pass it to
  1323. // the successCallback method.
  1324. var obtainVideo = function (audioStream) {
  1325. self.getUserMediaWithConstraints(
  1326. ['video'],
  1327. function (videoStream) {
  1328. return successCallback({
  1329. audioStream: audioStream,
  1330. videoStream: videoStream
  1331. });
  1332. },
  1333. function (error) {
  1334. console.error(
  1335. 'failed to obtain video stream - stop', error);
  1336. self.errorCallback(error);
  1337. },
  1338. config.resolution || '360');
  1339. };
  1340. var obtainAudio = function () {
  1341. self.getUserMediaWithConstraints(
  1342. ['audio'],
  1343. function (audioStream) {
  1344. if (newDevices.indexOf('video') !== -1)
  1345. obtainVideo(audioStream);
  1346. },
  1347. function (error) {
  1348. console.error(
  1349. 'failed to obtain audio stream - stop', error);
  1350. self.errorCallback(error);
  1351. }
  1352. );
  1353. };
  1354. if (newDevices.indexOf('audio') !== -1) {
  1355. obtainAudio();
  1356. } else {
  1357. obtainVideo(null);
  1358. }
  1359. } else {
  1360. this.getUserMediaWithConstraints(
  1361. newDevices,
  1362. function (stream) {
  1363. successCallback(stream);
  1364. },
  1365. function (error) {
  1366. self.errorCallback(error);
  1367. },
  1368. config.resolution || '360');
  1369. }
  1370. };
  1371. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1372. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1373. // it's an object with two properties: audioStream, videoStream.
  1374. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1375. console.log('got', stream, stream.getAudioTracks().length,
  1376. stream.getVideoTracks().length);
  1377. this.handleLocalStream(stream, usageOptions);
  1378. };
  1379. RTCUtils.prototype.errorCallback = function (error) {
  1380. var self = this;
  1381. console.error('failed to obtain audio/video stream - trying audio only', error);
  1382. var resolution = getPreviousResolution(currentResolution);
  1383. if(typeof error == "object" && error.constraintName && error.name
  1384. && (error.name == "ConstraintNotSatisfiedError" ||
  1385. error.name == "OverconstrainedError") &&
  1386. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1387. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1388. && resolution != null)
  1389. {
  1390. self.getUserMediaWithConstraints(['audio', 'video'],
  1391. function (stream) {
  1392. return self.successCallback(stream);
  1393. }, function (error) {
  1394. return self.errorCallback(error);
  1395. }, resolution);
  1396. }
  1397. else {
  1398. self.getUserMediaWithConstraints(
  1399. ['audio'],
  1400. function (stream) {
  1401. return self.successCallback(stream);
  1402. },
  1403. function (error) {
  1404. console.error('failed to obtain audio/video stream - stop',
  1405. error);
  1406. return self.successCallback(null);
  1407. }
  1408. );
  1409. }
  1410. };
  1411. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1412. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1413. // an object with two properties: audioStream, videoStream.
  1414. var audioStream, videoStream;
  1415. if(window.webkitMediaStream)
  1416. {
  1417. audioStream = new webkitMediaStream();
  1418. videoStream = new webkitMediaStream();
  1419. if(stream) {
  1420. var audioTracks = stream.getAudioTracks();
  1421. for (var i = 0; i < audioTracks.length; i++) {
  1422. audioStream.addTrack(audioTracks[i]);
  1423. }
  1424. var videoTracks = stream.getVideoTracks();
  1425. for (i = 0; i < videoTracks.length; i++) {
  1426. videoStream.addTrack(videoTracks[i]);
  1427. }
  1428. }
  1429. }
  1430. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1431. { // Firefox and Temasys plugin
  1432. if (stream && stream.audioStream)
  1433. audioStream = stream.audioStream;
  1434. else
  1435. audioStream = new DummyMediaStream("dummyAudio");
  1436. if (stream && stream.videoStream)
  1437. videoStream = stream.videoStream;
  1438. else
  1439. videoStream = new DummyMediaStream("dummyVideo");
  1440. }
  1441. var audioMuted = (usageOptions && usageOptions.audio === false),
  1442. videoMuted = (usageOptions && usageOptions.video === false);
  1443. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1444. videoGUM = (!usageOptions || usageOptions.video !== false);
  1445. this.service.createLocalStream(audioStream, "audio", null, null,
  1446. audioMuted, audioGUM);
  1447. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1448. videoMuted, videoGUM);
  1449. };
  1450. function DummyMediaStream(id) {
  1451. this.id = id;
  1452. this.label = id;
  1453. this.stop = function() { };
  1454. this.getAudioTracks = function() { return []; };
  1455. this.getVideoTracks = function() { return []; };
  1456. }
  1457. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1458. var newStream = null;
  1459. if (window.webkitMediaStream) {
  1460. newStream = new webkitMediaStream();
  1461. if (newStream) {
  1462. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1463. for (var i = 0; i < tracks.length; i++) {
  1464. newStream.addTrack(tracks[i]);
  1465. }
  1466. }
  1467. }
  1468. else {
  1469. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1470. if (stream) {
  1471. newStream = stream;
  1472. } else {
  1473. newStream =
  1474. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1475. }
  1476. }
  1477. return newStream;
  1478. };
  1479. module.exports = RTCUtils;
  1480. },{"../../service/RTC/Resolutions":105,"../xmpp/SDPUtil":56,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1481. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1482. // Adapter's interface.
  1483. var AdapterJS = AdapterJS || {};
  1484. // Browserify compatibility
  1485. if(typeof exports !== 'undefined') {
  1486. module.exports = AdapterJS;
  1487. }
  1488. AdapterJS.options = AdapterJS.options || {};
  1489. // uncomment to get virtual webcams
  1490. // AdapterJS.options.getAllCams = true;
  1491. // uncomment to prevent the install prompt when the plugin in not yet installed
  1492. // AdapterJS.options.hidePluginInstallPrompt = true;
  1493. // AdapterJS version
  1494. AdapterJS.VERSION = '0.11.0';
  1495. // This function will be called when the WebRTC API is ready to be used
  1496. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1497. // the plugin
  1498. // You may Override this function to synchronise the start of your application
  1499. // with the WebRTC API being ready.
  1500. // If you decide not to override use this synchronisation, it may result in
  1501. // an extensive CPU usage on the plugin start (once per tab loaded)
  1502. // Params:
  1503. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1504. //
  1505. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1506. // The WebRTC API is ready.
  1507. // Override me and do whatever you want here
  1508. };
  1509. // Sets a callback function to be called when the WebRTC interface is ready.
  1510. // The first argument is the function to callback.\
  1511. // Throws an error if the first argument is not a function
  1512. AdapterJS.webRTCReady = function (callback) {
  1513. if (typeof callback !== 'function') {
  1514. throw new Error('Callback provided is not a function');
  1515. }
  1516. if (true === AdapterJS.onwebrtcreadyDone) {
  1517. // All WebRTC interfaces are ready, just call the callback
  1518. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1519. } else {
  1520. // will be triggered automatically when your browser/plugin is ready.
  1521. AdapterJS.onwebrtcready = callback;
  1522. }
  1523. };
  1524. // Plugin namespace
  1525. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1526. // The object to store plugin information
  1527. AdapterJS.WebRTCPlugin.pluginInfo = {
  1528. prefix : 'Tem',
  1529. plugName : 'TemWebRTCPlugin',
  1530. pluginId : 'plugin0',
  1531. type : 'application/x-temwebrtcplugin',
  1532. onload : '__TemWebRTCReady0',
  1533. portalLink : 'http://skylink.io/plugin/',
  1534. downloadLink : null, //set below
  1535. companyName: 'Temasys'
  1536. };
  1537. if(!!navigator.platform.match(/^Mac/i)) {
  1538. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1539. }
  1540. else if(!!navigator.platform.match(/^Win/i)) {
  1541. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1542. }
  1543. // Unique identifier of each opened page
  1544. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1545. // Use this whenever you want to call the plugin.
  1546. AdapterJS.WebRTCPlugin.plugin = null;
  1547. // Set log level for the plugin once it is ready.
  1548. // The different values are
  1549. // This is an asynchronous function that will run when the plugin is ready
  1550. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1551. // Defines webrtc's JS interface according to the plugin's implementation.
  1552. // Define plugin Browsers as WebRTC Interface.
  1553. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1554. // This function detects whether or not a plugin is installed.
  1555. // Checks if Not IE (firefox, for example), else if it's IE,
  1556. // we're running IE and do something. If not it is not supported.
  1557. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1558. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1559. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1560. // Inject the HTML DOM object element into the page.
  1561. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1562. // States of readiness that the plugin goes through when
  1563. // being injected and stated
  1564. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1565. NONE : 0, // no plugin use
  1566. INITIALIZING : 1, // Detected need for plugin
  1567. INJECTING : 2, // Injecting plugin
  1568. INJECTED: 3, // Plugin element injected but not usable yet
  1569. READY: 4 // Plugin ready to be used
  1570. };
  1571. // Current state of the plugin. You cannot use the plugin before this is
  1572. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1573. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1574. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1575. // Used to make sure AdapterJS.onwebrtcready is only called once
  1576. AdapterJS.onwebrtcreadyDone = false;
  1577. // Log levels for the plugin.
  1578. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1579. /*
  1580. Log outputs are prefixed in some cases.
  1581. INFO: Information reported by the plugin.
  1582. ERROR: Errors originating from within the plugin.
  1583. WEBRTC: Error originating from within the libWebRTC library
  1584. */
  1585. // From the least verbose to the most verbose
  1586. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1587. NONE : 'NONE',
  1588. ERROR : 'ERROR',
  1589. WARNING : 'WARNING',
  1590. INFO: 'INFO',
  1591. VERBOSE: 'VERBOSE',
  1592. SENSITIVE: 'SENSITIVE'
  1593. };
  1594. // Does a waiting check before proceeding to load the plugin.
  1595. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1596. // This methid will use an interval to wait for the plugin to be ready.
  1597. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1598. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1599. // This function will be called when plugin is ready. It sends necessary
  1600. // details to the plugin.
  1601. // The function will wait for the document to be ready and the set the
  1602. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1603. // indicating that it can start being requested.
  1604. // This function is not in the IE/Safari condition brackets so that
  1605. // TemPluginLoaded function might be called on Chrome/Firefox.
  1606. // This function is the only private function that is not encapsulated to
  1607. // allow the plugin method to be called.
  1608. __TemWebRTCReady0 = function () {
  1609. if (document.readyState === 'complete') {
  1610. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1611. AdapterJS.maybeThroughWebRTCReady();
  1612. } else {
  1613. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1614. if (document.readyState === 'complete') {
  1615. // TODO: update comments, we wait for the document to be ready
  1616. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1617. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1618. AdapterJS.maybeThroughWebRTCReady();
  1619. }
  1620. }, 100);
  1621. }
  1622. };
  1623. AdapterJS.maybeThroughWebRTCReady = function() {
  1624. if (!AdapterJS.onwebrtcreadyDone) {
  1625. AdapterJS.onwebrtcreadyDone = true;
  1626. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1627. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1628. }
  1629. }
  1630. };
  1631. // Text namespace
  1632. AdapterJS.TEXT = {
  1633. PLUGIN: {
  1634. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1635. 'to work on this browser.',
  1636. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1637. BUTTON: 'Install Now'
  1638. },
  1639. REFRESH: {
  1640. REQUIRE_REFRESH: 'Please refresh page',
  1641. BUTTON: 'Refresh Page'
  1642. }
  1643. };
  1644. // The result of ice connection states.
  1645. // - starting: Ice connection is starting.
  1646. // - checking: Ice connection is checking.
  1647. // - connected Ice connection is connected.
  1648. // - completed Ice connection is connected.
  1649. // - done Ice connection has been completed.
  1650. // - disconnected Ice connection has been disconnected.
  1651. // - failed Ice connection has failed.
  1652. // - closed Ice connection is closed.
  1653. AdapterJS._iceConnectionStates = {
  1654. starting : 'starting',
  1655. checking : 'checking',
  1656. connected : 'connected',
  1657. completed : 'connected',
  1658. done : 'completed',
  1659. disconnected : 'disconnected',
  1660. failed : 'failed',
  1661. closed : 'closed'
  1662. };
  1663. //The IceConnection states that has been fired for each peer.
  1664. AdapterJS._iceConnectionFiredStates = [];
  1665. // Check if WebRTC Interface is defined.
  1666. AdapterJS.isDefined = null;
  1667. // This function helps to retrieve the webrtc detected browser information.
  1668. // This sets:
  1669. // - webrtcDetectedBrowser: The browser agent name.
  1670. // - webrtcDetectedVersion: The browser version.
  1671. // - webrtcDetectedType: The types of webRTC support.
  1672. // - 'moz': Mozilla implementation of webRTC.
  1673. // - 'webkit': WebKit implementation of webRTC.
  1674. // - 'plugin': Using the plugin implementation.
  1675. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1676. var hasMatch, checkMatch = navigator.userAgent.match(
  1677. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1678. if (/trident/i.test(checkMatch[1])) {
  1679. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1680. webrtcDetectedBrowser = 'IE';
  1681. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1682. } else if (checkMatch[1] === 'Chrome') {
  1683. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1684. if (hasMatch !== null) {
  1685. webrtcDetectedBrowser = 'opera';
  1686. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1687. }
  1688. }
  1689. if (navigator.userAgent.indexOf('Safari')) {
  1690. if (typeof InstallTrigger !== 'undefined') {
  1691. webrtcDetectedBrowser = 'firefox';
  1692. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1693. webrtcDetectedBrowser = 'IE';
  1694. } else if (
  1695. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1696. webrtcDetectedBrowser = 'safari';
  1697. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1698. webrtcDetectedBrowser = 'opera';
  1699. } else if (!!window.chrome) {
  1700. webrtcDetectedBrowser = 'chrome';
  1701. }
  1702. }
  1703. if (!webrtcDetectedBrowser) {
  1704. webrtcDetectedVersion = checkMatch[1];
  1705. }
  1706. if (!webrtcDetectedVersion) {
  1707. try {
  1708. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1709. [navigator.appName, navigator.appVersion, '-?'];
  1710. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1711. checkMatch.splice(1, 1, hasMatch[1]);
  1712. }
  1713. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1714. } catch (error) { }
  1715. }
  1716. };
  1717. // To fix configuration as some browsers does not support
  1718. // the 'urls' attribute.
  1719. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1720. if (pcConfig === null) {
  1721. return;
  1722. }
  1723. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1724. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1725. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1726. delete pcConfig.iceServers[i].urls;
  1727. }
  1728. }
  1729. };
  1730. AdapterJS.addEvent = function(elem, evnt, func) {
  1731. if (elem.addEventListener) { // W3C DOM
  1732. elem.addEventListener(evnt, func, false);
  1733. } else if (elem.attachEvent) {// OLD IE DOM
  1734. elem.attachEvent('on'+evnt, func);
  1735. } else { // No much to do
  1736. elem[evnt] = func;
  1737. }
  1738. };
  1739. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1740. // only inject once the page is ready
  1741. if (document.readyState !== 'complete') {
  1742. return;
  1743. }
  1744. var w = window;
  1745. var i = document.createElement('iframe');
  1746. i.style.position = 'fixed';
  1747. i.style.top = '-41px';
  1748. i.style.left = 0;
  1749. i.style.right = 0;
  1750. i.style.width = '100%';
  1751. i.style.height = '40px';
  1752. i.style.backgroundColor = '#ffffe1';
  1753. i.style.border = 'none';
  1754. i.style.borderBottom = '1px solid #888888';
  1755. i.style.zIndex = '9999999';
  1756. if(typeof i.style.webkitTransition === 'string') {
  1757. i.style.webkitTransition = 'all .5s ease-out';
  1758. } else if(typeof i.style.transition === 'string') {
  1759. i.style.transition = 'all .5s ease-out';
  1760. }
  1761. document.body.appendChild(i);
  1762. c = (i.contentWindow) ? i.contentWindow :
  1763. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1764. c.document.open();
  1765. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1766. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1767. 'middle; cursor: default;">' + text + '</span>');
  1768. if(buttonText && buttonLink) {
  1769. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1770. c.document.close();
  1771. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1772. if (!!displayRefreshBar) {
  1773. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1774. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1775. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1776. }
  1777. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1778. e.preventDefault();
  1779. try {
  1780. event.cancelBubble = true;
  1781. } catch(error) { }
  1782. });
  1783. }
  1784. else {
  1785. c.document.close();
  1786. }
  1787. AdapterJS.addEvent(c.document, 'click', function() {
  1788. w.document.body.removeChild(i);
  1789. });
  1790. setTimeout(function() {
  1791. if(typeof i.style.webkitTransform === 'string') {
  1792. i.style.webkitTransform = 'translateY(40px)';
  1793. } else if(typeof i.style.transform === 'string') {
  1794. i.style.transform = 'translateY(40px)';
  1795. } else {
  1796. i.style.top = '0px';
  1797. }
  1798. }, 300);
  1799. };
  1800. // -----------------------------------------------------------
  1801. // Detected webrtc implementation. Types are:
  1802. // - 'moz': Mozilla implementation of webRTC.
  1803. // - 'webkit': WebKit implementation of webRTC.
  1804. // - 'plugin': Using the plugin implementation.
  1805. webrtcDetectedType = null;
  1806. // Detected webrtc datachannel support. Types are:
  1807. // - 'SCTP': SCTP datachannel support.
  1808. // - 'RTP': RTP datachannel support.
  1809. webrtcDetectedDCSupport = null;
  1810. // Set the settings for creating DataChannels, MediaStream for
  1811. // Cross-browser compability.
  1812. // - This is only for SCTP based support browsers.
  1813. // the 'urls' attribute.
  1814. checkMediaDataChannelSettings =
  1815. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1816. if (typeof callback !== 'function') {
  1817. return;
  1818. }
  1819. var beOfferer = true;
  1820. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1821. // Nightly version does not require MozDontOfferDataChannel for interop
  1822. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1823. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1824. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1825. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1826. // Resends an updated version of constraints for MozDataChannel to work
  1827. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1828. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1829. try {
  1830. delete constraints.mandatory.MozDontOfferDataChannel;
  1831. } catch (error) {
  1832. console.error('Failed deleting MozDontOfferDataChannel');
  1833. console.error(error);
  1834. }
  1835. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1836. constraints.mandatory.MozDontOfferDataChannel = true;
  1837. }
  1838. if (!isLocalFirefox) {
  1839. // temporary measure to remove Moz* constraints in non Firefox browsers
  1840. for (var prop in constraints.mandatory) {
  1841. if (constraints.mandatory.hasOwnProperty(prop)) {
  1842. if (prop.indexOf('Moz') !== -1) {
  1843. delete constraints.mandatory[prop];
  1844. }
  1845. }
  1846. }
  1847. }
  1848. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1849. // interopability of the media stream
  1850. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1851. beOfferer = false;
  1852. }
  1853. callback(beOfferer, constraints);
  1854. };
  1855. // Handles the differences for all browsers ice connection state output.
  1856. // - Tested outcomes are:
  1857. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1858. // - Chrome (answerer) : 'checking' > 'connected'
  1859. // - Firefox (offerer) : 'checking' > 'connected'
  1860. // - Firefox (answerer): 'checking' > 'connected'
  1861. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1862. if (typeof callback !== 'function') {
  1863. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1864. return;
  1865. }
  1866. peerId = (peerId) ? peerId : 'peer';
  1867. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1868. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1869. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1870. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1871. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1872. }
  1873. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1874. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1875. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1876. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1877. setTimeout(function () {
  1878. AdapterJS._iceConnectionFiredStates[peerId]
  1879. .push(AdapterJS._iceConnectionStates.done);
  1880. callback(AdapterJS._iceConnectionStates.done);
  1881. }, 1000);
  1882. }
  1883. callback(iceConnectionState);
  1884. }
  1885. return;
  1886. };
  1887. // Firefox:
  1888. // - Creates iceServer from the url for Firefox.
  1889. // - Create iceServer with stun url.
  1890. // - Create iceServer with turn url.
  1891. // - Ignore the transport parameter from TURN url for FF version <=27.
  1892. // - Return null for createIceServer if transport=tcp.
  1893. // - FF 27 and above supports transport parameters in TURN url,
  1894. // - So passing in the full url to create iceServer.
  1895. // Chrome:
  1896. // - Creates iceServer from the url for Chrome M33 and earlier.
  1897. // - Create iceServer with stun url.
  1898. // - Chrome M28 & above uses below TURN format.
  1899. // Plugin:
  1900. // - Creates Ice Server for Plugin Browsers
  1901. // - If Stun - Create iceServer with stun url.
  1902. // - Else - Create iceServer with turn url
  1903. // - This is a WebRTC Function
  1904. createIceServer = null;
  1905. // Firefox:
  1906. // - Creates IceServers for Firefox
  1907. // - Use .url for FireFox.
  1908. // - Multiple Urls support
  1909. // Chrome:
  1910. // - Creates iceServers from the urls for Chrome M34 and above.
  1911. // - .urls is supported since Chrome M34.
  1912. // - Multiple Urls support
  1913. // Plugin:
  1914. // - Creates Ice Servers for Plugin Browsers
  1915. // - Multiple Urls support
  1916. // - This is a WebRTC Function
  1917. createIceServers = null;
  1918. //------------------------------------------------------------
  1919. //The RTCPeerConnection object.
  1920. RTCPeerConnection = null;
  1921. // Creates RTCSessionDescription object for Plugin Browsers
  1922. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  1923. RTCSessionDescription : null;
  1924. // Creates RTCIceCandidate object for Plugin Browsers
  1925. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  1926. RTCIceCandidate : null;
  1927. // Get UserMedia (only difference is the prefix).
  1928. // Code from Adam Barth.
  1929. getUserMedia = null;
  1930. // Attach a media stream to an element.
  1931. attachMediaStream = null;
  1932. // Re-attach a media stream to an element.
  1933. reattachMediaStream = null;
  1934. // Detected browser agent name. Types are:
  1935. // - 'firefox': Firefox browser.
  1936. // - 'chrome': Chrome browser.
  1937. // - 'opera': Opera browser.
  1938. // - 'safari': Safari browser.
  1939. // - 'IE' - Internet Explorer browser.
  1940. webrtcDetectedBrowser = null;
  1941. // Detected browser version.
  1942. webrtcDetectedVersion = null;
  1943. // Check for browser types and react accordingly
  1944. if (navigator.mozGetUserMedia) {
  1945. webrtcDetectedBrowser = 'firefox';
  1946. webrtcDetectedVersion = parseInt(navigator
  1947. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1948. webrtcDetectedType = 'moz';
  1949. webrtcDetectedDCSupport = 'SCTP';
  1950. RTCPeerConnection = function (pcConfig, pcConstraints) {
  1951. AdapterJS.maybeFixConfiguration(pcConfig);
  1952. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  1953. };
  1954. // The RTCSessionDescription object.
  1955. RTCSessionDescription = mozRTCSessionDescription;
  1956. window.RTCSessionDescription = RTCSessionDescription;
  1957. // The RTCIceCandidate object.
  1958. RTCIceCandidate = mozRTCIceCandidate;
  1959. window.RTCIceCandidate = RTCIceCandidate;
  1960. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1961. navigator.getUserMedia = window.getUserMedia;
  1962. // Shim for MediaStreamTrack.getSources.
  1963. MediaStreamTrack.getSources = function(successCb) {
  1964. setTimeout(function() {
  1965. var infos = [
  1966. { kind: 'audio', id: 'default', label:'', facing:'' },
  1967. { kind: 'video', id: 'default', label:'', facing:'' }
  1968. ];
  1969. successCb(infos);
  1970. }, 0);
  1971. };
  1972. createIceServer = function (url, username, password) {
  1973. var iceServer = null;
  1974. var url_parts = url.split(':');
  1975. if (url_parts[0].indexOf('stun') === 0) {
  1976. iceServer = { url : url };
  1977. } else if (url_parts[0].indexOf('turn') === 0) {
  1978. if (webrtcDetectedVersion < 27) {
  1979. var turn_url_parts = url.split('?');
  1980. if (turn_url_parts.length === 1 ||
  1981. turn_url_parts[1].indexOf('transport=udp') === 0) {
  1982. iceServer = {
  1983. url : turn_url_parts[0],
  1984. credential : password,
  1985. username : username
  1986. };
  1987. }
  1988. } else {
  1989. iceServer = {
  1990. url : url,
  1991. credential : password,
  1992. username : username
  1993. };
  1994. }
  1995. }
  1996. return iceServer;
  1997. };
  1998. createIceServers = function (urls, username, password) {
  1999. var iceServers = [];
  2000. for (i = 0; i < urls.length; i++) {
  2001. var iceServer = createIceServer(urls[i], username, password);
  2002. if (iceServer !== null) {
  2003. iceServers.push(iceServer);
  2004. }
  2005. }
  2006. return iceServers;
  2007. };
  2008. attachMediaStream = function (element, stream) {
  2009. element.mozSrcObject = stream;
  2010. if (stream !== null)
  2011. element.play();
  2012. return element;
  2013. };
  2014. reattachMediaStream = function (to, from) {
  2015. to.mozSrcObject = from.mozSrcObject;
  2016. to.play();
  2017. return to;
  2018. };
  2019. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2020. if (!callback) {
  2021. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2022. ': 1 argument required, but only 0 present.');
  2023. }
  2024. return callback([]);
  2025. };
  2026. // Fake get{Video,Audio}Tracks
  2027. if (!MediaStream.prototype.getVideoTracks) {
  2028. MediaStream.prototype.getVideoTracks = function () {
  2029. return [];
  2030. };
  2031. }
  2032. if (!MediaStream.prototype.getAudioTracks) {
  2033. MediaStream.prototype.getAudioTracks = function () {
  2034. return [];
  2035. };
  2036. }
  2037. AdapterJS.maybeThroughWebRTCReady();
  2038. } else if (navigator.webkitGetUserMedia) {
  2039. webrtcDetectedBrowser = 'chrome';
  2040. webrtcDetectedType = 'webkit';
  2041. webrtcDetectedVersion = parseInt(navigator
  2042. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2043. // check if browser is opera 20+
  2044. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2045. if (checkIfOpera !== null) {
  2046. webrtcDetectedBrowser = 'opera';
  2047. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2048. }
  2049. // check browser datachannel support
  2050. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2051. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2052. webrtcDetectedDCSupport = 'SCTP';
  2053. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2054. webrtcDetectedVersion > 24) {
  2055. webrtcDetectedDCSupport = 'RTP';
  2056. } else {
  2057. webrtcDetectedDCSupport = '';
  2058. }
  2059. createIceServer = function (url, username, password) {
  2060. var iceServer = null;
  2061. var url_parts = url.split(':');
  2062. if (url_parts[0].indexOf('stun') === 0) {
  2063. iceServer = { 'url' : url };
  2064. } else if (url_parts[0].indexOf('turn') === 0) {
  2065. iceServer = {
  2066. 'url' : url,
  2067. 'credential' : password,
  2068. 'username' : username
  2069. };
  2070. }
  2071. return iceServer;
  2072. };
  2073. createIceServers = function (urls, username, password) {
  2074. var iceServers = [];
  2075. if (webrtcDetectedVersion >= 34) {
  2076. iceServers = {
  2077. 'urls' : urls,
  2078. 'credential' : password,
  2079. 'username' : username
  2080. };
  2081. } else {
  2082. for (i = 0; i < urls.length; i++) {
  2083. var iceServer = createIceServer(urls[i], username, password);
  2084. if (iceServer !== null) {
  2085. iceServers.push(iceServer);
  2086. }
  2087. }
  2088. }
  2089. return iceServers;
  2090. };
  2091. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2092. if (webrtcDetectedVersion < 34) {
  2093. AdapterJS.maybeFixConfiguration(pcConfig);
  2094. }
  2095. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2096. };
  2097. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2098. navigator.getUserMedia = window.getUserMedia;
  2099. attachMediaStream = function (element, stream) {
  2100. if (typeof element.srcObject !== 'undefined') {
  2101. element.srcObject = stream;
  2102. } else if (typeof element.mozSrcObject !== 'undefined') {
  2103. element.mozSrcObject = stream;
  2104. } else if (typeof element.src !== 'undefined') {
  2105. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2106. } else {
  2107. console.log('Error attaching stream to element.');
  2108. }
  2109. return element;
  2110. };
  2111. reattachMediaStream = function (to, from) {
  2112. to.src = from.src;
  2113. return to;
  2114. };
  2115. AdapterJS.maybeThroughWebRTCReady();
  2116. } else { // TRY TO USE PLUGIN
  2117. // IE 9 is not offering an implementation of console.log until you open a console
  2118. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2119. /* jshint -W020 */
  2120. console = {} || console;
  2121. // Implemented based on console specs from MDN
  2122. // You may override these functions
  2123. console.log = function (arg) {};
  2124. console.info = function (arg) {};
  2125. console.error = function (arg) {};
  2126. console.dir = function (arg) {};
  2127. console.exception = function (arg) {};
  2128. console.trace = function (arg) {};
  2129. console.warn = function (arg) {};
  2130. console.count = function (arg) {};
  2131. console.debug = function (arg) {};
  2132. console.count = function (arg) {};
  2133. console.time = function (arg) {};
  2134. console.timeEnd = function (arg) {};
  2135. console.group = function (arg) {};
  2136. console.groupCollapsed = function (arg) {};
  2137. console.groupEnd = function (arg) {};
  2138. /* jshint +W020 */
  2139. }
  2140. webrtcDetectedType = 'plugin';
  2141. webrtcDetectedDCSupport = 'plugin';
  2142. AdapterJS.parseWebrtcDetectedBrowser();
  2143. isIE = webrtcDetectedBrowser === 'IE';
  2144. /* jshint -W035 */
  2145. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2146. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2147. /* empty because it needs to prevent the function from running. */
  2148. }
  2149. };
  2150. /* jshint +W035 */
  2151. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2152. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2153. // Call immediately if possible
  2154. // Once the plugin is set, the code will always take this path
  2155. callback();
  2156. } else {
  2157. // otherwise start a 100ms interval
  2158. var checkPluginReadyState = setInterval(function () {
  2159. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2160. clearInterval(checkPluginReadyState);
  2161. callback();
  2162. }
  2163. }, 100);
  2164. }
  2165. };
  2166. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2167. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2168. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2169. });
  2170. };
  2171. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2172. // only inject once the page is ready
  2173. if (document.readyState !== 'complete') {
  2174. return;
  2175. }
  2176. // Prevent multiple injections
  2177. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2178. return;
  2179. }
  2180. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2181. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2182. var frag = document.createDocumentFragment();
  2183. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2184. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2185. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2186. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2187. '<param name="pluginId" value="' +
  2188. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2189. '<param name="windowless" value="false" /> ' +
  2190. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2191. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2192. '" />' +
  2193. // uncomment to be able to use virtual cams
  2194. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2195. '</object>';
  2196. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2197. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2198. }
  2199. document.body.appendChild(frag);
  2200. // Need to re-fetch the plugin
  2201. AdapterJS.WebRTCPlugin.plugin =
  2202. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2203. } else {
  2204. // Load Plugin
  2205. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2206. AdapterJS.WebRTCPlugin.plugin.id =
  2207. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2208. // IE will only start the plugin if it's ACTUALLY visible
  2209. if (isIE) {
  2210. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2211. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2212. } else { // The size of the plugin on Safari should be 0x0px
  2213. // so that the autorisation prompt is at the top
  2214. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2215. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2216. }
  2217. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2218. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2219. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2220. '<param name="pluginId" value="' +
  2221. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2222. '<param name="windowless" value="false" /> ' +
  2223. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2224. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2225. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2226. }
  2227. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2228. };
  2229. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2230. function (comName, plugName, installedCb, notInstalledCb) {
  2231. if (!isIE) {
  2232. var pluginArray = navigator.plugins;
  2233. for (var i = 0; i < pluginArray.length; i++) {
  2234. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2235. installedCb();
  2236. return;
  2237. }
  2238. }
  2239. notInstalledCb();
  2240. } else {
  2241. try {
  2242. var axo = new ActiveXObject(comName + '.' + plugName);
  2243. } catch (e) {
  2244. notInstalledCb();
  2245. return;
  2246. }
  2247. installedCb();
  2248. }
  2249. };
  2250. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2251. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2252. AdapterJS.isDefined = function (variable) {
  2253. return variable !== null && variable !== undefined;
  2254. };
  2255. createIceServer = function (url, username, password) {
  2256. var iceServer = null;
  2257. var url_parts = url.split(':');
  2258. if (url_parts[0].indexOf('stun') === 0) {
  2259. iceServer = {
  2260. 'url' : url,
  2261. 'hasCredentials' : false
  2262. };
  2263. } else if (url_parts[0].indexOf('turn') === 0) {
  2264. iceServer = {
  2265. 'url' : url,
  2266. 'hasCredentials' : true,
  2267. 'credential' : password,
  2268. 'username' : username
  2269. };
  2270. }
  2271. return iceServer;
  2272. };
  2273. createIceServers = function (urls, username, password) {
  2274. var iceServers = [];
  2275. for (var i = 0; i < urls.length; ++i) {
  2276. iceServers.push(createIceServer(urls[i], username, password));
  2277. }
  2278. return iceServers;
  2279. };
  2280. RTCSessionDescription = function (info) {
  2281. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2282. return AdapterJS.WebRTCPlugin.plugin.
  2283. ConstructSessionDescription(info.type, info.sdp);
  2284. };
  2285. RTCPeerConnection = function (servers, constraints) {
  2286. var iceServers = null;
  2287. if (servers) {
  2288. iceServers = servers.iceServers;
  2289. for (var i = 0; i < iceServers.length; i++) {
  2290. if (iceServers[i].urls && !iceServers[i].url) {
  2291. iceServers[i].url = iceServers[i].urls;
  2292. }
  2293. iceServers[i].hasCredentials = AdapterJS.
  2294. isDefined(iceServers[i].username) &&
  2295. AdapterJS.isDefined(iceServers[i].credential);
  2296. }
  2297. }
  2298. var mandatory = (constraints && constraints.mandatory) ?
  2299. constraints.mandatory : null;
  2300. var optional = (constraints && constraints.optional) ?
  2301. constraints.optional : null;
  2302. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2303. return AdapterJS.WebRTCPlugin.plugin.
  2304. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2305. iceServers, mandatory, optional);
  2306. };
  2307. MediaStreamTrack = {};
  2308. MediaStreamTrack.getSources = function (callback) {
  2309. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2310. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2311. });
  2312. };
  2313. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2314. constraints.audio = constraints.audio || false;
  2315. constraints.video = constraints.video || false;
  2316. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2317. AdapterJS.WebRTCPlugin.plugin.
  2318. getUserMedia(constraints, successCallback, failureCallback);
  2319. });
  2320. };
  2321. window.navigator.getUserMedia = window.getUserMedia;
  2322. attachMediaStream = function (element, stream) {
  2323. if (!element || !element.parentNode) {
  2324. return;
  2325. }
  2326. var streamId
  2327. if (stream === null) {
  2328. streamId = '';
  2329. }
  2330. else {
  2331. stream.enableSoundTracks(true);
  2332. streamId = stream.id;
  2333. }
  2334. if (element.nodeName.toLowerCase() !== 'audio') {
  2335. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2336. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2337. var frag = document.createDocumentFragment();
  2338. var temp = document.createElement('div');
  2339. var classHTML = '';
  2340. if (element.className) {
  2341. classHTML = 'class="' + element.className + '" ';
  2342. } else if (element.attributes && element.attributes['class']) {
  2343. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2344. }
  2345. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2346. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2347. '<param name="pluginId" value="' + elementId + '" /> ' +
  2348. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2349. '<param name="windowless" value="true" /> ' +
  2350. '<param name="streamId" value="' + streamId + '" /> ' +
  2351. '</object>';
  2352. while (temp.firstChild) {
  2353. frag.appendChild(temp.firstChild);
  2354. }
  2355. var height = '';
  2356. var width = '';
  2357. if (element.getBoundingClientRect) {
  2358. var rectObject = element.getBoundingClientRect();
  2359. width = rectObject.width + 'px';
  2360. height = rectObject.height + 'px';
  2361. }
  2362. else if (element.width) {
  2363. width = element.width;
  2364. height = element.height;
  2365. } else {
  2366. // TODO: What scenario could bring us here?
  2367. }
  2368. element.parentNode.insertBefore(frag, element);
  2369. frag = document.getElementById(elementId);
  2370. frag.width = width;
  2371. frag.height = height;
  2372. element.parentNode.removeChild(element);
  2373. } else {
  2374. var children = element.children;
  2375. for (var i = 0; i !== children.length; ++i) {
  2376. if (children[i].name === 'streamId') {
  2377. children[i].value = streamId;
  2378. break;
  2379. }
  2380. }
  2381. element.setStreamId(streamId);
  2382. }
  2383. var newElement = document.getElementById(elementId);
  2384. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2385. if (isIE) { // on IE the event needs to be plugged manually
  2386. newElement.attachEvent('onplaying', newElement.onplaying);
  2387. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2388. newElement._TemOnClick = function (id) {
  2389. var arg = {
  2390. srcElement : document.getElementById(id)
  2391. };
  2392. newElement.onclick(arg);
  2393. };
  2394. }
  2395. return newElement;
  2396. } else {
  2397. return element;
  2398. }
  2399. };
  2400. reattachMediaStream = function (to, from) {
  2401. var stream = null;
  2402. var children = from.children;
  2403. for (var i = 0; i !== children.length; ++i) {
  2404. if (children[i].name === 'streamId') {
  2405. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2406. stream = AdapterJS.WebRTCPlugin.plugin
  2407. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2408. break;
  2409. }
  2410. }
  2411. if (stream !== null) {
  2412. return attachMediaStream(to, stream);
  2413. } else {
  2414. console.log('Could not find the stream associated with this element');
  2415. }
  2416. };
  2417. RTCIceCandidate = function (candidate) {
  2418. if (!candidate.sdpMid) {
  2419. candidate.sdpMid = '';
  2420. }
  2421. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2422. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2423. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2424. );
  2425. };
  2426. // inject plugin
  2427. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2428. AdapterJS.WebRTCPlugin.injectPlugin();
  2429. };
  2430. // This function will be called if the plugin is needed (browser different
  2431. // from Chrome or Firefox), but the plugin is not installed.
  2432. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2433. function() {
  2434. AdapterJS.addEvent(document,
  2435. 'readystatechange',
  2436. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2437. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2438. };
  2439. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2440. if (AdapterJS.options.hidePluginInstallPrompt) {
  2441. return;
  2442. }
  2443. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2444. if(downloadLink) { // if download link
  2445. var popupString;
  2446. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2447. popupString = 'This website requires you to install the ' +
  2448. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2449. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2450. ' WebRTC Plugin</a>' +
  2451. ' to work on this browser.';
  2452. } else { // no portal link, just print a generic explanation
  2453. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2454. }
  2455. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2456. } else { // no download link, just print a generic explanation
  2457. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2458. }
  2459. };
  2460. // Try to detect the plugin and act accordingly
  2461. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2462. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2463. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2464. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2465. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2466. }
  2467. (function () {
  2468. 'use strict';
  2469. var baseGetUserMedia = null;
  2470. AdapterJS.TEXT.EXTENSION = {
  2471. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2472. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2473. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2474. BUTTON_FF: 'Install Now',
  2475. BUTTON_CHROME: 'Go to Chrome Web Store'
  2476. };
  2477. var clone = function(obj) {
  2478. if (null == obj || "object" != typeof obj) return obj;
  2479. var copy = obj.constructor();
  2480. for (var attr in obj) {
  2481. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2482. }
  2483. return copy;
  2484. };
  2485. if (window.navigator.mozGetUserMedia) {
  2486. baseGetUserMedia = window.navigator.getUserMedia;
  2487. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2488. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2489. // intercepting screensharing requests
  2490. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2491. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2492. }
  2493. var updatedConstraints = clone(constraints);
  2494. //constraints.video.mediaSource = constraints.video.mediaSource;
  2495. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2496. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2497. // strange but this works anyway
  2498. var checkIfReady = setInterval(function () {
  2499. if (document.readyState === 'complete') {
  2500. clearInterval(checkIfReady);
  2501. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2502. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2503. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2504. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2505. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2506. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2507. } else {
  2508. failureCb(error);
  2509. }
  2510. });
  2511. }
  2512. }, 1);
  2513. } else { // regular GetUserMediaRequest
  2514. baseGetUserMedia(constraints, successCb, failureCb);
  2515. }
  2516. };
  2517. getUserMedia = navigator.getUserMedia;
  2518. } else if (window.navigator.webkitGetUserMedia) {
  2519. baseGetUserMedia = window.navigator.getUserMedia;
  2520. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2521. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2522. if (window.webrtcDetectedBrowser !== 'chrome') {
  2523. throw new Error('Current browser does not support screensharing');
  2524. }
  2525. // would be fine since no methods
  2526. var updatedConstraints = clone(constraints);
  2527. var chromeCallback = function(error, sourceId) {
  2528. if(!error) {
  2529. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2530. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2531. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2532. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2533. if (sourceId) {
  2534. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2535. }
  2536. delete updatedConstraints.video.mediaSource;
  2537. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2538. } else {
  2539. if (error === 'permission-denied') {
  2540. throw new Error('Permission denied for screen retrieval');
  2541. } else {
  2542. throw new Error('Failed retrieving selected screen');
  2543. }
  2544. }
  2545. };
  2546. var onIFrameCallback = function (event) {
  2547. if (!event.data) {
  2548. return;
  2549. }
  2550. if (event.data.chromeMediaSourceId) {
  2551. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2552. chromeCallback('permission-denied');
  2553. } else {
  2554. chromeCallback(null, event.data.chromeMediaSourceId);
  2555. }
  2556. }
  2557. if (event.data.chromeExtensionStatus) {
  2558. if (event.data.chromeExtensionStatus === 'not-installed') {
  2559. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2560. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2561. event.data.data, true, true);
  2562. } else {
  2563. chromeCallback(event.data.chromeExtensionStatus, null);
  2564. }
  2565. }
  2566. // this event listener is no more needed
  2567. window.removeEventListener('message', onIFrameCallback);
  2568. };
  2569. window.addEventListener('message', onIFrameCallback);
  2570. postFrameMessage({
  2571. captureSourceId: true
  2572. });
  2573. } else {
  2574. baseGetUserMedia(constraints, successCb, failureCb);
  2575. }
  2576. };
  2577. getUserMedia = navigator.getUserMedia;
  2578. } else {
  2579. baseGetUserMedia = window.navigator.getUserMedia;
  2580. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2581. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2582. // would be fine since no methods
  2583. var updatedConstraints = clone(constraints);
  2584. // wait for plugin to be ready
  2585. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2586. // check if screensharing feature is available
  2587. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2588. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2589. // set the constraints
  2590. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2591. updatedConstraints.video.optional.push({
  2592. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2593. });
  2594. delete updatedConstraints.video.mediaSource;
  2595. } else {
  2596. throw new Error('Your WebRTC plugin does not support screensharing');
  2597. }
  2598. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2599. });
  2600. } else {
  2601. baseGetUserMedia(constraints, successCb, failureCb);
  2602. }
  2603. };
  2604. getUserMedia = window.navigator.getUserMedia;
  2605. }
  2606. if (window.webrtcDetectedBrowser === 'chrome') {
  2607. var iframe = document.createElement('iframe');
  2608. iframe.onload = function() {
  2609. iframe.isLoaded = true;
  2610. };
  2611. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2612. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2613. iframe.style.display = 'none';
  2614. (document.body || document.documentElement).appendChild(iframe);
  2615. var postFrameMessage = function (object) {
  2616. object = object || {};
  2617. if (!iframe.isLoaded) {
  2618. setTimeout(function () {
  2619. iframe.contentWindow.postMessage(object, '*');
  2620. }, 100);
  2621. return;
  2622. }
  2623. iframe.contentWindow.postMessage(object, '*');
  2624. };
  2625. }
  2626. })();
  2627. },{}],11:[function(require,module,exports){
  2628. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2629. var UI = {};
  2630. var VideoLayout = require("./videolayout/VideoLayout.js");
  2631. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2632. var Prezi = require("./prezi/Prezi.js");
  2633. var Etherpad = require("./etherpad/Etherpad.js");
  2634. var Chat = require("./side_pannels/chat/Chat.js");
  2635. var Toolbar = require("./toolbars/Toolbar");
  2636. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2637. var BottomToolbar = require("./toolbars/BottomToolbar");
  2638. var ContactList = require("./side_pannels/contactlist/ContactList");
  2639. var Avatar = require("./avatar/Avatar");
  2640. var EventEmitter = require("events");
  2641. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2642. var Settings = require("./../settings/Settings");
  2643. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2644. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2645. UI.messageHandler = require("./util/MessageHandler");
  2646. var messageHandler = UI.messageHandler;
  2647. var Authentication = require("./authentication/Authentication");
  2648. var UIUtil = require("./util/UIUtil");
  2649. var NicknameHandler = require("./util/NicknameHandler");
  2650. var JitsiPopover = require("./util/JitsiPopover");
  2651. var CQEvents = require("../../service/connectionquality/CQEvents");
  2652. var DesktopSharingEventTypes
  2653. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2654. var RTCEvents = require("../../service/RTC/RTCEvents");
  2655. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2656. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2657. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2658. var UIEvents = require("../../service/UI/UIEvents");
  2659. var MemberEvents = require("../../service/members/Events");
  2660. var eventEmitter = new EventEmitter();
  2661. var roomName = null;
  2662. function promptDisplayName() {
  2663. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2664. message += APP.translation.translateString(
  2665. "dialog.displayNameRequired");
  2666. message += '</h2>' +
  2667. '<input name="displayName" type="text" data-i18n=' +
  2668. '"[placeholder]defaultNickname" placeholder="' +
  2669. APP.translation.translateString(
  2670. "defaultNickname", {name: "Jane Pink"}) +
  2671. '" autofocus>';
  2672. var buttonTxt
  2673. = APP.translation.generateTranslationHTML("dialog.Ok");
  2674. var buttons = [];
  2675. buttons.push({title: buttonTxt, value: "ok"});
  2676. messageHandler.openDialog(null, message,
  2677. true,
  2678. buttons,
  2679. function (e, v, m, f) {
  2680. if (v == "ok") {
  2681. var displayName = f.displayName;
  2682. if (displayName) {
  2683. VideoLayout.inputDisplayNameHandler(displayName);
  2684. return true;
  2685. }
  2686. }
  2687. e.preventDefault();
  2688. },
  2689. function () {
  2690. var form = $.prompt.getPrompt();
  2691. var input = form.find("input[name='displayName']");
  2692. input.focus();
  2693. var button = form.find("button");
  2694. button.attr("disabled", "disabled");
  2695. input.keyup(function () {
  2696. if(!input.val())
  2697. button.attr("disabled", "disabled");
  2698. else
  2699. button.removeAttr("disabled");
  2700. });
  2701. }
  2702. );
  2703. }
  2704. function notifyForInitialMute() {
  2705. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2706. "notify.muted", null, {timeOut: 120000});
  2707. }
  2708. function setupPrezi() {
  2709. $("#reloadPresentationLink").click(function() {
  2710. Prezi.reloadPresentation();
  2711. });
  2712. }
  2713. function setupChat() {
  2714. Chat.init();
  2715. $("#toggle_smileys").click(function() {
  2716. Chat.toggleSmileys();
  2717. });
  2718. }
  2719. function setupToolbars() {
  2720. Toolbar.init(UI);
  2721. Toolbar.setupButtonsFromConfig();
  2722. BottomToolbar.init();
  2723. }
  2724. function streamHandler(stream, isMuted) {
  2725. switch (stream.type) {
  2726. case "audio":
  2727. VideoLayout.changeLocalAudio(stream, isMuted);
  2728. break;
  2729. case "video":
  2730. VideoLayout.changeLocalVideo(stream, isMuted);
  2731. break;
  2732. case "stream":
  2733. VideoLayout.changeLocalStream(stream, isMuted);
  2734. break;
  2735. }
  2736. }
  2737. function onXmppConnectionFailed(stropheErrorMsg) {
  2738. var title = APP.translation.generateTranslationHTML(
  2739. "dialog.error");
  2740. var message;
  2741. if (stropheErrorMsg) {
  2742. message = APP.translation.generateTranslationHTML(
  2743. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2744. } else {
  2745. message = APP.translation.generateTranslationHTML(
  2746. "dialog.connectError");
  2747. }
  2748. messageHandler.openDialog(
  2749. title, message, true, {}, function (e, v, m, f) { return false; });
  2750. }
  2751. function onDisposeConference(unload) {
  2752. Toolbar.showAuthenticateButton(false);
  2753. }
  2754. function onDisplayNameChanged(jid, displayName) {
  2755. ContactList.onDisplayNameChange(jid, displayName);
  2756. SettingsMenu.onDisplayNameChange(jid, displayName);
  2757. VideoLayout.onDisplayNameChanged(jid, displayName);
  2758. }
  2759. function registerListeners() {
  2760. APP.RTC.addStreamListener(streamHandler,
  2761. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2762. APP.RTC.addStreamListener(streamHandler,
  2763. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2764. APP.RTC.addStreamListener(function (stream) {
  2765. VideoLayout.onRemoteStreamAdded(stream);
  2766. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2767. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2768. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  2769. function (resourceJid) {
  2770. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2771. });
  2772. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2773. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2774. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2775. endpointsEnteringLastN, stream);
  2776. });
  2777. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2778. function (devices) {
  2779. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2780. });
  2781. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  2782. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function () {
  2783. // when the data channel becomes available, tell the bridge about video
  2784. // selections so that it can do adaptive simulcast,
  2785. // we want the notification to trigger even if userJid is undefined,
  2786. // or null.
  2787. var userJid = APP.UI.getLargeVideoJid();
  2788. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userJid);
  2789. });
  2790. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  2791. var resourceJid;
  2792. if(jid === APP.statistics.LOCAL_JID) {
  2793. resourceJid = AudioLevels.LOCAL_LEVEL;
  2794. if(APP.RTC.localAudio.isMuted()) {
  2795. audioLevel = 0;
  2796. }
  2797. } else {
  2798. resourceJid = Strophe.getResourceFromJid(jid);
  2799. }
  2800. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2801. UI.getLargeVideoJid());
  2802. });
  2803. APP.desktopsharing.addListener(function () {
  2804. ToolbarToggler.showDesktopSharingButton();
  2805. }, DesktopSharingEventTypes.INIT);
  2806. APP.desktopsharing.addListener(
  2807. Toolbar.changeDesktopSharingButtonState,
  2808. DesktopSharingEventTypes.SWITCHING_DONE);
  2809. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2810. VideoLayout.updateLocalConnectionStats);
  2811. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2812. VideoLayout.updateConnectionStats);
  2813. APP.connectionquality.addListener(CQEvents.STOP,
  2814. VideoLayout.onStatsStop);
  2815. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2816. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2817. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2818. messageHandler.openMessageDialog(
  2819. 'dialog.serviceUnavailable',
  2820. 'dialog.gracefulShutdown'
  2821. );
  2822. });
  2823. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2824. var title = APP.translation.generateTranslationHTML(
  2825. "dialog.reservationError");
  2826. var message = APP.translation.generateTranslationHTML(
  2827. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2828. messageHandler.openDialog(
  2829. title,
  2830. message,
  2831. true, {},
  2832. function (event, value, message, formVals) {
  2833. return false;
  2834. }
  2835. );
  2836. });
  2837. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2838. messageHandler.openMessageDialog("dialog.sessTerminated",
  2839. "dialog.kickMessage");
  2840. });
  2841. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2842. //FIXME: use Session Terminated from translation, but
  2843. // 'reason' text comes from XMPP packet and is not translated
  2844. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2845. messageHandler.openDialog(
  2846. title, reason, true, {},
  2847. function (event, value, message, formVals) {
  2848. return false;
  2849. }
  2850. );
  2851. });
  2852. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2853. messageHandler.showError("dialog.error",
  2854. "dialog.bridgeUnavailable");
  2855. });
  2856. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2857. Avatar.setUserAvatar(from, id);
  2858. });
  2859. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2860. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2861. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2862. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2863. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2864. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2865. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2866. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2867. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2868. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2869. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2870. onAuthenticationRequired);
  2871. APP.xmpp.addListener(XMPPEvents.VIDEO_TYPE, onPeerVideoTypeChanged);
  2872. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2873. function (resource, devices) {
  2874. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2875. });
  2876. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  2877. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  2878. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function (doMuteAudio) {
  2879. UI.setAudioMuted(doMuteAudio);
  2880. });
  2881. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2882. onDtmfSupportChanged);
  2883. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  2884. SettingsMenu.setStartMuted(audio, video);
  2885. });
  2886. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  2887. UI.setInitialMuteFromFocus(audio, video);
  2888. });
  2889. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  2890. UI.messageHandler.showError("dialog.sorry",
  2891. "dialog.internalError");
  2892. });
  2893. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function () {
  2894. messageHandler.showError("dialog.error",
  2895. "dialog.SLDFailure");
  2896. });
  2897. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function () {
  2898. messageHandler.showError("dialog.error",
  2899. "dialog.SRDFailure");
  2900. });
  2901. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function () {
  2902. messageHandler.showError();
  2903. });
  2904. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function () {
  2905. // FIXME: re-use LoginDialog which supports retries
  2906. UI.showLoginPopup(connect);
  2907. });
  2908. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focusComponent, retrySec) {
  2909. UI.messageHandler.notify(
  2910. null, "notify.focus",
  2911. 'disconnected', "notify.focusFail",
  2912. {component: focusComponent, ms: retrySec});
  2913. });
  2914. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  2915. UI.messageHandler.openReportDialog(null,
  2916. "dialog.joinError", pres);
  2917. });
  2918. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  2919. UI.messageHandler.openReportDialog(null,
  2920. "dialog.connectError", pres);
  2921. });
  2922. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function () {
  2923. var roomName = UI.generateRoomName();
  2924. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  2925. });
  2926. //NicknameHandler emits this event
  2927. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  2928. APP.xmpp.addToPresence("displayName", nickname);
  2929. });
  2930. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  2931. AudioLevels.init();
  2932. });
  2933. if (!config.filmStripOnly) {
  2934. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2935. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2936. // Listens for video interruption events.
  2937. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  2938. // Listens for video restores events.
  2939. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  2940. }
  2941. }
  2942. /**
  2943. * Mutes/unmutes the local video.
  2944. *
  2945. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2946. * @param options an object which specifies optional arguments such as the
  2947. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2948. * specifies whether the method was initiated in response to a user command (in
  2949. * contrast to an automatic decision taken by the application logic)
  2950. */
  2951. function setVideoMute(mute, options) {
  2952. APP.RTC.setVideoMute(mute,
  2953. UI.setVideoMuteButtonsState,
  2954. options);
  2955. }
  2956. function onResize() {
  2957. Chat.resizeChat();
  2958. VideoLayout.resizeLargeVideoContainer();
  2959. }
  2960. function bindEvents() {
  2961. /**
  2962. * Resizes and repositions videos in full screen mode.
  2963. */
  2964. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  2965. onResize);
  2966. $(window).resize(onResize);
  2967. }
  2968. UI.start = function (init) {
  2969. document.title = interfaceConfig.APP_NAME;
  2970. var setupWelcomePage = null;
  2971. if(config.enableWelcomePage && window.location.pathname == "/" &&
  2972. (!window.localStorage.welcomePageDisabled ||
  2973. window.localStorage.welcomePageDisabled == "false")) {
  2974. $("#videoconference_page").hide();
  2975. if (!setupWelcomePage)
  2976. setupWelcomePage = require("./welcome_page/WelcomePage");
  2977. setupWelcomePage();
  2978. return;
  2979. }
  2980. $("#welcome_page").hide();
  2981. // Set the defaults for prompt dialogs.
  2982. $.prompt.setDefaults({persistent: false});
  2983. registerListeners();
  2984. VideoLayout.init(eventEmitter);
  2985. NicknameHandler.init(eventEmitter);
  2986. bindEvents();
  2987. setupPrezi();
  2988. if(!config.filmStripOnly) {
  2989. $("#videospace").mousemove(function () {
  2990. return ToolbarToggler.showToolbar();
  2991. });
  2992. setupToolbars();
  2993. setupChat();
  2994. // Display notice message at the top of the toolbar
  2995. if (config.noticeMessage) {
  2996. $('#noticeText').text(config.noticeMessage);
  2997. $('#notice').css({display: 'block'});
  2998. }
  2999. $("#downloadlog").click(function (event) {
  3000. dump(event.target);
  3001. });
  3002. }
  3003. else
  3004. {
  3005. $("#header").css("display", "none");
  3006. $("#bottomToolbar").css("display", "none");
  3007. $("#downloadlog").css("display", "none");
  3008. $("#remoteVideos").css("padding", "0px 0px 18px 0px");
  3009. $("#remoteVideos").css("right", "0px");
  3010. messageHandler.disableNotifications();
  3011. $('body').popover("disable");
  3012. // $("[data-toggle=popover]").popover("disable");
  3013. JitsiPopover.enabled = false;
  3014. }
  3015. document.title = interfaceConfig.APP_NAME;
  3016. if(config.requireDisplayName) {
  3017. var currentSettings = Settings.getSettings();
  3018. if (!currentSettings.displayName) {
  3019. promptDisplayName();
  3020. }
  3021. }
  3022. init();
  3023. if(!config.filmStripOnly) {
  3024. toastr.options = {
  3025. "closeButton": true,
  3026. "debug": false,
  3027. "positionClass": "notification-bottom-right",
  3028. "onclick": null,
  3029. "showDuration": "300",
  3030. "hideDuration": "1000",
  3031. "timeOut": "2000",
  3032. "extendedTimeOut": "1000",
  3033. "showEasing": "swing",
  3034. "hideEasing": "linear",
  3035. "showMethod": "fadeIn",
  3036. "hideMethod": "fadeOut",
  3037. "reposition": function () {
  3038. if (PanelToggler.isVisible()) {
  3039. $("#toast-container").addClass("notification-bottom-right-center");
  3040. } else {
  3041. $("#toast-container").removeClass("notification-bottom-right-center");
  3042. }
  3043. },
  3044. "newestOnTop": false
  3045. };
  3046. SettingsMenu.init();
  3047. }
  3048. };
  3049. function chatAddError(errorMessage, originalText) {
  3050. return Chat.chatAddError(errorMessage, originalText);
  3051. }
  3052. function chatSetSubject(text) {
  3053. return Chat.chatSetSubject(text);
  3054. }
  3055. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3056. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3057. }
  3058. function onMucJoined(jid, info) {
  3059. Toolbar.updateRoomUrl(window.location.href);
  3060. var meHTML = APP.translation.generateTranslationHTML("me");
  3061. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3062. var settings = Settings.getSettings();
  3063. // Make sure we configure our avatar id, before creating avatar for us
  3064. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3065. // Add myself to the contact list.
  3066. ContactList.addContact(jid);
  3067. // Once we've joined the muc show the toolbar
  3068. ToolbarToggler.showToolbar();
  3069. var displayName =
  3070. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3071. if (displayName)
  3072. onDisplayNameChanged('localVideoContainer', displayName);
  3073. VideoLayout.mucJoined();
  3074. }
  3075. function initEtherpad(name) {
  3076. Etherpad.init(name);
  3077. }
  3078. function onMucMemberLeft(jid) {
  3079. console.log('left.muc', jid);
  3080. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3081. '>.displayname').html();
  3082. messageHandler.notify(displayName,'notify.somebody',
  3083. 'disconnected',
  3084. 'notify.disconnected');
  3085. if (!config.startAudioMuted ||
  3086. config.startAudioMuted > APP.members.size()) {
  3087. UIUtil.playSoundNotification('userLeft');
  3088. }
  3089. ContactList.removeContact(jid);
  3090. VideoLayout.participantLeft(jid);
  3091. }
  3092. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3093. console.info("My role changed, new role: " + info.role);
  3094. onModeratorStatusChanged(isModerator);
  3095. VideoLayout.showModeratorIndicator();
  3096. SettingsMenu.onRoleChanged();
  3097. if (isModerator) {
  3098. Authentication.closeAuthenticationWindow();
  3099. messageHandler.notify(null, "notify.me",
  3100. 'connected', "notify.moderator");
  3101. }
  3102. }
  3103. function onModeratorStatusChanged(isModerator) {
  3104. Toolbar.showSipCallButton(isModerator);
  3105. Toolbar.showRecordingButton(
  3106. isModerator); //&&
  3107. // FIXME:
  3108. // Recording visible if
  3109. // there are at least 2(+ 1 focus) participants
  3110. //Object.keys(connection.emuc.members).length >= 3);
  3111. }
  3112. function onPasswordRequired(callback) {
  3113. // password is required
  3114. Toolbar.lockLockButton();
  3115. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3116. message += APP.translation.translateString(
  3117. "dialog.passwordRequired");
  3118. message += '</h2>' +
  3119. '<input name="lockKey" type="text" data-i18n=' +
  3120. '"[placeholder]dialog.password" placeholder="' +
  3121. APP.translation.translateString("dialog.password") +
  3122. '" autofocus>';
  3123. messageHandler.openTwoButtonDialog(null, null, null, message,
  3124. true,
  3125. "dialog.Ok",
  3126. function (e, v, m, f) {},
  3127. null,
  3128. function (e, v, m, f) {
  3129. if (v) {
  3130. var lockKey = f.lockKey;
  3131. if (lockKey) {
  3132. Toolbar.setSharedKey(lockKey);
  3133. callback(lockKey);
  3134. }
  3135. }
  3136. },
  3137. ':input:first'
  3138. );
  3139. }
  3140. /**
  3141. * The dialpad button is shown iff there is at least one member that supports
  3142. * DTMF (e.g. jigasi).
  3143. */
  3144. function onDtmfSupportChanged(dtmfSupport) {
  3145. //TODO: enable when the UI is ready
  3146. //Toolbar.showDialPadButton(dtmfSupport);
  3147. }
  3148. function onMucMemberJoined(jid, id, displayName) {
  3149. messageHandler.notify(displayName,'notify.somebody',
  3150. 'connected',
  3151. 'notify.connected');
  3152. if (!config.startAudioMuted ||
  3153. config.startAudioMuted > APP.members.size())
  3154. UIUtil.playSoundNotification('userJoined');
  3155. // Configure avatar
  3156. Avatar.setUserAvatar(jid, id);
  3157. // Add Peer's container
  3158. VideoLayout.ensurePeerContainerExists(jid);
  3159. }
  3160. function onMucPresenceStatus(jid, info) {
  3161. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3162. }
  3163. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3164. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3165. }
  3166. function onMucRoleChanged(role, displayName) {
  3167. VideoLayout.showModeratorIndicator();
  3168. if (role === 'moderator') {
  3169. var messageKey, messageOptions = {};
  3170. if (!displayName) {
  3171. messageKey = "notify.grantedToUnknown";
  3172. }
  3173. else {
  3174. messageKey = "notify.grantedTo";
  3175. messageOptions = {to: displayName};
  3176. }
  3177. messageHandler.notify(
  3178. displayName,'notify.somebody',
  3179. 'connected', messageKey,
  3180. messageOptions);
  3181. }
  3182. }
  3183. function onAuthenticationRequired(intervalCallback) {
  3184. Authentication.openAuthenticationDialog(
  3185. roomName, intervalCallback, function () {
  3186. Toolbar.authenticateClicked();
  3187. });
  3188. }
  3189. function onLastNChanged(oldValue, newValue) {
  3190. if (config.muteLocalVideoIfNotInLastN) {
  3191. setVideoMute(!newValue, { 'byUser': false });
  3192. }
  3193. }
  3194. UI.toggleSmileys = function () {
  3195. Chat.toggleSmileys();
  3196. };
  3197. UI.getSettings = function () {
  3198. return Settings.getSettings();
  3199. };
  3200. UI.toggleFilmStrip = function () {
  3201. return BottomToolbar.toggleFilmStrip();
  3202. };
  3203. UI.toggleChat = function () {
  3204. return BottomToolbar.toggleChat();
  3205. };
  3206. UI.toggleContactList = function () {
  3207. return BottomToolbar.toggleContactList();
  3208. };
  3209. UI.inputDisplayNameHandler = function (value) {
  3210. VideoLayout.inputDisplayNameHandler(value);
  3211. };
  3212. UI.getLargeVideoJid = function() {
  3213. return VideoLayout.getLargeVideoJid();
  3214. };
  3215. UI.generateRoomName = function() {
  3216. if(roomName)
  3217. return roomName;
  3218. var roomnode = null;
  3219. var path = window.location.pathname;
  3220. // determinde the room node from the url
  3221. // TODO: just the roomnode or the whole bare jid?
  3222. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3223. // custom function might be responsible for doing the pushstate
  3224. roomnode = config.getroomnode(path);
  3225. } else {
  3226. /* fall back to default strategy
  3227. * this is making assumptions about how the URL->room mapping happens.
  3228. * It currently assumes deployment at root, with a rewrite like the
  3229. * following one (for nginx):
  3230. location ~ ^/([a-zA-Z0-9]+)$ {
  3231. rewrite ^/(.*)$ / break;
  3232. }
  3233. */
  3234. if (path.length > 1) {
  3235. roomnode = path.substr(1).toLowerCase();
  3236. } else {
  3237. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3238. roomnode = word.toLowerCase();
  3239. window.history.pushState('VideoChat',
  3240. 'Room: ' + word, window.location.pathname + word);
  3241. }
  3242. }
  3243. roomName = roomnode + '@' + config.hosts.muc;
  3244. return roomName;
  3245. };
  3246. UI.connectionIndicatorShowMore = function(jid) {
  3247. return VideoLayout.showMore(jid);
  3248. };
  3249. UI.showLoginPopup = function(callback) {
  3250. console.log('password is required');
  3251. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3252. message += APP.translation.translateString(
  3253. "dialog.passwordRequired");
  3254. message += '</h2>' +
  3255. '<input name="username" type="text" ' +
  3256. 'placeholder="user@domain.net" autofocus>' +
  3257. '<input name="password" ' +
  3258. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3259. ' placeholder="user password">';
  3260. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3261. true,
  3262. "dialog.Ok",
  3263. function (e, v, m, f) {
  3264. if (v) {
  3265. if (f.username !== null && f.password != null) {
  3266. callback(f.username, f.password);
  3267. }
  3268. }
  3269. },
  3270. null, null, ':input:first'
  3271. );
  3272. };
  3273. UI.checkForNicknameAndJoin = function () {
  3274. Authentication.closeAuthenticationDialog();
  3275. Authentication.stopInterval();
  3276. var nick = null;
  3277. if (config.useNicks) {
  3278. nick = window.prompt('Your nickname (optional)');
  3279. }
  3280. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3281. };
  3282. function dump(elem, filename) {
  3283. elem = elem.parentNode;
  3284. elem.download = filename || 'meetlog.json';
  3285. elem.href = 'data:application/json;charset=utf-8,\n';
  3286. var data = APP.xmpp.getJingleLog();
  3287. var metadata = {};
  3288. metadata.time = new Date();
  3289. metadata.url = window.location.href;
  3290. metadata.ua = navigator.userAgent;
  3291. var log = APP.xmpp.getXmppLog();
  3292. if (log) {
  3293. metadata.xmpp = log;
  3294. }
  3295. data.metadata = metadata;
  3296. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3297. return false;
  3298. }
  3299. UI.getRoomName = function () {
  3300. return roomName;
  3301. };
  3302. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3303. if (muteAudio || muteVideo)
  3304. notifyForInitialMute();
  3305. if (muteAudio)
  3306. UI.setAudioMuted(true);
  3307. if (muteVideo)
  3308. UI.setVideoMute(true);
  3309. };
  3310. /**
  3311. * Mutes/unmutes the local video.
  3312. */
  3313. UI.toggleVideo = function () {
  3314. setVideoMute(!APP.RTC.localVideo.isMuted());
  3315. };
  3316. /**
  3317. * Mutes / unmutes audio for the local participant.
  3318. */
  3319. UI.toggleAudio = function() {
  3320. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3321. };
  3322. /**
  3323. * Sets muted audio state for the local participant.
  3324. */
  3325. UI.setAudioMuted = function (mute, earlyMute) {
  3326. var audioMute = null;
  3327. if (earlyMute)
  3328. audioMute = function (mute, cb) {
  3329. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3330. };
  3331. else
  3332. audioMute = function (mute, cb) {
  3333. return APP.xmpp.setAudioMute(mute, cb);
  3334. };
  3335. if (!audioMute(mute, function () {
  3336. VideoLayout.showLocalAudioIndicator(mute);
  3337. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3338. })) {
  3339. // We still click the button.
  3340. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3341. return;
  3342. }
  3343. };
  3344. UI.addListener = function (type, listener) {
  3345. eventEmitter.on(type, listener);
  3346. };
  3347. UI.clickOnVideo = function (videoNumber) {
  3348. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3349. if (remoteVideos.length > videoNumber) {
  3350. remoteVideos[videoNumber].click();
  3351. }
  3352. };
  3353. //Used by torture
  3354. UI.showToolbar = function () {
  3355. return ToolbarToggler.showToolbar();
  3356. };
  3357. //Used by torture
  3358. UI.dockToolbar = function (isDock) {
  3359. return ToolbarToggler.dockToolbar(isDock);
  3360. };
  3361. UI.setVideoMuteButtonsState = function (mute) {
  3362. var video = $('#video');
  3363. var communicativeClass = "icon-camera";
  3364. var muteClass = "icon-camera icon-camera-disabled";
  3365. if (mute) {
  3366. video.removeClass(communicativeClass);
  3367. video.addClass(muteClass);
  3368. } else {
  3369. video.removeClass(muteClass);
  3370. video.addClass(communicativeClass);
  3371. }
  3372. };
  3373. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3374. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3375. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3376. if(resourceJid === APP.xmpp.myResource())
  3377. SettingsMenu.changeAvatar(thumbUrl);
  3378. };
  3379. UI.setVideoMute = setVideoMute;
  3380. module.exports = UI;
  3381. },{"../../service/RTC/RTCEvents":104,"../../service/RTC/StreamEventTypes":106,"../../service/UI/UIEvents":107,"../../service/connectionquality/CQEvents":109,"../../service/desktopsharing/DesktopSharingEventTypes":110,"../../service/members/Events":111,"../../service/xmpp/XMPPEvents":113,"../RTC/RTCBrowserType":8,"./../settings/Settings":47,"./audio_levels/AudioLevels.js":12,"./authentication/Authentication":14,"./avatar/Avatar":16,"./etherpad/Etherpad.js":17,"./prezi/Prezi.js":18,"./side_pannels/SidePanelToggler":20,"./side_pannels/chat/Chat.js":21,"./side_pannels/contactlist/ContactList":25,"./side_pannels/settings/SettingsMenu":26,"./toolbars/BottomToolbar":27,"./toolbars/Toolbar":28,"./toolbars/ToolbarToggler":29,"./util/JitsiPopover":30,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":114}],12:[function(require,module,exports){
  3382. /* global APP, interfaceConfig, $, Strophe */
  3383. var CanvasUtil = require("./CanvasUtils");
  3384. var ASDrawContext = null;
  3385. function initActiveSpeakerAudioLevels() {
  3386. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3387. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3388. // Draw a circle.
  3389. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3390. // Add a shadow around the circle
  3391. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3392. ASDrawContext.shadowOffsetX = 0;
  3393. ASDrawContext.shadowOffsetY = 0;
  3394. }
  3395. /**
  3396. * The audio Levels plugin.
  3397. */
  3398. var AudioLevels = (function(my) {
  3399. var audioLevelCanvasCache = {};
  3400. my.LOCAL_LEVEL = 'local';
  3401. my.init = function () {
  3402. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3403. initActiveSpeakerAudioLevels();
  3404. };
  3405. /**
  3406. * Updates the audio level canvas for the given peerJid. If the canvas
  3407. * didn't exist we create it.
  3408. */
  3409. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3410. var resourceJid = null;
  3411. var videoSpanId = null;
  3412. if (!peerJid)
  3413. videoSpanId = 'localVideoContainer';
  3414. else {
  3415. resourceJid = Strophe.getResourceFromJid(peerJid);
  3416. videoSpanId = 'participant_' + resourceJid;
  3417. }
  3418. var videoSpan = document.getElementById(videoSpanId);
  3419. if (!videoSpan) {
  3420. if (resourceJid)
  3421. console.error("No video element for jid", resourceJid);
  3422. else
  3423. console.error("No video element for local video.");
  3424. return;
  3425. }
  3426. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3427. var videoSpaceWidth = $('#remoteVideos').width();
  3428. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3429. var thumbnailWidth = thumbnailSize[0];
  3430. var thumbnailHeight = thumbnailSize[1];
  3431. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3432. audioLevelCanvas = document.createElement('canvas');
  3433. audioLevelCanvas.className = "audiolevel";
  3434. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3435. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3436. resizeAudioLevelCanvas( audioLevelCanvas,
  3437. thumbnailWidth,
  3438. thumbnailHeight);
  3439. videoSpan.appendChild(audioLevelCanvas);
  3440. } else {
  3441. audioLevelCanvas = audioLevelCanvas.get(0);
  3442. resizeAudioLevelCanvas( audioLevelCanvas,
  3443. thumbnailWidth,
  3444. thumbnailHeight);
  3445. }
  3446. };
  3447. /**
  3448. * Updates the audio level UI for the given resourceJid.
  3449. *
  3450. * @param resourceJid the resource jid indicating the video element for
  3451. * which we draw the audio level
  3452. * @param audioLevel the newAudio level to render
  3453. */
  3454. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3455. drawAudioLevelCanvas(resourceJid, audioLevel);
  3456. var videoSpanId = getVideoSpanId(resourceJid);
  3457. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3458. if (!audioLevelCanvas)
  3459. return;
  3460. var drawContext = audioLevelCanvas.getContext('2d');
  3461. var canvasCache = audioLevelCanvasCache[resourceJid];
  3462. drawContext.clearRect (0, 0,
  3463. audioLevelCanvas.width, audioLevelCanvas.height);
  3464. drawContext.drawImage(canvasCache, 0, 0);
  3465. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3466. if(!APP.xmpp.myJid()) {
  3467. return;
  3468. }
  3469. resourceJid = APP.xmpp.myResource();
  3470. }
  3471. if(resourceJid === largeVideoResourceJid) {
  3472. window.requestAnimationFrame(function () {
  3473. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3474. });
  3475. }
  3476. };
  3477. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3478. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3479. return;
  3480. ASDrawContext.clearRect(0, 0, 300, 300);
  3481. if(audioLevel == 0)
  3482. return;
  3483. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3484. // Fill the shape.
  3485. ASDrawContext.fill();
  3486. };
  3487. /**
  3488. * Resizes the given audio level canvas to match the given thumbnail size.
  3489. */
  3490. function resizeAudioLevelCanvas(audioLevelCanvas,
  3491. thumbnailWidth,
  3492. thumbnailHeight) {
  3493. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3494. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3495. }
  3496. /**
  3497. * Draws the audio level canvas into the cached canvas object.
  3498. *
  3499. * @param resourceJid the resource jid indicating the video element for
  3500. * which we draw the audio level
  3501. * @param audioLevel the newAudio level to render
  3502. */
  3503. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3504. if (!audioLevelCanvasCache[resourceJid]) {
  3505. var videoSpanId = getVideoSpanId(resourceJid);
  3506. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3507. /*
  3508. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3509. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3510. * error. Since audio levels are frequently updated, the errors have
  3511. * been observed to pile into the console, strain the CPU.
  3512. */
  3513. if (audioLevelCanvasOrig) {
  3514. audioLevelCanvasCache[resourceJid] =
  3515. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3516. }
  3517. }
  3518. var canvas = audioLevelCanvasCache[resourceJid];
  3519. if (!canvas)
  3520. return;
  3521. var drawContext = canvas.getContext('2d');
  3522. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3523. var shadowLevel = getShadowLevel(audioLevel);
  3524. if (shadowLevel > 0) {
  3525. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3526. CanvasUtil.drawRoundRectGlow(drawContext,
  3527. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3528. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3529. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3530. interfaceConfig.CANVAS_RADIUS,
  3531. interfaceConfig.SHADOW_COLOR,
  3532. shadowLevel);
  3533. }
  3534. }
  3535. /**
  3536. * Returns the shadow/glow level for the given audio level.
  3537. *
  3538. * @param audioLevel the audio level from which we determine the shadow
  3539. * level
  3540. */
  3541. function getShadowLevel (audioLevel) {
  3542. var shadowLevel = 0;
  3543. if (audioLevel <= 0.3) {
  3544. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3545. }
  3546. else if (audioLevel <= 0.6) {
  3547. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3548. }
  3549. else {
  3550. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3551. }
  3552. return shadowLevel;
  3553. }
  3554. /**
  3555. * Returns the video span id corresponding to the given resourceJid or local
  3556. * user.
  3557. */
  3558. function getVideoSpanId(resourceJid) {
  3559. var videoSpanId = null;
  3560. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3561. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3562. videoSpanId = 'localVideoContainer';
  3563. else
  3564. videoSpanId = 'participant_' + resourceJid;
  3565. return videoSpanId;
  3566. }
  3567. /**
  3568. * Indicates that the remote video has been resized.
  3569. */
  3570. $(document).bind('remotevideo.resized', function (event, width, height) {
  3571. var resized = false;
  3572. $('#remoteVideos>span>canvas').each(function() {
  3573. var canvas = $(this).get(0);
  3574. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3575. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3576. resized = true;
  3577. }
  3578. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3579. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3580. resized = true;
  3581. }
  3582. });
  3583. if (resized)
  3584. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3585. audioLevelCanvasCache[resourceJid].width =
  3586. width + interfaceConfig.CANVAS_EXTRA;
  3587. audioLevelCanvasCache[resourceJid].height =
  3588. height + interfaceConfig.CANVAS_EXTRA;
  3589. });
  3590. });
  3591. return my;
  3592. })(AudioLevels || {});
  3593. module.exports = AudioLevels;
  3594. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3595. /**
  3596. * Utility class for drawing canvas shapes.
  3597. */
  3598. var CanvasUtil = (function(my) {
  3599. /**
  3600. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3601. * of the glow.
  3602. *
  3603. * @param drawContext the context of the canvas to draw to
  3604. * @param x the x coordinate of the round rectangle
  3605. * @param y the y coordinate of the round rectangle
  3606. * @param w the width of the round rectangle
  3607. * @param h the height of the round rectangle
  3608. * @param glowColor the color of the glow
  3609. * @param glowWidth the width of the glow
  3610. */
  3611. my.drawRoundRectGlow
  3612. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3613. // Save the previous state of the context.
  3614. drawContext.save();
  3615. if (w < 2 * r) r = w / 2;
  3616. if (h < 2 * r) r = h / 2;
  3617. // Draw a round rectangle.
  3618. drawContext.beginPath();
  3619. drawContext.moveTo(x+r, y);
  3620. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3621. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3622. drawContext.arcTo(x, y+h, x, y, r);
  3623. drawContext.arcTo(x, y, x+w, y, r);
  3624. drawContext.closePath();
  3625. // Add a shadow around the rectangle
  3626. drawContext.shadowColor = glowColor;
  3627. drawContext.shadowBlur = glowWidth;
  3628. drawContext.shadowOffsetX = 0;
  3629. drawContext.shadowOffsetY = 0;
  3630. // Fill the shape.
  3631. drawContext.fill();
  3632. drawContext.save();
  3633. drawContext.restore();
  3634. // 1) Uncomment this line to use Composite Operation, which is doing the
  3635. // same as the clip function below and is also antialiasing the round
  3636. // border, but is said to be less fast performance wise.
  3637. // drawContext.globalCompositeOperation='destination-out';
  3638. drawContext.beginPath();
  3639. drawContext.moveTo(x+r, y);
  3640. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3641. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3642. drawContext.arcTo(x, y+h, x, y, r);
  3643. drawContext.arcTo(x, y, x+w, y, r);
  3644. drawContext.closePath();
  3645. // 2) Uncomment this line to use Composite Operation, which is doing the
  3646. // same as the clip function below and is also antialiasing the round
  3647. // border, but is said to be less fast performance wise.
  3648. // drawContext.fill();
  3649. // Comment these two lines if choosing to do the same with composite
  3650. // operation above 1 and 2.
  3651. drawContext.clip();
  3652. drawContext.clearRect(0, 0, 277, 200);
  3653. // Restore the previous context state.
  3654. drawContext.restore();
  3655. };
  3656. /**
  3657. * Clones the given canvas.
  3658. *
  3659. * @return the new cloned canvas.
  3660. */
  3661. my.cloneCanvas = function (oldCanvas) {
  3662. /*
  3663. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3664. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3665. * levels are frequently updated, the errors have been observed to pile
  3666. * into the console, strain the CPU.
  3667. */
  3668. if (!oldCanvas)
  3669. return oldCanvas;
  3670. //create a new canvas
  3671. var newCanvas = document.createElement('canvas');
  3672. var context = newCanvas.getContext('2d');
  3673. //set dimensions
  3674. newCanvas.width = oldCanvas.width;
  3675. newCanvas.height = oldCanvas.height;
  3676. //apply the old canvas to the new one
  3677. context.drawImage(oldCanvas, 0, 0);
  3678. //return the new canvas
  3679. return newCanvas;
  3680. };
  3681. return my;
  3682. })(CanvasUtil || {});
  3683. module.exports = CanvasUtil;
  3684. },{}],14:[function(require,module,exports){
  3685. /* global $, APP*/
  3686. var LoginDialog = require('./LoginDialog');
  3687. var Moderator = require('../../xmpp/moderator');
  3688. /* Initial "authentication required" dialog */
  3689. var authDialog = null;
  3690. /* Loop retry ID that wits for other user to create the room */
  3691. var authRetryId = null;
  3692. var authenticationWindow = null;
  3693. var Authentication = {
  3694. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3695. // This is the loop that will wait for the room to be created by
  3696. // someone else. 'auth_required.moderator' will bring us back here.
  3697. authRetryId = window.setTimeout(intervalCallback, 5000);
  3698. // Show prompt only if it's not open
  3699. if (authDialog !== null) {
  3700. return;
  3701. }
  3702. // extract room name from 'room@muc.server.net'
  3703. var room = roomName.substr(0, roomName.indexOf('@'));
  3704. var title
  3705. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3706. var msg
  3707. = APP.translation.generateTranslationHTML(
  3708. "dialog.WaitForHostMsg", {room: room});
  3709. var buttonTxt
  3710. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3711. var buttons = [];
  3712. buttons.push({title: buttonTxt, value: "authNow"});
  3713. authDialog = APP.UI.messageHandler.openDialog(
  3714. title,
  3715. msg,
  3716. true,
  3717. buttons,
  3718. function (onSubmitEvent, submitValue) {
  3719. // Do not close the dialog yet
  3720. onSubmitEvent.preventDefault();
  3721. // Open login popup
  3722. if (submitValue === 'authNow') {
  3723. callback();
  3724. }
  3725. }
  3726. );
  3727. },
  3728. closeAuthenticationWindow: function () {
  3729. if (authenticationWindow) {
  3730. authenticationWindow.close();
  3731. authenticationWindow = null;
  3732. }
  3733. },
  3734. xmppAuthenticate: function () {
  3735. var loginDialog = LoginDialog.show(
  3736. function (connection, state) {
  3737. if (!state) {
  3738. // User cancelled
  3739. loginDialog.close();
  3740. return;
  3741. } else if (state == APP.xmpp.Status.CONNECTED) {
  3742. loginDialog.close();
  3743. Authentication.stopInterval();
  3744. Authentication.closeAuthenticationDialog();
  3745. // Close the connection as anonymous one will be used
  3746. // to create the conference. Session-id will authorize
  3747. // the request.
  3748. connection.disconnect();
  3749. var roomName = APP.UI.generateRoomName();
  3750. Moderator.allocateConferenceFocus(roomName, function () {
  3751. // If it's not "on the fly" authentication now join
  3752. // the conference room
  3753. if (!APP.xmpp.isMUCJoined()) {
  3754. APP.UI.checkForNicknameAndJoin();
  3755. }
  3756. });
  3757. }
  3758. }, true);
  3759. },
  3760. focusAuthenticationWindow: function () {
  3761. // If auth window exists just bring it to the front
  3762. if (authenticationWindow) {
  3763. authenticationWindow.focus();
  3764. return;
  3765. }
  3766. },
  3767. closeAuthenticationDialog: function () {
  3768. // Close authentication dialog if opened
  3769. if (authDialog) {
  3770. authDialog.close();
  3771. authDialog = null;
  3772. }
  3773. },
  3774. createAuthenticationWindow: function (callback, url) {
  3775. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3776. url, 910, 660,
  3777. // On closed
  3778. function () {
  3779. // Close authentication dialog if opened
  3780. Authentication.closeAuthenticationDialog();
  3781. callback();
  3782. authenticationWindow = null;
  3783. });
  3784. return authenticationWindow;
  3785. },
  3786. stopInterval: function () {
  3787. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3788. if (authRetryId) {
  3789. window.clearTimeout(authRetryId);
  3790. authRetryId = null;
  3791. }
  3792. }
  3793. };
  3794. module.exports = Authentication;
  3795. },{"../../xmpp/moderator":59,"./LoginDialog":15}],15:[function(require,module,exports){
  3796. /* global $, APP, config*/
  3797. var XMPP = require('../../xmpp/xmpp');
  3798. var Moderator = require('../../xmpp/moderator');
  3799. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3800. // anonymous domain is not enabled
  3801. /**
  3802. * Creates new <tt>Dialog</tt> instance.
  3803. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3804. * when we either fail to connect or succeed(check Strophe.Status).
  3805. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3806. * in order to create session-id after the connection is established.
  3807. * @constructor
  3808. */
  3809. function Dialog(callback, obtainSession) {
  3810. var self = this;
  3811. var stop = false;
  3812. var connection = APP.xmpp.createConnection();
  3813. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3814. message += APP.translation.translateString("dialog.passwordRequired");
  3815. message += '</h2>' +
  3816. '<input name="username" type="text" ' +
  3817. 'placeholder="user@domain.net" autofocus>' +
  3818. '<input name="password" ' +
  3819. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3820. ' placeholder="user password">';
  3821. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3822. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3823. var states = {
  3824. login: {
  3825. html: message,
  3826. buttons: [
  3827. { title: okButton, value: true},
  3828. { title: cancelButton, value: false}
  3829. ],
  3830. focus: ':input:first',
  3831. submit: function (e, v, m, f) {
  3832. e.preventDefault();
  3833. if (v) {
  3834. var jid = f.username;
  3835. var password = f.password;
  3836. if (jid && password) {
  3837. stop = false;
  3838. connection.reset();
  3839. connDialog.goToState('connecting');
  3840. connection.connect(jid, password, stateHandler);
  3841. }
  3842. } else {
  3843. // User cancelled
  3844. stop = true;
  3845. callback();
  3846. }
  3847. }
  3848. },
  3849. connecting: {
  3850. title: APP.translation.translateString('dialog.connecting'),
  3851. html: '<div id="connectionStatus"></div>',
  3852. buttons: [],
  3853. defaultButton: 0
  3854. },
  3855. finished: {
  3856. title: APP.translation.translateString('dialog.error'),
  3857. html: '<div id="errorMessage"></div>',
  3858. buttons: [
  3859. {
  3860. title: APP.translation.translateString('dialog.retry'),
  3861. value: 'retry'
  3862. },
  3863. {
  3864. title: APP.translation.translateString('dialog.Cancel'),
  3865. value: 'cancel'
  3866. },
  3867. ],
  3868. defaultButton: 0,
  3869. submit: function (e, v, m, f) {
  3870. e.preventDefault();
  3871. if (v === 'retry')
  3872. connDialog.goToState('login');
  3873. else
  3874. callback();
  3875. }
  3876. }
  3877. };
  3878. var connDialog
  3879. = APP.UI.messageHandler.openDialogWithStates(states,
  3880. { persistent: true, closeText: '' }, null);
  3881. var stateHandler = function (status, message) {
  3882. if (stop) {
  3883. return;
  3884. }
  3885. var translateKey = "connection." + XMPP.getStatusString(status);
  3886. var statusStr = APP.translation.translateString(translateKey);
  3887. // Display current state
  3888. var connectionStatus =
  3889. connDialog.getState('connecting').find('#connectionStatus');
  3890. connectionStatus.text(statusStr);
  3891. switch (status) {
  3892. case XMPP.Status.CONNECTED:
  3893. stop = true;
  3894. if (!obtainSession) {
  3895. callback(connection, status);
  3896. return;
  3897. }
  3898. // Obtaining session-id status
  3899. connectionStatus.text(
  3900. APP.translation.translateString(
  3901. 'connection.FETCH_SESSION_ID'));
  3902. // Authenticate with Jicofo and obtain session-id
  3903. var roomName = APP.UI.generateRoomName();
  3904. // Jicofo will return new session-id when connected
  3905. // from authenticated domain
  3906. connection.sendIQ(
  3907. Moderator.createConferenceIq(roomName),
  3908. function (result) {
  3909. connectionStatus.text(
  3910. APP.translation.translateString(
  3911. 'connection.GOT_SESSION_ID'));
  3912. stop = true;
  3913. // Parse session-id
  3914. Moderator.parseSessionId(result);
  3915. callback(connection, status);
  3916. },
  3917. function (error) {
  3918. console.error("Auth on the fly failed", error);
  3919. stop = true;
  3920. var errorMsg =
  3921. APP.translation.translateString(
  3922. 'connection.GET_SESSION_ID_ERROR') +
  3923. $(error).find('>error').attr('code');
  3924. self.displayError(errorMsg);
  3925. connection.disconnect();
  3926. });
  3927. break;
  3928. case XMPP.Status.AUTHFAIL:
  3929. case XMPP.Status.CONNFAIL:
  3930. case XMPP.Status.DISCONNECTED:
  3931. stop = true;
  3932. callback(connection, status);
  3933. var errorMessage = statusStr;
  3934. if (message)
  3935. {
  3936. errorMessage += ': ' + message;
  3937. }
  3938. self.displayError(errorMessage);
  3939. break;
  3940. default:
  3941. break;
  3942. }
  3943. };
  3944. /**
  3945. * Displays error message in 'finished' state which allows either to cancel
  3946. * or retry.
  3947. * @param message the final message to be displayed.
  3948. */
  3949. this.displayError = function (message) {
  3950. var finishedState = connDialog.getState('finished');
  3951. var errorMessageElem = finishedState.find('#errorMessage');
  3952. errorMessageElem.text(message);
  3953. connDialog.goToState('finished');
  3954. };
  3955. /**
  3956. * Closes LoginDialog.
  3957. */
  3958. this.close = function () {
  3959. stop = true;
  3960. connDialog.close();
  3961. };
  3962. }
  3963. var LoginDialog = {
  3964. /**
  3965. * Displays login prompt used to establish new XMPP connection. Given
  3966. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  3967. * called when we connect successfully(status === CONNECTED) or when we fail
  3968. * to do so. On connection failure program can call Dialog.close() method in
  3969. * order to cancel or do nothing to let the user retry.
  3970. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  3971. * called when we either fail to connect or succeed(check
  3972. * Strophe.Status).
  3973. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  3974. * Jicofo in order to create session-id after the connection is
  3975. * established.
  3976. * @returns {Dialog}
  3977. */
  3978. show: function (callback, obtainSession) {
  3979. return new Dialog(callback, obtainSession);
  3980. }
  3981. };
  3982. module.exports = LoginDialog;
  3983. },{"../../xmpp/moderator":59,"../../xmpp/xmpp":67}],16:[function(require,module,exports){
  3984. var Settings = require("../../settings/Settings");
  3985. var users = {};
  3986. var Avatar = {
  3987. /**
  3988. * Sets the user's avatar in the settings menu(if local user), contact list
  3989. * and thumbnail
  3990. * @param jid jid of the user
  3991. * @param id email or userID to be used as a hash
  3992. */
  3993. setUserAvatar: function (jid, id) {
  3994. if (id) {
  3995. if (users[jid] === id) {
  3996. return;
  3997. }
  3998. users[jid] = id;
  3999. }
  4000. var thumbUrl = this.getThumbUrl(jid);
  4001. var contactListUrl = this.getContactListUrl(jid);
  4002. var resourceJid = Strophe.getResourceFromJid(jid);
  4003. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4004. },
  4005. /**
  4006. * Returns image URL for the avatar to be displayed on large video area
  4007. * where current active speaker is presented.
  4008. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4009. */
  4010. getActiveSpeakerUrl: function (jid) {
  4011. return this.getGravatarUrl(jid, 100);
  4012. },
  4013. /**
  4014. * Returns image URL for the avatar to be displayed on small video thumbnail
  4015. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4016. */
  4017. getThumbUrl: function (jid) {
  4018. return this.getGravatarUrl(jid, 100);
  4019. },
  4020. /**
  4021. * Returns the URL for the avatar to be displayed as contactlist item
  4022. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4023. */
  4024. getContactListUrl: function (jid) {
  4025. return this.getGravatarUrl(jid, 30);
  4026. },
  4027. getGravatarUrl: function (jid, size) {
  4028. if (!jid) {
  4029. console.error("Get gravatar - jid is undefined");
  4030. return null;
  4031. }
  4032. var id = users[jid];
  4033. if (!id) {
  4034. console.warn(
  4035. "No avatar stored yet for " + jid + " - using JID as ID");
  4036. id = jid;
  4037. }
  4038. return 'https://www.gravatar.com/avatar/' +
  4039. MD5.hexdigest(id.trim().toLowerCase()) +
  4040. "?d=wavatar&size=" + (size || "30");
  4041. }
  4042. };
  4043. module.exports = Avatar;
  4044. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4045. /* global $, config,
  4046. setLargeVideoVisible, Util */
  4047. var VideoLayout = require("../videolayout/VideoLayout");
  4048. var Prezi = require("../prezi/Prezi");
  4049. var UIUtil = require("../util/UIUtil");
  4050. var etherpadName = null;
  4051. var etherpadIFrame = null;
  4052. var domain = null;
  4053. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4054. /**
  4055. * Resizes the etherpad.
  4056. */
  4057. function resize() {
  4058. if ($('#etherpad>iframe').length) {
  4059. var remoteVideos = $('#remoteVideos');
  4060. var availableHeight
  4061. = window.innerHeight - remoteVideos.outerHeight();
  4062. var availableWidth = UIUtil.getAvailableVideoWidth();
  4063. $('#etherpad>iframe').width(availableWidth);
  4064. $('#etherpad>iframe').height(availableHeight);
  4065. }
  4066. }
  4067. /**
  4068. * Creates the Etherpad button and adds it to the toolbar.
  4069. */
  4070. function enableEtherpadButton() {
  4071. if (!$('#etherpadButton').is(":visible"))
  4072. $('#etherpadButton').css({display: 'inline-block'});
  4073. }
  4074. /**
  4075. * Creates the IFrame for the etherpad.
  4076. */
  4077. function createIFrame() {
  4078. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4079. domain + etherpadName + options, function() {
  4080. document.domain = document.domain;
  4081. bubbleIframeMouseMove(etherpadIFrame);
  4082. setTimeout(function() {
  4083. // the iframes inside of the etherpad are
  4084. // not yet loaded when the etherpad iframe is loaded
  4085. var outer = etherpadIFrame.
  4086. contentDocument.getElementsByName("ace_outer")[0];
  4087. bubbleIframeMouseMove(outer);
  4088. var inner = outer.
  4089. contentDocument.getElementsByName("ace_inner")[0];
  4090. bubbleIframeMouseMove(inner);
  4091. }, 2000);
  4092. });
  4093. }
  4094. function bubbleIframeMouseMove(iframe){
  4095. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4096. iframe.contentWindow.onmousemove = function(e){
  4097. if(existingOnMouseMove) existingOnMouseMove(e);
  4098. var evt = document.createEvent("MouseEvents");
  4099. var boundingClientRect = iframe.getBoundingClientRect();
  4100. evt.initMouseEvent(
  4101. "mousemove",
  4102. true, // bubbles
  4103. false, // not cancelable
  4104. window,
  4105. e.detail,
  4106. e.screenX,
  4107. e.screenY,
  4108. e.clientX + boundingClientRect.left,
  4109. e.clientY + boundingClientRect.top,
  4110. e.ctrlKey,
  4111. e.altKey,
  4112. e.shiftKey,
  4113. e.metaKey,
  4114. e.button,
  4115. null // no related element
  4116. );
  4117. iframe.dispatchEvent(evt);
  4118. };
  4119. }
  4120. var Etherpad = {
  4121. /**
  4122. * Initializes the etherpad.
  4123. */
  4124. init: function (name) {
  4125. if (config.etherpad_base && !etherpadName && name) {
  4126. domain = config.etherpad_base;
  4127. etherpadName = name;
  4128. enableEtherpadButton();
  4129. /**
  4130. * Resizes the etherpad, when the window is resized.
  4131. */
  4132. $(window).resize(function () {
  4133. resize();
  4134. });
  4135. }
  4136. },
  4137. /**
  4138. * Opens/hides the Etherpad.
  4139. */
  4140. toggleEtherpad: function (isPresentation) {
  4141. if (!etherpadIFrame)
  4142. createIFrame();
  4143. if(VideoLayout.getLargeVideoState() === "etherpad")
  4144. {
  4145. VideoLayout.setLargeVideoState("video");
  4146. }
  4147. else
  4148. {
  4149. VideoLayout.setLargeVideoState("etherpad");
  4150. }
  4151. resize();
  4152. }
  4153. };
  4154. module.exports = Etherpad;
  4155. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4156. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4157. var UIUtil = require("../util/UIUtil");
  4158. var VideoLayout = require("../videolayout/VideoLayout");
  4159. var messageHandler = require("../util/MessageHandler");
  4160. var PreziPlayer = require("./PreziPlayer");
  4161. var preziPlayer = null;
  4162. /**
  4163. * Shows/hides a presentation.
  4164. */
  4165. function setPresentationVisible(visible) {
  4166. if (visible) {
  4167. VideoLayout.setLargeVideoState("prezi");
  4168. }
  4169. else {
  4170. VideoLayout.setLargeVideoState("video");
  4171. }
  4172. }
  4173. var Prezi = {
  4174. /**
  4175. * Reloads the current presentation.
  4176. */
  4177. reloadPresentation: function() {
  4178. var iframe = document.getElementById(preziPlayer.options.preziId);
  4179. iframe.src = iframe.src;
  4180. },
  4181. /**
  4182. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4183. * otherwise.
  4184. */
  4185. isPresentationVisible: function () {
  4186. return ($('#presentation>iframe') != null
  4187. && $('#presentation>iframe').css('opacity') == 1);
  4188. },
  4189. /**
  4190. * Opens the Prezi dialog, from which the user could choose a presentation
  4191. * to load.
  4192. */
  4193. openPreziDialog: function() {
  4194. var myprezi = APP.xmpp.getPrezi();
  4195. if (myprezi) {
  4196. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4197. null,
  4198. "dialog.removePreziMsg",
  4199. null,
  4200. false,
  4201. "dialog.Remove",
  4202. function(e,v,m,f) {
  4203. if(v) {
  4204. APP.xmpp.removePreziFromPresence();
  4205. }
  4206. }
  4207. );
  4208. }
  4209. else if (preziPlayer != null) {
  4210. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4211. null, "dialog.sharePreziMsg",
  4212. null,
  4213. false,
  4214. "dialog.Ok",
  4215. function(e,v,m,f) {
  4216. $.prompt.close();
  4217. }
  4218. );
  4219. }
  4220. else {
  4221. var html = APP.translation.generateTranslationHTML(
  4222. "dialog.sharePreziTitle");
  4223. var cancelButton = APP.translation.generateTranslationHTML(
  4224. "dialog.Cancel");
  4225. var shareButton = APP.translation.generateTranslationHTML(
  4226. "dialog.Share");
  4227. var backButton = APP.translation.generateTranslationHTML(
  4228. "dialog.Back");
  4229. var buttons = [];
  4230. var buttons1 = [];
  4231. // Cancel button to both states
  4232. buttons.push({title: cancelButton, value: false});
  4233. buttons1.push({title: cancelButton, value: false});
  4234. // Share button
  4235. buttons.push({title: shareButton, value: true});
  4236. // Back button
  4237. buttons1.push({title: backButton, value: true});
  4238. var linkError = APP.translation.generateTranslationHTML(
  4239. "dialog.preziLinkError");
  4240. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4241. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4242. var openPreziState = {
  4243. state0: {
  4244. html: '<h2>' + html + '</h2>' +
  4245. '<input name="preziUrl" type="text" ' +
  4246. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4247. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4248. '\' placeholder="' + defaultUrl + '" autofocus>',
  4249. persistent: false,
  4250. buttons: buttons,
  4251. focus: ':input:first',
  4252. defaultButton: 0,
  4253. submit: function (e, v, m, f) {
  4254. e.preventDefault();
  4255. if(v)
  4256. {
  4257. var preziUrl = f.preziUrl;
  4258. if (preziUrl)
  4259. {
  4260. var urlValue
  4261. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4262. if (urlValue.indexOf('http://prezi.com/') != 0
  4263. && urlValue.indexOf('https://prezi.com/') != 0)
  4264. {
  4265. $.prompt.goToState('state1');
  4266. return false;
  4267. }
  4268. else {
  4269. var presIdTmp = urlValue.substring(
  4270. urlValue.indexOf("prezi.com/") + 10);
  4271. if (!isAlphanumeric(presIdTmp)
  4272. || presIdTmp.indexOf('/') < 2) {
  4273. $.prompt.goToState('state1');
  4274. return false;
  4275. }
  4276. else {
  4277. APP.xmpp.addToPresence("prezi", urlValue);
  4278. $.prompt.close();
  4279. }
  4280. }
  4281. }
  4282. }
  4283. else
  4284. $.prompt.close();
  4285. }
  4286. },
  4287. state1: {
  4288. html: '<h2>' + html + '</h2>' +
  4289. linkError,
  4290. persistent: false,
  4291. buttons: buttons1,
  4292. focus: ':input:first',
  4293. defaultButton: 1,
  4294. submit: function (e, v, m, f) {
  4295. e.preventDefault();
  4296. if (v === 0)
  4297. $.prompt.close();
  4298. else
  4299. $.prompt.goToState('state0');
  4300. }
  4301. }
  4302. };
  4303. messageHandler.openDialogWithStates(openPreziState);
  4304. }
  4305. }
  4306. };
  4307. /**
  4308. * A new presentation has been added.
  4309. *
  4310. * @param event the event indicating the add of a presentation
  4311. * @param jid the jid from which the presentation was added
  4312. * @param presUrl url of the presentation
  4313. * @param currentSlide the current slide to which we should move
  4314. */
  4315. function presentationAdded(event, jid, presUrl, currentSlide) {
  4316. console.log("presentation added", presUrl);
  4317. var presId = getPresentationId(presUrl);
  4318. var elementId = 'participant_'
  4319. + Strophe.getResourceFromJid(jid)
  4320. + '_' + presId;
  4321. VideoLayout.addPreziContainer(elementId);
  4322. var controlsEnabled = false;
  4323. if (jid === APP.xmpp.myJid())
  4324. controlsEnabled = true;
  4325. setPresentationVisible(true);
  4326. VideoLayout.setLargeVideoHover(
  4327. function (event) {
  4328. if (Prezi.isPresentationVisible()) {
  4329. var reloadButtonRight = window.innerWidth
  4330. - $('#presentation>iframe').offset().left
  4331. - $('#presentation>iframe').width();
  4332. $('#reloadPresentation').css({ right: reloadButtonRight,
  4333. display:'inline-block'});
  4334. }
  4335. },
  4336. function (event) {
  4337. if (!Prezi.isPresentationVisible())
  4338. $('#reloadPresentation').css({display:'none'});
  4339. else {
  4340. var e = event.toElement || event.relatedTarget;
  4341. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4342. $('#reloadPresentation').css({display:'none'});
  4343. }
  4344. });
  4345. preziPlayer = new PreziPlayer(
  4346. 'presentation',
  4347. {preziId: presId,
  4348. width: getPresentationWidth(),
  4349. height: getPresentationHeihgt(),
  4350. controls: controlsEnabled,
  4351. debug: true
  4352. });
  4353. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4354. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4355. console.log("prezi status", event.value);
  4356. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4357. if (jid != APP.xmpp.myJid())
  4358. preziPlayer.flyToStep(currentSlide);
  4359. }
  4360. });
  4361. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4362. console.log("event value", event.value);
  4363. APP.xmpp.addToPresence("preziSlide", event.value);
  4364. });
  4365. $("#" + elementId).css( 'background-image',
  4366. 'url(../images/avatarprezi.png)');
  4367. $("#" + elementId).click(
  4368. function () {
  4369. setPresentationVisible(true);
  4370. }
  4371. );
  4372. };
  4373. /**
  4374. * A presentation has been removed.
  4375. *
  4376. * @param event the event indicating the remove of a presentation
  4377. * @param jid the jid for which the presentation was removed
  4378. * @param the url of the presentation
  4379. */
  4380. function presentationRemoved(event, jid, presUrl) {
  4381. console.log('presentation removed', presUrl);
  4382. var presId = getPresentationId(presUrl);
  4383. setPresentationVisible(false);
  4384. $('#participant_'
  4385. + Strophe.getResourceFromJid(jid)
  4386. + '_' + presId).remove();
  4387. $('#presentation>iframe').remove();
  4388. if (preziPlayer != null) {
  4389. preziPlayer.destroy();
  4390. preziPlayer = null;
  4391. }
  4392. };
  4393. /**
  4394. * Indicates if the given string is an alphanumeric string.
  4395. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4396. * purpose of checking URIs.
  4397. */
  4398. function isAlphanumeric(unsafeText) {
  4399. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4400. return regex.test(unsafeText);
  4401. }
  4402. /**
  4403. * Returns the presentation id from the given url.
  4404. */
  4405. function getPresentationId (presUrl) {
  4406. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4407. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4408. }
  4409. /**
  4410. * Returns the presentation width.
  4411. */
  4412. function getPresentationWidth() {
  4413. var availableWidth = UIUtil.getAvailableVideoWidth();
  4414. var availableHeight = getPresentationHeihgt();
  4415. var aspectRatio = 16.0 / 9.0;
  4416. if (availableHeight < availableWidth / aspectRatio) {
  4417. availableWidth = Math.floor(availableHeight * aspectRatio);
  4418. }
  4419. return availableWidth;
  4420. }
  4421. /**
  4422. * Returns the presentation height.
  4423. */
  4424. function getPresentationHeihgt() {
  4425. var remoteVideos = $('#remoteVideos');
  4426. return window.innerHeight - remoteVideos.outerHeight();
  4427. }
  4428. /**
  4429. * Resizes the presentation iframe.
  4430. */
  4431. function resize() {
  4432. if ($('#presentation>iframe')) {
  4433. $('#presentation>iframe').width(getPresentationWidth());
  4434. $('#presentation>iframe').height(getPresentationHeihgt());
  4435. }
  4436. }
  4437. /**
  4438. * Presentation has been removed.
  4439. */
  4440. $(document).bind('presentationremoved.muc', presentationRemoved);
  4441. /**
  4442. * Presentation has been added.
  4443. */
  4444. $(document).bind('presentationadded.muc', presentationAdded);
  4445. /*
  4446. * Indicates presentation slide change.
  4447. */
  4448. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4449. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4450. preziPlayer.flyToStep(current);
  4451. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4452. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4453. preziPlayer.flyToStep(current, i);
  4454. }
  4455. }
  4456. });
  4457. $(window).resize(function () {
  4458. resize();
  4459. });
  4460. module.exports = Prezi;
  4461. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4462. (function() {
  4463. "use strict";
  4464. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4465. window.PreziPlayer = (function() {
  4466. PreziPlayer.API_VERSION = 1;
  4467. PreziPlayer.CURRENT_STEP = 'currentStep';
  4468. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4469. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4470. PreziPlayer.STATUS_LOADING = 'loading';
  4471. PreziPlayer.STATUS_READY = 'ready';
  4472. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4473. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4474. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4475. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4476. PreziPlayer.EVENT_STATUS = "statusChange";
  4477. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4478. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4479. PreziPlayer.domain = "https://prezi.com";
  4480. PreziPlayer.path = "/player/";
  4481. PreziPlayer.players = {};
  4482. PreziPlayer.binded_methods = ['changesHandler'];
  4483. PreziPlayer.createMultiplePlayers = function(optionArray){
  4484. for(var i=0; i<optionArray.length; i++) {
  4485. var optionSet = optionArray[i];
  4486. new PreziPlayer(optionSet.id, optionSet);
  4487. };
  4488. };
  4489. PreziPlayer.messageReceived = function(event){
  4490. var message, item, player;
  4491. try {
  4492. message = JSON.parse(event.data);
  4493. if (message.id && (player = PreziPlayer.players[message.id])) {
  4494. if (player.options.debug === true) {
  4495. if (console && console.log)
  4496. console.log('received', message);
  4497. }
  4498. if (message.type === "changes") {
  4499. player.changesHandler(message);
  4500. }
  4501. for (var i = 0; i < player.callbacks.length; i++) {
  4502. item = player.callbacks[i];
  4503. if (item && message.type === item.event) {
  4504. item.callback(message);
  4505. }
  4506. }
  4507. }
  4508. } catch (e) { }
  4509. };
  4510. function PreziPlayer(id, options) {
  4511. var params, paramString = "", _this = this;
  4512. if (PreziPlayer.players[id]){
  4513. PreziPlayer.players[id].destroy();
  4514. }
  4515. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4516. var method_name = PreziPlayer.binded_methods[i];
  4517. _this[method_name] = __bind(_this[method_name], _this);
  4518. };
  4519. options = options || {};
  4520. this.options = options;
  4521. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4522. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4523. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4524. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4525. this.callbacks = [];
  4526. this.id = id;
  4527. this.embedTo = document.getElementById(id);
  4528. if (!this.embedTo) {
  4529. throw "The element id is not available.";
  4530. }
  4531. this.iframe = document.createElement('iframe');
  4532. params = [
  4533. { name: 'oid', value: options.preziId },
  4534. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4535. { name: 'controls', value: options.controls ? 1 : 0 }
  4536. ];
  4537. for(var i=0; i<params.length; i++) {
  4538. var param = params[i];
  4539. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4540. };
  4541. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4542. this.iframe.frameBorder = 0;
  4543. this.iframe.scrolling = "no";
  4544. this.iframe.width = options.width || 640;
  4545. this.iframe.height = options.height || 480;
  4546. this.embedTo.innerHTML = '';
  4547. // JITSI: IN CASE SOMETHING GOES WRONG.
  4548. try {
  4549. this.embedTo.appendChild(this.iframe);
  4550. }
  4551. catch (err) {
  4552. console.log("CATCH ERROR");
  4553. }
  4554. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4555. // crashes for us.
  4556. this.initPollInterval = setInterval(function(){
  4557. _this.sendMessage({'action': 'init'});
  4558. }, 500);
  4559. PreziPlayer.players[id] = this;
  4560. }
  4561. PreziPlayer.prototype.changesHandler = function(message) {
  4562. var key, value, j, item;
  4563. if (this.initPollInterval) {
  4564. clearInterval(this.initPollInterval);
  4565. this.initPollInterval = false;
  4566. }
  4567. for (key in message.data) {
  4568. if (message.data.hasOwnProperty(key)){
  4569. value = message.data[key];
  4570. this.values[key] = value;
  4571. for (j=0; j<this.callbacks.length; j++) {
  4572. item = this.callbacks[j];
  4573. if (item && item.event === key + "Change"){
  4574. item.callback({type: item.event, value: value});
  4575. }
  4576. }
  4577. }
  4578. }
  4579. };
  4580. PreziPlayer.prototype.destroy = function() {
  4581. if (this.initPollInterval) {
  4582. clearInterval(this.initPollInterval);
  4583. this.initPollInterval = false;
  4584. }
  4585. this.embedTo.innerHTML = '';
  4586. };
  4587. PreziPlayer.prototype.sendMessage = function(message) {
  4588. if (this.options.debug === true) {
  4589. if (console && console.log) console.log('sent', message);
  4590. }
  4591. message.version = PreziPlayer.API_VERSION;
  4592. message.id = this.id;
  4593. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4594. };
  4595. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4596. PreziPlayer.prototype.flyToNextStep = function() {
  4597. return this.sendMessage({
  4598. 'action': 'present',
  4599. 'data': ['moveToNextStep']
  4600. });
  4601. };
  4602. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4603. PreziPlayer.prototype.flyToPreviousStep = function() {
  4604. return this.sendMessage({
  4605. 'action': 'present',
  4606. 'data': ['moveToPrevStep']
  4607. });
  4608. };
  4609. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4610. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4611. var obj = this;
  4612. // check animation_step
  4613. if (animation_step > 0 &&
  4614. obj.values.animationCountOnSteps &&
  4615. obj.values.animationCountOnSteps[step] <= animation_step) {
  4616. animation_step = obj.values.animationCountOnSteps[step];
  4617. }
  4618. // jump to animation steps by calling flyToNextStep()
  4619. function doAnimationSteps() {
  4620. if (obj.values.isMoving == true) {
  4621. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4622. return;
  4623. }
  4624. while (animation_step-- > 0) {
  4625. obj.flyToNextStep(); // do the animation steps
  4626. }
  4627. }
  4628. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4629. // jump to the step
  4630. return this.sendMessage({
  4631. 'action': 'present',
  4632. 'data': ['moveToStep', step]
  4633. });
  4634. };
  4635. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4636. PreziPlayer.prototype.flyToObject = function(objectId) {
  4637. return this.sendMessage({
  4638. 'action': 'present',
  4639. 'data': ['moveToObject', objectId]
  4640. });
  4641. };
  4642. PreziPlayer.prototype.play = function(defaultDelay) {
  4643. return this.sendMessage({
  4644. 'action': 'present',
  4645. 'data': ['startAutoPlay', defaultDelay]
  4646. });
  4647. };
  4648. PreziPlayer.prototype.stop = function() {
  4649. return this.sendMessage({
  4650. 'action': 'present',
  4651. 'data': ['stopAutoPlay']
  4652. });
  4653. };
  4654. PreziPlayer.prototype.pause = function(defaultDelay) {
  4655. return this.sendMessage({
  4656. 'action': 'present',
  4657. 'data': ['pauseAutoPlay', defaultDelay]
  4658. });
  4659. };
  4660. PreziPlayer.prototype.getCurrentStep = function() {
  4661. return this.values.currentStep;
  4662. };
  4663. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4664. return this.values.currentAnimationStep;
  4665. };
  4666. PreziPlayer.prototype.getCurrentObject = function() {
  4667. return this.values.currentObject;
  4668. };
  4669. PreziPlayer.prototype.getStatus = function() {
  4670. return this.values.status;
  4671. };
  4672. PreziPlayer.prototype.isPlaying = function() {
  4673. return this.values.isAutoPlaying;
  4674. };
  4675. PreziPlayer.prototype.getStepCount = function() {
  4676. return this.values.stepCount;
  4677. };
  4678. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4679. return this.values.animationCountOnSteps;
  4680. };
  4681. PreziPlayer.prototype.getTitle = function() {
  4682. return this.values.title;
  4683. };
  4684. PreziPlayer.prototype.setDimensions = function(dims) {
  4685. for (var parameter in dims) {
  4686. this.iframe[parameter] = dims[parameter];
  4687. }
  4688. }
  4689. PreziPlayer.prototype.getDimensions = function() {
  4690. return {
  4691. width: parseInt(this.iframe.width, 10),
  4692. height: parseInt(this.iframe.height, 10)
  4693. }
  4694. }
  4695. PreziPlayer.prototype.on = function(event, callback) {
  4696. this.callbacks.push({
  4697. event: event,
  4698. callback: callback
  4699. });
  4700. };
  4701. PreziPlayer.prototype.off = function(event, callback) {
  4702. var j, item;
  4703. if (event === undefined) {
  4704. this.callbacks = [];
  4705. }
  4706. j = this.callbacks.length;
  4707. while (j--) {
  4708. item = this.callbacks[j];
  4709. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4710. this.callbacks.splice(j, 1);
  4711. }
  4712. }
  4713. };
  4714. if (window.addEventListener) {
  4715. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4716. } else {
  4717. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4718. }
  4719. return PreziPlayer;
  4720. })();
  4721. })();
  4722. module.exports = PreziPlayer;
  4723. },{}],20:[function(require,module,exports){
  4724. /* global require, $ */
  4725. var Chat = require("./chat/Chat");
  4726. var ContactList = require("./contactlist/ContactList");
  4727. var Settings = require("./../../settings/Settings");
  4728. var SettingsMenu = require("./settings/SettingsMenu");
  4729. var VideoLayout = require("../videolayout/VideoLayout");
  4730. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4731. var UIUtil = require("../util/UIUtil");
  4732. var LargeVideo = require("../videolayout/LargeVideo");
  4733. /**
  4734. * Toggler for the chat, contact list, settings menu, etc..
  4735. */
  4736. var PanelToggler = (function(my) {
  4737. var currentlyOpen = null;
  4738. var buttons = {
  4739. '#chatspace': '#chatBottomButton',
  4740. '#contactlist': '#contactListButton',
  4741. '#settingsmenu': '#settingsButton'
  4742. };
  4743. /**
  4744. * Toggles the windows in the side panel
  4745. * @param object the window that should be shown
  4746. * @param selector the selector for the element containing the panel
  4747. * @param onOpenComplete function to be called when the panel is opened
  4748. * @param onOpen function to be called if the window is going to be opened
  4749. * @param onClose function to be called if the window is going to be closed
  4750. */
  4751. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4752. UIUtil.buttonClick(buttons[selector], "active");
  4753. if (object.isVisible()) {
  4754. $("#toast-container").animate({
  4755. right: '5px'
  4756. },
  4757. {
  4758. queue: false,
  4759. duration: 500
  4760. });
  4761. $(selector).hide("slide", {
  4762. direction: "right",
  4763. queue: false,
  4764. duration: 500
  4765. });
  4766. if(typeof onClose === "function") {
  4767. onClose();
  4768. }
  4769. currentlyOpen = null;
  4770. }
  4771. else {
  4772. // Undock the toolbar when the chat is shown and if we're in a
  4773. // video mode.
  4774. if (LargeVideo.isLargeVideoVisible()) {
  4775. ToolbarToggler.dockToolbar(false);
  4776. }
  4777. if(currentlyOpen) {
  4778. var current = $(currentlyOpen);
  4779. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4780. current.css('z-index', 4);
  4781. setTimeout(function () {
  4782. current.css('display', 'none');
  4783. current.css('z-index', 5);
  4784. }, 500);
  4785. }
  4786. $("#toast-container").animate({
  4787. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4788. },
  4789. {
  4790. queue: false,
  4791. duration: 500
  4792. });
  4793. $(selector).show("slide", {
  4794. direction: "right",
  4795. queue: false,
  4796. duration: 500,
  4797. complete: onOpenComplete
  4798. });
  4799. if(typeof onOpen === "function") {
  4800. onOpen();
  4801. }
  4802. currentlyOpen = selector;
  4803. }
  4804. };
  4805. /**
  4806. * Opens / closes the chat area.
  4807. */
  4808. my.toggleChat = function() {
  4809. var chatCompleteFunction = Chat.isVisible() ?
  4810. function() {} : function () {
  4811. Chat.scrollChatToBottom();
  4812. $('#chatspace').trigger('shown');
  4813. };
  4814. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4815. toggle(Chat,
  4816. '#chatspace',
  4817. function () {
  4818. // Request the focus in the nickname field or the chat input field.
  4819. if ($('#nickname').css('visibility') === 'visible') {
  4820. $('#nickinput').focus();
  4821. } else {
  4822. $('#usermsg').focus();
  4823. }
  4824. },
  4825. null,
  4826. Chat.resizeChat,
  4827. null);
  4828. };
  4829. /**
  4830. * Opens / closes the contact list area.
  4831. */
  4832. my.toggleContactList = function () {
  4833. var completeFunction = ContactList.isVisible() ?
  4834. function() {} : function () { $('#contactlist').trigger('shown');};
  4835. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4836. toggle(ContactList,
  4837. '#contactlist',
  4838. null,
  4839. function() {
  4840. ContactList.setVisualNotification(false);
  4841. },
  4842. null);
  4843. };
  4844. /**
  4845. * Opens / closes the settings menu
  4846. */
  4847. my.toggleSettingsMenu = function() {
  4848. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4849. toggle(SettingsMenu,
  4850. '#settingsmenu',
  4851. null,
  4852. function() {
  4853. var settings = Settings.getSettings();
  4854. $('#setDisplayName').get(0).value = settings.displayName;
  4855. $('#setEmail').get(0).value = settings.email;
  4856. },
  4857. null);
  4858. };
  4859. /**
  4860. * Returns the size of the side panel.
  4861. */
  4862. my.getPanelSize = function () {
  4863. var availableHeight = window.innerHeight;
  4864. var availableWidth = window.innerWidth;
  4865. var panelWidth = 200;
  4866. if (availableWidth * 0.2 < 200) {
  4867. panelWidth = availableWidth * 0.2;
  4868. }
  4869. return [panelWidth, availableHeight];
  4870. };
  4871. my.isVisible = function() {
  4872. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4873. };
  4874. return my;
  4875. }(PanelToggler || {}));
  4876. module.exports = PanelToggler;
  4877. },{"../toolbars/ToolbarToggler":29,"../util/UIUtil":33,"../videolayout/LargeVideo":35,"../videolayout/VideoLayout":39,"./../../settings/Settings":47,"./chat/Chat":21,"./contactlist/ContactList":25,"./settings/SettingsMenu":26}],21:[function(require,module,exports){
  4878. /* global APP, $, Util, nickname:true */
  4879. var Replacement = require("./Replacement");
  4880. var CommandsProcessor = require("./Commands");
  4881. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4882. var smileys = require("./smileys.json").smileys;
  4883. var NicknameHandler = require("../../util/NicknameHandler");
  4884. var UIUtil = require("../../util/UIUtil");
  4885. var UIEvents = require("../../../../service/UI/UIEvents");
  4886. var notificationInterval = false;
  4887. var unreadMessages = 0;
  4888. /**
  4889. * Shows/hides a visual notification, indicating that a message has arrived.
  4890. */
  4891. function setVisualNotification(show) {
  4892. var unreadMsgElement = document.getElementById('unreadMessages');
  4893. var unreadMsgBottomElement
  4894. = document.getElementById('bottomUnreadMessages');
  4895. var glower = $('#chatButton');
  4896. var bottomGlower = $('#chatBottomButton');
  4897. if (unreadMessages) {
  4898. unreadMsgElement.innerHTML = unreadMessages.toString();
  4899. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4900. ToolbarToggler.dockToolbar(true);
  4901. var chatButtonElement
  4902. = document.getElementById('chatButton').parentNode;
  4903. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4904. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4905. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4906. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4907. unreadMsgElement.setAttribute(
  4908. 'style',
  4909. 'top:' + topIndent +
  4910. '; left:' + leftIndent + ';');
  4911. var chatBottomButtonElement
  4912. = document.getElementById('chatBottomButton').parentNode;
  4913. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4914. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4915. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4916. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  4917. unreadMsgBottomElement.setAttribute(
  4918. 'style',
  4919. 'top:' + bottomTopIndent +
  4920. '; left:' + bottomLeftIndent + ';');
  4921. if (!glower.hasClass('icon-chat-simple')) {
  4922. glower.removeClass('icon-chat');
  4923. glower.addClass('icon-chat-simple');
  4924. }
  4925. }
  4926. else {
  4927. unreadMsgElement.innerHTML = '';
  4928. unreadMsgBottomElement.innerHTML = '';
  4929. glower.removeClass('icon-chat-simple');
  4930. glower.addClass('icon-chat');
  4931. }
  4932. if (show && !notificationInterval) {
  4933. notificationInterval = window.setInterval(function () {
  4934. glower.toggleClass('active');
  4935. bottomGlower.toggleClass('active glowing');
  4936. }, 800);
  4937. }
  4938. else if (!show && notificationInterval) {
  4939. window.clearInterval(notificationInterval);
  4940. notificationInterval = false;
  4941. glower.removeClass('active');
  4942. bottomGlower.removeClass('glowing');
  4943. bottomGlower.addClass('active');
  4944. }
  4945. }
  4946. /**
  4947. * Returns the current time in the format it is shown to the user
  4948. * @returns {string}
  4949. */
  4950. function getCurrentTime(stamp) {
  4951. var now = (stamp? new Date(stamp): new Date());
  4952. var hour = now.getHours();
  4953. var minute = now.getMinutes();
  4954. var second = now.getSeconds();
  4955. if(hour.toString().length === 1) {
  4956. hour = '0'+hour;
  4957. }
  4958. if(minute.toString().length === 1) {
  4959. minute = '0'+minute;
  4960. }
  4961. if(second.toString().length === 1) {
  4962. second = '0'+second;
  4963. }
  4964. return hour+':'+minute+':'+second;
  4965. }
  4966. function toggleSmileys() {
  4967. var smileys = $('#smileysContainer');
  4968. if(!smileys.is(':visible')) {
  4969. smileys.show("slide", { direction: "down", duration: 300});
  4970. } else {
  4971. smileys.hide("slide", { direction: "down", duration: 300});
  4972. }
  4973. $('#usermsg').focus();
  4974. }
  4975. function addClickFunction(smiley, number) {
  4976. smiley.onclick = function addSmileyToMessage() {
  4977. var usermsg = $('#usermsg');
  4978. var message = usermsg.val();
  4979. message += smileys['smiley' + number];
  4980. usermsg.val(message);
  4981. usermsg.get(0).setSelectionRange(message.length, message.length);
  4982. toggleSmileys();
  4983. usermsg.focus();
  4984. };
  4985. }
  4986. /**
  4987. * Adds the smileys container to the chat
  4988. */
  4989. function addSmileys() {
  4990. var smileysContainer = document.createElement('div');
  4991. smileysContainer.id = 'smileysContainer';
  4992. for(var i = 1; i <= 21; i++) {
  4993. var smileyContainer = document.createElement('div');
  4994. smileyContainer.id = 'smiley' + i;
  4995. smileyContainer.className = 'smileyContainer';
  4996. var smiley = document.createElement('img');
  4997. smiley.src = 'images/smileys/smiley' + i + '.svg';
  4998. smiley.className = 'smiley';
  4999. addClickFunction(smiley, i);
  5000. smileyContainer.appendChild(smiley);
  5001. smileysContainer.appendChild(smileyContainer);
  5002. }
  5003. $("#chatspace").append(smileysContainer);
  5004. }
  5005. /**
  5006. * Resizes the chat conversation.
  5007. */
  5008. function resizeChatConversation() {
  5009. var msgareaHeight = $('#usermsg').outerHeight();
  5010. var chatspace = $('#chatspace');
  5011. var width = chatspace.width();
  5012. var chat = $('#chatconversation');
  5013. var smileys = $('#smileysarea');
  5014. smileys.height(msgareaHeight);
  5015. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5016. $('#smileysContainer').css('bottom', msgareaHeight);
  5017. chat.width(width - 10);
  5018. chat.height(window.innerHeight - 15 - msgareaHeight);
  5019. }
  5020. /**
  5021. * Chat related user interface.
  5022. */
  5023. var Chat = (function (my) {
  5024. /**
  5025. * Initializes chat related interface.
  5026. */
  5027. my.init = function () {
  5028. if(NicknameHandler.getNickname())
  5029. Chat.setChatConversationMode(true);
  5030. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5031. function (nickname) {
  5032. Chat.setChatConversationMode(true);
  5033. });
  5034. $('#nickinput').keydown(function (event) {
  5035. if (event.keyCode === 13) {
  5036. event.preventDefault();
  5037. var val = UIUtil.escapeHtml(this.value);
  5038. this.value = '';
  5039. if (!NicknameHandler.getNickname()) {
  5040. NicknameHandler.setNickname(val);
  5041. return;
  5042. }
  5043. }
  5044. });
  5045. var usermsg = $('#usermsg');
  5046. usermsg.keydown(function (event) {
  5047. if (event.keyCode === 13) {
  5048. event.preventDefault();
  5049. var value = this.value;
  5050. usermsg.val('').trigger('autosize.resize');
  5051. this.focus();
  5052. var command = new CommandsProcessor(value);
  5053. if(command.isCommand()) {
  5054. command.processCommand();
  5055. }
  5056. else {
  5057. var message = UIUtil.escapeHtml(value);
  5058. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5059. }
  5060. }
  5061. });
  5062. var onTextAreaResize = function () {
  5063. resizeChatConversation();
  5064. Chat.scrollChatToBottom();
  5065. };
  5066. usermsg.autosize({callback: onTextAreaResize});
  5067. $("#chatspace").bind("shown",
  5068. function () {
  5069. unreadMessages = 0;
  5070. setVisualNotification(false);
  5071. });
  5072. addSmileys();
  5073. };
  5074. /**
  5075. * Appends the given message to the chat conversation.
  5076. */
  5077. my.updateChatConversation =
  5078. function (from, displayName, message, myjid, stamp) {
  5079. var divClassName = '';
  5080. if (APP.xmpp.myJid() === from) {
  5081. divClassName = "localuser";
  5082. }
  5083. else {
  5084. divClassName = "remoteuser";
  5085. if (!Chat.isVisible()) {
  5086. unreadMessages++;
  5087. UIUtil.playSoundNotification('chatNotification');
  5088. setVisualNotification(true);
  5089. }
  5090. }
  5091. // replace links and smileys
  5092. // Strophe already escapes special symbols on sending,
  5093. // so we escape here only tags to avoid double &amp;
  5094. var escMessage = message.replace(/</g, '&lt;').
  5095. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5096. var escDisplayName = UIUtil.escapeHtml(displayName);
  5097. message = Replacement.processReplacements(escMessage);
  5098. var messageContainer =
  5099. '<div class="chatmessage">'+
  5100. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5101. '<div class="username ' + divClassName +'">' + escDisplayName +
  5102. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5103. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5104. '</div>';
  5105. $('#chatconversation').append(messageContainer);
  5106. $('#chatconversation').animate(
  5107. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5108. };
  5109. /**
  5110. * Appends error message to the conversation
  5111. * @param errorMessage the received error message.
  5112. * @param originalText the original message.
  5113. */
  5114. my.chatAddError = function(errorMessage, originalText) {
  5115. errorMessage = UIUtil.escapeHtml(errorMessage);
  5116. originalText = UIUtil.escapeHtml(originalText);
  5117. $('#chatconversation').append(
  5118. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5119. (originalText? (' \"'+ originalText + '\"') : "") +
  5120. ' was not sent.' +
  5121. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5122. $('#chatconversation').animate(
  5123. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5124. };
  5125. /**
  5126. * Sets the subject to the UI
  5127. * @param subject the subject
  5128. */
  5129. my.chatSetSubject = function(subject) {
  5130. if (subject)
  5131. subject = subject.trim();
  5132. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5133. if(subject === "") {
  5134. $("#subject").css({display: "none"});
  5135. }
  5136. else {
  5137. $("#subject").css({display: "block"});
  5138. }
  5139. };
  5140. /**
  5141. * Sets the chat conversation mode.
  5142. */
  5143. my.setChatConversationMode = function (isConversationMode) {
  5144. if (isConversationMode) {
  5145. $('#nickname').css({visibility: 'hidden'});
  5146. $('#chatconversation').css({visibility: 'visible'});
  5147. $('#usermsg').css({visibility: 'visible'});
  5148. $('#smileysarea').css({visibility: 'visible'});
  5149. $('#usermsg').focus();
  5150. }
  5151. };
  5152. /**
  5153. * Resizes the chat area.
  5154. */
  5155. my.resizeChat = function () {
  5156. var chatSize = require("../SidePanelToggler").getPanelSize();
  5157. $('#chatspace').width(chatSize[0]);
  5158. $('#chatspace').height(chatSize[1]);
  5159. resizeChatConversation();
  5160. };
  5161. /**
  5162. * Indicates if the chat is currently visible.
  5163. */
  5164. my.isVisible = function () {
  5165. return $('#chatspace').is(":visible");
  5166. };
  5167. /**
  5168. * Shows and hides the window with the smileys
  5169. */
  5170. my.toggleSmileys = toggleSmileys;
  5171. /**
  5172. * Scrolls chat to the bottom.
  5173. */
  5174. my.scrollChatToBottom = function() {
  5175. setTimeout(function () {
  5176. $('#chatconversation').scrollTop(
  5177. $('#chatconversation')[0].scrollHeight);
  5178. }, 5);
  5179. };
  5180. return my;
  5181. }(Chat || {}));
  5182. module.exports = Chat;
  5183. },{"../../../../service/UI/UIEvents":107,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5184. /* global APP, require */
  5185. var UIUtil = require("../../util/UIUtil");
  5186. /**
  5187. * List with supported commands. The keys are the names of the commands and
  5188. * the value is the function that processes the message.
  5189. * @type {{String: function}}
  5190. */
  5191. var commands = {
  5192. "topic" : processTopic
  5193. };
  5194. /**
  5195. * Extracts the command from the message.
  5196. * @param message the received message
  5197. * @returns {string} the command
  5198. */
  5199. function getCommand(message) {
  5200. if(message) {
  5201. for(var command in commands) {
  5202. if(message.indexOf("/" + command) == 0)
  5203. return command;
  5204. }
  5205. }
  5206. return "";
  5207. }
  5208. /**
  5209. * Processes the data for topic command.
  5210. * @param commandArguments the arguments of the topic command.
  5211. */
  5212. function processTopic(commandArguments) {
  5213. var topic = UIUtil.escapeHtml(commandArguments);
  5214. APP.xmpp.setSubject(topic);
  5215. }
  5216. /**
  5217. * Constructs a new CommandProccessor instance from a message that
  5218. * handles commands received via chat messages.
  5219. * @param message the message
  5220. * @constructor
  5221. */
  5222. function CommandsProcessor(message) {
  5223. var command = getCommand(message);
  5224. /**
  5225. * Returns the name of the command.
  5226. * @returns {String} the command
  5227. */
  5228. this.getCommand = function() {
  5229. return command;
  5230. };
  5231. var messageArgument = message.substr(command.length + 2);
  5232. /**
  5233. * Returns the arguments of the command.
  5234. * @returns {string}
  5235. */
  5236. this.getArgument = function() {
  5237. return messageArgument;
  5238. };
  5239. }
  5240. /**
  5241. * Checks whether this instance is valid command or not.
  5242. * @returns {boolean}
  5243. */
  5244. CommandsProcessor.prototype.isCommand = function() {
  5245. if (this.getCommand())
  5246. return true;
  5247. return false;
  5248. };
  5249. /**
  5250. * Processes the command.
  5251. */
  5252. CommandsProcessor.prototype.processCommand = function() {
  5253. if(!this.isCommand())
  5254. return;
  5255. commands[this.getCommand()](this.getArgument());
  5256. };
  5257. module.exports = CommandsProcessor;
  5258. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5259. var Smileys = require("./smileys.json");
  5260. /**
  5261. * Processes links and smileys in "body"
  5262. */
  5263. function processReplacements(body)
  5264. {
  5265. //make links clickable
  5266. body = linkify(body);
  5267. //add smileys
  5268. body = smilify(body);
  5269. return body;
  5270. }
  5271. /**
  5272. * Finds and replaces all links in the links in "body"
  5273. * with their <a href=""></a>
  5274. */
  5275. function linkify(inputText)
  5276. {
  5277. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5278. //URLs starting with http://, https://, or ftp://
  5279. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5280. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5281. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5282. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5283. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5284. //Change email addresses to mailto:: links.
  5285. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5286. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5287. return replacedText;
  5288. }
  5289. /**
  5290. * Replaces common smiley strings with images
  5291. */
  5292. function smilify(body)
  5293. {
  5294. if(!body) {
  5295. return body;
  5296. }
  5297. var regexs = Smileys["regexs"];
  5298. for(var smiley in regexs) {
  5299. if(regexs.hasOwnProperty(smiley)) {
  5300. body = body.replace(regexs[smiley],
  5301. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5302. }
  5303. }
  5304. return body;
  5305. }
  5306. module.exports = {
  5307. processReplacements: processReplacements,
  5308. linkify: linkify
  5309. };
  5310. },{"./smileys.json":24}],24:[function(require,module,exports){
  5311. module.exports={
  5312. "smileys": {
  5313. "smiley1": ":)",
  5314. "smiley2": ":(",
  5315. "smiley3": ":D",
  5316. "smiley4": "(y)",
  5317. "smiley5": " :P",
  5318. "smiley6": "(wave)",
  5319. "smiley7": "(blush)",
  5320. "smiley8": "(chuckle)",
  5321. "smiley9": "(shocked)",
  5322. "smiley10": ":*",
  5323. "smiley11": "(n)",
  5324. "smiley12": "(search)",
  5325. "smiley13": " <3",
  5326. "smiley14": "(oops)",
  5327. "smiley15": "(angry)",
  5328. "smiley16": "(angel)",
  5329. "smiley17": "(sick)",
  5330. "smiley18": ";(",
  5331. "smiley19": "(bomb)",
  5332. "smiley20": "(clap)",
  5333. "smiley21": " ;)"
  5334. },
  5335. "regexs": {
  5336. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5337. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5338. "smiley1": /(:-\)|:\))/gi,
  5339. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5340. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5341. "smiley6": /(\(wave\))/gi,
  5342. "smiley7": /(\(blush\))/gi,
  5343. "smiley8": /(\(chuckle\))/gi,
  5344. "smiley9": /(:-0|\(shocked\))/gi,
  5345. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5346. "smiley11": /(\(n\))/gi,
  5347. "smiley12": /(\(search\))/g,
  5348. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5349. "smiley14": /(\(oops\))/gi,
  5350. "smiley15": /(\(angry\))/gi,
  5351. "smiley16": /(\(angel\))/gi,
  5352. "smiley17": /(\(sick\))/gi,
  5353. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5354. "smiley19": /(\(bomb\))/gi,
  5355. "smiley20": /(\(clap\))/gi,
  5356. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5357. }
  5358. }
  5359. },{}],25:[function(require,module,exports){
  5360. /* global $, APP, Strophe */
  5361. var Avatar = require('../../avatar/Avatar');
  5362. var numberOfContacts = 0;
  5363. var notificationInterval;
  5364. /**
  5365. * Updates the number of participants in the contact list button and sets
  5366. * the glow
  5367. * @param delta indicates whether a new user has joined (1) or someone has
  5368. * left(-1)
  5369. */
  5370. function updateNumberOfParticipants(delta) {
  5371. numberOfContacts += delta;
  5372. if (numberOfContacts === 1) {
  5373. // when the user is alone we don't show the number of participants
  5374. $("#numberOfParticipants").text('');
  5375. ContactList.setVisualNotification(false);
  5376. } else if (numberOfContacts > 1) {
  5377. ContactList.setVisualNotification(!ContactList.isVisible());
  5378. $("#numberOfParticipants").text(numberOfContacts);
  5379. } else {
  5380. console.error("Invalid number of participants: " + numberOfContacts);
  5381. }
  5382. }
  5383. /**
  5384. * Creates the avatar element.
  5385. *
  5386. * @return {object} the newly created avatar element
  5387. */
  5388. function createAvatar(jid) {
  5389. var avatar = document.createElement('img');
  5390. avatar.className = "icon-avatar avatar";
  5391. avatar.src = Avatar.getContactListUrl(jid);
  5392. return avatar;
  5393. }
  5394. /**
  5395. * Creates the display name paragraph.
  5396. *
  5397. * @param displayName the display name to set
  5398. */
  5399. function createDisplayNameParagraph(key, displayName) {
  5400. var p = document.createElement('p');
  5401. if(displayName)
  5402. p.innerText = displayName;
  5403. else if(key) {
  5404. p.setAttribute("data-i18n",key);
  5405. p.innerText = APP.translation.translateString(key);
  5406. }
  5407. return p;
  5408. }
  5409. function stopGlowing(glower) {
  5410. window.clearInterval(notificationInterval);
  5411. notificationInterval = false;
  5412. glower.removeClass('glowing');
  5413. if (!ContactList.isVisible()) {
  5414. glower.removeClass('active');
  5415. }
  5416. }
  5417. /**
  5418. * Contact list.
  5419. */
  5420. var ContactList = {
  5421. /**
  5422. * Indicates if the chat is currently visible.
  5423. *
  5424. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5425. * otherwise
  5426. */
  5427. isVisible: function () {
  5428. return $('#contactlist').is(":visible");
  5429. },
  5430. /**
  5431. * Adds a contact for the given peerJid if such doesn't yet exist.
  5432. *
  5433. * @param peerJid the peerJid corresponding to the contact
  5434. */
  5435. ensureAddContact: function (peerJid) {
  5436. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5437. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5438. if (!contact || contact.length <= 0)
  5439. ContactList.addContact(peerJid);
  5440. },
  5441. /**
  5442. * Adds a contact for the given peer jid.
  5443. *
  5444. * @param peerJid the jid of the contact to add
  5445. */
  5446. addContact: function (peerJid) {
  5447. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5448. var contactlist = $('#contacts');
  5449. var newContact = document.createElement('li');
  5450. newContact.id = resourceJid;
  5451. newContact.className = "clickable";
  5452. newContact.onclick = function (event) {
  5453. if (event.currentTarget.className === "clickable") {
  5454. $(ContactList).trigger('contactclicked', [peerJid]);
  5455. }
  5456. };
  5457. newContact.appendChild(createAvatar(peerJid));
  5458. newContact.appendChild(createDisplayNameParagraph("participant"));
  5459. if (resourceJid === APP.xmpp.myResource()) {
  5460. contactlist.prepend(newContact);
  5461. }
  5462. else {
  5463. contactlist.append(newContact);
  5464. }
  5465. updateNumberOfParticipants(1);
  5466. },
  5467. /**
  5468. * Removes a contact for the given peer jid.
  5469. *
  5470. * @param peerJid the peerJid corresponding to the contact to remove
  5471. */
  5472. removeContact: function (peerJid) {
  5473. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5474. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5475. if (contact && contact.length > 0) {
  5476. var contactlist = $('#contactlist>ul');
  5477. contactlist.get(0).removeChild(contact.get(0));
  5478. updateNumberOfParticipants(-1);
  5479. }
  5480. },
  5481. setVisualNotification: function (show, stopGlowingIn) {
  5482. var glower = $('#contactListButton');
  5483. if (show && !notificationInterval) {
  5484. notificationInterval = window.setInterval(function () {
  5485. glower.toggleClass('active glowing');
  5486. }, 800);
  5487. }
  5488. else if (!show && notificationInterval) {
  5489. stopGlowing(glower);
  5490. }
  5491. if (stopGlowingIn) {
  5492. setTimeout(function () {
  5493. stopGlowing(glower);
  5494. }, stopGlowingIn);
  5495. }
  5496. },
  5497. setClickable: function (resourceJid, isClickable) {
  5498. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5499. if (isClickable) {
  5500. contact.addClass('clickable');
  5501. } else {
  5502. contact.removeClass('clickable');
  5503. }
  5504. },
  5505. onDisplayNameChange: function (peerJid, displayName) {
  5506. if (peerJid === 'localVideoContainer')
  5507. peerJid = APP.xmpp.myJid();
  5508. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5509. var contactName = $('#contacts #' + resourceJid + '>p');
  5510. if (contactName && displayName && displayName.length > 0)
  5511. contactName.html(displayName);
  5512. },
  5513. userAvatarChanged: function (resourceJid, contactListUrl) {
  5514. // set the avatar in the contact list
  5515. var contact = $('#' + resourceJid + '>img');
  5516. if (contact && contact.length > 0) {
  5517. contact.get(0).src = contactListUrl;
  5518. }
  5519. }
  5520. };
  5521. module.exports = ContactList;
  5522. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5523. /* global APP, $ */
  5524. var Avatar = require("../../avatar/Avatar");
  5525. var Settings = require("./../../../settings/Settings");
  5526. var UIUtil = require("../../util/UIUtil");
  5527. var languages = require("../../../../service/translation/languages");
  5528. function generateLanguagesSelectBox() {
  5529. var currentLang = APP.translation.getCurrentLanguage();
  5530. var html = "<select id=\"languages_selectbox\">";
  5531. var langArray = languages.getLanguages();
  5532. for(var i = 0; i < langArray.length; i++) {
  5533. var lang = langArray[i];
  5534. html += "<option ";
  5535. if(lang === currentLang)
  5536. html += "selected ";
  5537. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5538. html += "</option>";
  5539. }
  5540. return html + "</select>";
  5541. }
  5542. var SettingsMenu = {
  5543. init: function () {
  5544. var startMutedSelector = $("#startMutedOptions");
  5545. startMutedSelector.before(generateLanguagesSelectBox());
  5546. APP.translation.translateElement($("#languages_selectbox"));
  5547. $('#settingsmenu>input').keyup(function(event){
  5548. if(event.keyCode === 13) {//enter
  5549. SettingsMenu.update();
  5550. }
  5551. });
  5552. if (APP.xmpp.isModerator()) {
  5553. startMutedSelector.css("display", "block");
  5554. }
  5555. else {
  5556. startMutedSelector.css("display", "none");
  5557. }
  5558. $("#updateSettings").click(function () {
  5559. SettingsMenu.update();
  5560. });
  5561. },
  5562. onRoleChanged: function () {
  5563. if(APP.xmpp.isModerator()) {
  5564. $("#startMutedOptions").css("display", "block");
  5565. }
  5566. else {
  5567. $("#startMutedOptions").css("display", "none");
  5568. }
  5569. },
  5570. setStartMuted: function (audio, video) {
  5571. $("#startAudioMuted").attr("checked", audio);
  5572. $("#startVideoMuted").attr("checked", video);
  5573. },
  5574. update: function() {
  5575. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5576. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5577. if(newDisplayName) {
  5578. var displayName = Settings.setDisplayName(newDisplayName);
  5579. APP.xmpp.addToPresence("displayName", displayName, true);
  5580. }
  5581. var language = $("#languages_selectbox").val();
  5582. APP.translation.setLanguage(language);
  5583. Settings.setLanguage(language);
  5584. APP.xmpp.addToPresence("email", newEmail);
  5585. var email = Settings.setEmail(newEmail);
  5586. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5587. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5588. APP.xmpp.addToPresence("startMuted",
  5589. [startAudioMuted, startVideoMuted]);
  5590. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5591. },
  5592. isVisible: function() {
  5593. return $('#settingsmenu').is(':visible');
  5594. },
  5595. setDisplayName: function(newDisplayName) {
  5596. var displayName = Settings.setDisplayName(newDisplayName);
  5597. $('#setDisplayName').get(0).value = displayName;
  5598. },
  5599. onDisplayNameChange: function(peerJid, newDisplayName) {
  5600. if(peerJid === 'localVideoContainer' ||
  5601. peerJid === APP.xmpp.myJid()) {
  5602. this.setDisplayName(newDisplayName);
  5603. }
  5604. },
  5605. changeAvatar: function (thumbUrl) {
  5606. $('#avatar').get(0).src = thumbUrl;
  5607. }
  5608. };
  5609. module.exports = SettingsMenu;
  5610. },{"../../../../service/translation/languages":112,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5611. /* global $ */
  5612. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5613. var buttonHandlers = {
  5614. "bottom_toolbar_contact_list": function () {
  5615. BottomToolbar.toggleContactList();
  5616. },
  5617. "bottom_toolbar_film_strip": function () {
  5618. BottomToolbar.toggleFilmStrip();
  5619. },
  5620. "bottom_toolbar_chat": function () {
  5621. BottomToolbar.toggleChat();
  5622. }
  5623. };
  5624. var BottomToolbar = (function (my) {
  5625. my.init = function () {
  5626. for(var k in buttonHandlers)
  5627. $("#" + k).click(buttonHandlers[k]);
  5628. };
  5629. my.toggleChat = function() {
  5630. PanelToggler.toggleChat();
  5631. };
  5632. my.toggleContactList = function() {
  5633. PanelToggler.toggleContactList();
  5634. };
  5635. my.toggleFilmStrip = function() {
  5636. var filmstrip = $("#remoteVideos");
  5637. filmstrip.toggleClass("hidden");
  5638. };
  5639. $(document).bind("remotevideo.resized", function (event, width, height) {
  5640. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5641. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5642. });
  5643. return my;
  5644. }(BottomToolbar || {}));
  5645. module.exports = BottomToolbar;
  5646. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5647. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5648. Util */
  5649. var messageHandler = require("../util/MessageHandler");
  5650. var BottomToolbar = require("./BottomToolbar");
  5651. var Prezi = require("../prezi/Prezi");
  5652. var Etherpad = require("../etherpad/Etherpad");
  5653. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5654. var Authentication = require("../authentication/Authentication");
  5655. var UIUtil = require("../util/UIUtil");
  5656. var AuthenticationEvents
  5657. = require("../../../service/authentication/AuthenticationEvents");
  5658. var roomUrl = null;
  5659. var sharedKey = '';
  5660. var UI = null;
  5661. var recordingToaster = null;
  5662. var buttonHandlers = {
  5663. "toolbar_button_mute": function () {
  5664. return APP.UI.toggleAudio();
  5665. },
  5666. "toolbar_button_camera": function () {
  5667. return APP.UI.toggleVideo();
  5668. },
  5669. /*"toolbar_button_authentication": function () {
  5670. return Toolbar.authenticateClicked();
  5671. },*/
  5672. "toolbar_button_record": function () {
  5673. return toggleRecording();
  5674. },
  5675. "toolbar_button_security": function () {
  5676. return Toolbar.openLockDialog();
  5677. },
  5678. "toolbar_button_link": function () {
  5679. return Toolbar.openLinkDialog();
  5680. },
  5681. "toolbar_button_chat": function () {
  5682. return BottomToolbar.toggleChat();
  5683. },
  5684. "toolbar_button_prezi": function () {
  5685. return Prezi.openPreziDialog();
  5686. },
  5687. "toolbar_button_etherpad": function () {
  5688. return Etherpad.toggleEtherpad(0);
  5689. },
  5690. "toolbar_button_desktopsharing": function () {
  5691. return APP.desktopsharing.toggleScreenSharing();
  5692. },
  5693. "toolbar_button_fullScreen": function() {
  5694. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  5695. return Toolbar.toggleFullScreen();
  5696. },
  5697. "toolbar_button_sip": function () {
  5698. return callSipButtonClicked();
  5699. },
  5700. "toolbar_button_dialpad": function () {
  5701. return dialpadButtonClicked();
  5702. },
  5703. "toolbar_button_settings": function () {
  5704. PanelToggler.toggleSettingsMenu();
  5705. },
  5706. "toolbar_button_hangup": function () {
  5707. return hangup();
  5708. },
  5709. "toolbar_button_login": function () {
  5710. Toolbar.authenticateClicked();
  5711. },
  5712. "toolbar_button_logout": function () {
  5713. // Ask for confirmation
  5714. messageHandler.openTwoButtonDialog(
  5715. "dialog.logoutTitle",
  5716. null,
  5717. "dialog.logoutQuestion",
  5718. null,
  5719. false,
  5720. "dialog.Yes",
  5721. function (evt, yes) {
  5722. if (yes) {
  5723. APP.xmpp.logout(function (url) {
  5724. if (url) {
  5725. window.location.href = url;
  5726. } else {
  5727. hangup();
  5728. }
  5729. });
  5730. }
  5731. });
  5732. }
  5733. };
  5734. function hangup() {
  5735. APP.xmpp.disposeConference();
  5736. if(config.enableWelcomePage) {
  5737. setTimeout(function() {
  5738. window.localStorage.welcomePageDisabled = false;
  5739. window.location.pathname = "/";
  5740. }, 10000);
  5741. }
  5742. var title = APP.translation.generateTranslationHTML(
  5743. "dialog.sessTerminated");
  5744. var msg = APP.translation.generateTranslationHTML(
  5745. "dialog.hungUp");
  5746. var button = APP.translation.generateTranslationHTML(
  5747. "dialog.joinAgain");
  5748. var buttons = [];
  5749. buttons.push({title: button, value: true});
  5750. UI.messageHandler.openDialog(
  5751. title,
  5752. msg,
  5753. true,
  5754. buttons,
  5755. function(event, value, message, formVals) {
  5756. window.location.reload();
  5757. return false;
  5758. }
  5759. );
  5760. }
  5761. /**
  5762. * Starts or stops the recording for the conference.
  5763. */
  5764. function toggleRecording() {
  5765. APP.xmpp.toggleRecording(function (callback) {
  5766. var msg = APP.translation.generateTranslationHTML(
  5767. "dialog.recordingToken");
  5768. var token = APP.translation.translateString("dialog.token");
  5769. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5770. '<h2>' + msg + '</h2>' +
  5771. '<input name="recordingToken" type="text" ' +
  5772. ' data-i18n="[placeholder]dialog.token" ' +
  5773. 'placeholder="' + token + '" autofocus>',
  5774. false,
  5775. "dialog.Save",
  5776. function (e, v, m, f) {
  5777. if (v) {
  5778. var token = f.recordingToken;
  5779. if (token) {
  5780. callback(UIUtil.escapeHtml(token));
  5781. }
  5782. }
  5783. },
  5784. null,
  5785. function () { },
  5786. ':input:first'
  5787. );
  5788. }, Toolbar.setRecordingButtonState);
  5789. }
  5790. /**
  5791. * Locks / unlocks the room.
  5792. */
  5793. function lockRoom(lock) {
  5794. var currentSharedKey = '';
  5795. if (lock)
  5796. currentSharedKey = sharedKey;
  5797. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5798. // password is required
  5799. if (sharedKey) {
  5800. console.log('set room password');
  5801. Toolbar.lockLockButton();
  5802. }
  5803. else {
  5804. console.log('removed room password');
  5805. Toolbar.unlockLockButton();
  5806. }
  5807. }, function (err) {
  5808. console.warn('setting password failed', err);
  5809. messageHandler.showError("dialog.lockTitle",
  5810. "dialog.lockMessage");
  5811. Toolbar.setSharedKey('');
  5812. }, function () {
  5813. console.warn('room passwords not supported');
  5814. messageHandler.showError("dialog.warning",
  5815. "dialog.passwordNotSupported");
  5816. Toolbar.setSharedKey('');
  5817. });
  5818. }
  5819. /**
  5820. * Invite participants to conference.
  5821. */
  5822. function inviteParticipants() {
  5823. if (roomUrl === null)
  5824. return;
  5825. var sharedKeyText = "";
  5826. if (sharedKey && sharedKey.length > 0) {
  5827. sharedKeyText =
  5828. APP.translation.translateString("email.sharedKey",
  5829. {sharedKey: sharedKey});
  5830. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5831. }
  5832. var supportedBrowsers = "Chromium, Google Chrome " +
  5833. APP.translation.translateString("email.and") + " Opera";
  5834. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5835. var subject = APP.translation.translateString("email.subject",
  5836. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5837. var body = APP.translation.translateString("email.body",
  5838. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5839. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5840. body = body.replace(/\n/g, "%0D%0A");
  5841. if (window.localStorage.displayname) {
  5842. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5843. }
  5844. if (interfaceConfig.INVITATION_POWERED_BY) {
  5845. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5846. }
  5847. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5848. }
  5849. function dialpadButtonClicked() {
  5850. //TODO show the dialpad box
  5851. }
  5852. function callSipButtonClicked() {
  5853. var defaultNumber
  5854. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5855. var sipMsg = APP.translation.generateTranslationHTML(
  5856. "dialog.sipMsg");
  5857. messageHandler.openTwoButtonDialog(null, null, null,
  5858. '<h2>' + sipMsg + '</h2>' +
  5859. '<input name="sipNumber" type="text"' +
  5860. ' value="' + defaultNumber + '" autofocus>',
  5861. false,
  5862. "dialog.Dial",
  5863. function (e, v, m, f) {
  5864. if (v) {
  5865. var numberInput = f.sipNumber;
  5866. if (numberInput) {
  5867. APP.xmpp.dial(
  5868. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5869. }
  5870. }
  5871. },
  5872. null, null, ':input:first'
  5873. );
  5874. }
  5875. var Toolbar = (function (my) {
  5876. my.init = function (ui) {
  5877. for(var k in buttonHandlers)
  5878. $("#" + k).click(buttonHandlers[k]);
  5879. UI = ui;
  5880. // Update login info
  5881. APP.xmpp.addListener(
  5882. AuthenticationEvents.IDENTITY_UPDATED,
  5883. function (authenticationEnabled, userIdentity) {
  5884. var loggedIn = false;
  5885. if (userIdentity) {
  5886. loggedIn = true;
  5887. }
  5888. Toolbar.showAuthenticateButton(authenticationEnabled);
  5889. if (authenticationEnabled) {
  5890. Toolbar.setAuthenticatedIdentity(userIdentity);
  5891. Toolbar.showLoginButton(!loggedIn);
  5892. Toolbar.showLogoutButton(loggedIn);
  5893. }
  5894. }
  5895. );
  5896. };
  5897. /**
  5898. * Sets shared key
  5899. * @param sKey the shared key
  5900. */
  5901. my.setSharedKey = function (sKey) {
  5902. sharedKey = sKey;
  5903. };
  5904. my.authenticateClicked = function () {
  5905. Authentication.focusAuthenticationWindow();
  5906. if (!APP.xmpp.isExternalAuthEnabled()) {
  5907. Authentication.xmppAuthenticate();
  5908. return;
  5909. }
  5910. // Get authentication URL
  5911. if (!APP.xmpp.isMUCJoined()) {
  5912. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  5913. // If conference has not been started yet - redirect to login page
  5914. window.location.href = url;
  5915. });
  5916. } else {
  5917. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  5918. // Otherwise - open popup with authentication URL
  5919. var authenticationWindow = Authentication.createAuthenticationWindow(
  5920. function () {
  5921. // On popup closed - retry room allocation
  5922. APP.xmpp.allocateConferenceFocus(
  5923. APP.UI.getRoomName(),
  5924. function () { console.info("AUTH DONE"); }
  5925. );
  5926. }, url);
  5927. if (!authenticationWindow) {
  5928. messageHandler.openMessageDialog(
  5929. null, "dialog.popupError");
  5930. }
  5931. });
  5932. }
  5933. };
  5934. /**
  5935. * Updates the room invite url.
  5936. */
  5937. my.updateRoomUrl = function (newRoomUrl) {
  5938. roomUrl = newRoomUrl;
  5939. // If the invite dialog has been already opened we update the information.
  5940. var inviteLink = document.getElementById('inviteLinkRef');
  5941. if (inviteLink) {
  5942. inviteLink.value = roomUrl;
  5943. inviteLink.select();
  5944. $('#inviteLinkRef').parent()
  5945. .find('button[value=true]').prop('disabled', false);
  5946. }
  5947. };
  5948. /**
  5949. * Disables and enables some of the buttons.
  5950. */
  5951. my.setupButtonsFromConfig = function () {
  5952. if (config.disablePrezi) {
  5953. $("#prezi_button").css({display: "none"});
  5954. }
  5955. };
  5956. /**
  5957. * Opens the lock room dialog.
  5958. */
  5959. my.openLockDialog = function () {
  5960. // Only the focus is able to set a shared key.
  5961. if (!APP.xmpp.isModerator()) {
  5962. if (sharedKey) {
  5963. messageHandler.openMessageDialog(null,
  5964. "dialog.passwordError");
  5965. } else {
  5966. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  5967. }
  5968. } else {
  5969. if (sharedKey) {
  5970. messageHandler.openTwoButtonDialog(null, null,
  5971. "dialog.passwordCheck",
  5972. null,
  5973. false,
  5974. "dialog.Remove",
  5975. function (e, v) {
  5976. if (v) {
  5977. Toolbar.setSharedKey('');
  5978. lockRoom(false);
  5979. }
  5980. });
  5981. } else {
  5982. var msg = APP.translation.generateTranslationHTML(
  5983. "dialog.passwordMsg");
  5984. var yourPassword = APP.translation.translateString(
  5985. "dialog.yourPassword");
  5986. messageHandler.openTwoButtonDialog(null, null, null,
  5987. '<h2>' + msg + '</h2>' +
  5988. '<input name="lockKey" type="text"' +
  5989. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  5990. 'placeholder="' + yourPassword + '" autofocus>',
  5991. false,
  5992. "dialog.Save",
  5993. function (e, v, m, f) {
  5994. if (v) {
  5995. var lockKey = f.lockKey;
  5996. if (lockKey) {
  5997. Toolbar.setSharedKey(
  5998. UIUtil.escapeHtml(lockKey));
  5999. lockRoom(true);
  6000. }
  6001. }
  6002. },
  6003. null, null, 'input:first'
  6004. );
  6005. }
  6006. }
  6007. };
  6008. /**
  6009. * Opens the invite link dialog.
  6010. */
  6011. my.openLinkDialog = function () {
  6012. var inviteAttreibutes;
  6013. if (roomUrl === null) {
  6014. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6015. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6016. } else {
  6017. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6018. }
  6019. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6020. null, null,
  6021. '<input id="inviteLinkRef" type="text" ' +
  6022. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6023. false,
  6024. "dialog.Invite",
  6025. function (e, v) {
  6026. if (v) {
  6027. if (roomUrl) {
  6028. inviteParticipants();
  6029. }
  6030. }
  6031. },
  6032. function (event) {
  6033. if (roomUrl) {
  6034. document.getElementById('inviteLinkRef').select();
  6035. } else {
  6036. if (event && event.target)
  6037. $(event.target)
  6038. .find('button[value=true]').prop('disabled', true);
  6039. }
  6040. }
  6041. );
  6042. };
  6043. /**
  6044. * Opens the settings dialog.
  6045. * FIXME: not used ?
  6046. */
  6047. my.openSettingsDialog = function () {
  6048. var settings1 = APP.translation.generateTranslationHTML(
  6049. "dialog.settings1");
  6050. var settings2 = APP.translation.generateTranslationHTML(
  6051. "dialog.settings2");
  6052. var settings3 = APP.translation.generateTranslationHTML(
  6053. "dialog.settings3");
  6054. var yourPassword = APP.translation.translateString(
  6055. "dialog.yourPassword");
  6056. messageHandler.openTwoButtonDialog(null,
  6057. '<h2>' + settings1 + '</h2>' +
  6058. '<input type="checkbox" id="initMuted">' +
  6059. settings2 + '<br/>' +
  6060. '<input type="checkbox" id="requireNicknames">' +
  6061. settings3 +
  6062. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6063. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6064. null,
  6065. null,
  6066. false,
  6067. "dialog.Save",
  6068. function () {
  6069. document.getElementById('lockKey').focus();
  6070. },
  6071. function (e, v) {
  6072. if (v) {
  6073. if ($('#initMuted').is(":checked")) {
  6074. // it is checked
  6075. }
  6076. if ($('#requireNicknames').is(":checked")) {
  6077. // it is checked
  6078. }
  6079. /*
  6080. var lockKey = document.getElementById('lockKey');
  6081. if (lockKey.value) {
  6082. setSharedKey(lockKey.value);
  6083. lockRoom(true);
  6084. }
  6085. */
  6086. }
  6087. }
  6088. );
  6089. };
  6090. /**
  6091. * Toggles the application in and out of full screen mode
  6092. * (a.k.a. presentation mode in Chrome).
  6093. */
  6094. my.toggleFullScreen = function () {
  6095. var fsElement = document.documentElement;
  6096. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6097. //Enter Full Screen
  6098. if (fsElement.mozRequestFullScreen) {
  6099. fsElement.mozRequestFullScreen();
  6100. }
  6101. else {
  6102. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6103. }
  6104. } else {
  6105. //Exit Full Screen
  6106. if (document.mozCancelFullScreen) {
  6107. document.mozCancelFullScreen();
  6108. } else {
  6109. document.webkitCancelFullScreen();
  6110. }
  6111. }
  6112. };
  6113. /**
  6114. * Unlocks the lock button state.
  6115. */
  6116. my.unlockLockButton = function () {
  6117. if ($("#lockIcon").hasClass("icon-security-locked"))
  6118. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6119. };
  6120. /**
  6121. * Updates the lock button state to locked.
  6122. */
  6123. my.lockLockButton = function () {
  6124. if ($("#lockIcon").hasClass("icon-security"))
  6125. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6126. };
  6127. /**
  6128. * Shows or hides authentication button
  6129. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6130. */
  6131. my.showAuthenticateButton = function (show) {
  6132. if (show) {
  6133. $('#authentication').css({display: "inline"});
  6134. }
  6135. else {
  6136. $('#authentication').css({display: "none"});
  6137. }
  6138. };
  6139. // Shows or hides the 'recording' button.
  6140. my.showRecordingButton = function (show) {
  6141. if (!config.enableRecording) {
  6142. return;
  6143. }
  6144. if (show) {
  6145. $('#recording').css({display: "inline"});
  6146. }
  6147. else {
  6148. $('#recording').css({display: "none"});
  6149. }
  6150. };
  6151. // Sets the state of the recording button
  6152. my.setRecordingButtonState = function (recordingState) {
  6153. var selector = $('#recordButton');
  6154. if (recordingState === 'on') {
  6155. selector.removeClass("icon-recEnable");
  6156. selector.addClass("icon-recEnable active");
  6157. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6158. var recordOnKey = "recording.on";
  6159. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6160. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6161. setTimeout(function(){
  6162. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6163. $('#videoConnectionMessage').css({display: "none"});
  6164. }, 1500);
  6165. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6166. null, null, {timeOut: 0, closeButton: null});
  6167. } else if (recordingState === 'off') {
  6168. selector.removeClass("icon-recEnable active");
  6169. selector.addClass("icon-recEnable");
  6170. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6171. $('#videoConnectionMessage').css({display: "none"});
  6172. if (recordingToaster)
  6173. messageHandler.remove(recordingToaster);
  6174. } else if (recordingState === 'pending') {
  6175. selector.removeClass("icon-recEnable active");
  6176. selector.addClass("icon-recEnable");
  6177. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6178. var recordPendingKey = "recording.pending";
  6179. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6180. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6181. $('#videoConnectionMessage').css({display: "block"});
  6182. }
  6183. };
  6184. // Shows or hides SIP calls button
  6185. my.showSipCallButton = function (show) {
  6186. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6187. $('#sipCallButton').css({display: "inline-block"});
  6188. } else {
  6189. $('#sipCallButton').css({display: "none"});
  6190. }
  6191. };
  6192. // Shows or hides the dialpad button
  6193. my.showDialPadButton = function (show) {
  6194. if (show) {
  6195. $('#dialPadButton').css({display: "inline-block"});
  6196. } else {
  6197. $('#dialPadButton').css({display: "none"});
  6198. }
  6199. };
  6200. /**
  6201. * Displays user authenticated identity name(login).
  6202. * @param authIdentity identity name to be displayed.
  6203. */
  6204. my.setAuthenticatedIdentity = function (authIdentity) {
  6205. if (authIdentity) {
  6206. var selector = $('#toolbar_auth_identity');
  6207. selector.css({display: "list-item"});
  6208. selector.text(authIdentity);
  6209. } else {
  6210. $('#toolbar_auth_identity').css({display: "none"});
  6211. }
  6212. };
  6213. /**
  6214. * Shows/hides login button.
  6215. * @param show <tt>true</tt> to show
  6216. */
  6217. my.showLoginButton = function (show) {
  6218. if (show) {
  6219. $('#toolbar_button_login').css({display: "list-item"});
  6220. } else {
  6221. $('#toolbar_button_login').css({display: "none"});
  6222. }
  6223. };
  6224. /**
  6225. * Shows/hides logout button.
  6226. * @param show <tt>true</tt> to show
  6227. */
  6228. my.showLogoutButton = function (show) {
  6229. if (show) {
  6230. $('#toolbar_button_logout').css({display: "list-item"});
  6231. } else {
  6232. $('#toolbar_button_logout').css({display: "none"});
  6233. }
  6234. };
  6235. /**
  6236. * Sets the state of the button. The button has blue glow if desktop
  6237. * streaming is active.
  6238. * @param active the state of the desktop streaming.
  6239. */
  6240. my.changeDesktopSharingButtonState = function (active) {
  6241. var button = $("#desktopsharing > a");
  6242. if (active) {
  6243. button.addClass("glow");
  6244. } else {
  6245. button.removeClass("glow");
  6246. }
  6247. };
  6248. return my;
  6249. }(Toolbar || {}));
  6250. module.exports = Toolbar;
  6251. },{"../../../service/authentication/AuthenticationEvents":108,"../authentication/Authentication":14,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../side_pannels/SidePanelToggler":20,"../util/MessageHandler":31,"../util/UIUtil":33,"./BottomToolbar":27}],29:[function(require,module,exports){
  6252. /* global APP, config, $, interfaceConfig, Moderator,
  6253. DesktopStreaming.showDesktopSharingButton */
  6254. var toolbarTimeoutObject,
  6255. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6256. function showDesktopSharingButton() {
  6257. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6258. $('#desktopsharing').css({display: "inline"});
  6259. } else {
  6260. $('#desktopsharing').css({display: "none"});
  6261. }
  6262. }
  6263. /**
  6264. * Hides the toolbar.
  6265. */
  6266. function hideToolbar() {
  6267. if(config.alwaysVisibleToolbar)
  6268. return;
  6269. var header = $("#header"),
  6270. bottomToolbar = $("#bottomToolbar");
  6271. var isToolbarHover = false;
  6272. header.find('*').each(function () {
  6273. var id = $(this).attr('id');
  6274. if ($("#" + id + ":hover").length > 0) {
  6275. isToolbarHover = true;
  6276. }
  6277. });
  6278. if ($("#bottomToolbar:hover").length > 0) {
  6279. isToolbarHover = true;
  6280. }
  6281. clearTimeout(toolbarTimeoutObject);
  6282. toolbarTimeoutObject = null;
  6283. if (!isToolbarHover) {
  6284. header.hide("slide", { direction: "up", duration: 300});
  6285. $('#subject').animate({top: "-=40"}, 300);
  6286. if ($("#remoteVideos").hasClass("hidden")) {
  6287. bottomToolbar.hide(
  6288. "slide", {direction: "right", duration: 300});
  6289. }
  6290. }
  6291. else {
  6292. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6293. }
  6294. }
  6295. var ToolbarToggler = {
  6296. /**
  6297. * Shows the main toolbar.
  6298. */
  6299. showToolbar: function () {
  6300. if(config.filmStripOnly)
  6301. return;
  6302. var header = $("#header"),
  6303. bottomToolbar = $("#bottomToolbar");
  6304. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6305. header.show("slide", { direction: "up", duration: 300});
  6306. $('#subject').animate({top: "+=40"}, 300);
  6307. if (!bottomToolbar.is(":visible")) {
  6308. bottomToolbar.show(
  6309. "slide", {direction: "right", duration: 300});
  6310. }
  6311. if (toolbarTimeoutObject) {
  6312. clearTimeout(toolbarTimeoutObject);
  6313. toolbarTimeoutObject = null;
  6314. }
  6315. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6316. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6317. }
  6318. if (APP.xmpp.isModerator())
  6319. {
  6320. // TODO: Enable settings functionality.
  6321. // Need to uncomment the settings button in index.html.
  6322. // $('#settingsButton').css({visibility:"visible"});
  6323. }
  6324. // Show/hide desktop sharing button
  6325. showDesktopSharingButton();
  6326. },
  6327. /**
  6328. * Docks/undocks the toolbar.
  6329. *
  6330. * @param isDock indicates what operation to perform
  6331. */
  6332. dockToolbar: function (isDock) {
  6333. if(config.filmStripOnly)
  6334. return;
  6335. if (isDock) {
  6336. // First make sure the toolbar is shown.
  6337. if (!$('#header').is(':visible')) {
  6338. this.showToolbar();
  6339. }
  6340. // Then clear the time out, to dock the toolbar.
  6341. if (toolbarTimeoutObject) {
  6342. clearTimeout(toolbarTimeoutObject);
  6343. toolbarTimeoutObject = null;
  6344. }
  6345. }
  6346. else {
  6347. if (!$('#header').is(':visible')) {
  6348. this.showToolbar();
  6349. }
  6350. else {
  6351. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6352. }
  6353. }
  6354. },
  6355. showDesktopSharingButton: showDesktopSharingButton
  6356. };
  6357. module.exports = ToolbarToggler;
  6358. },{}],30:[function(require,module,exports){
  6359. /* global $ */
  6360. var JitsiPopover = (function () {
  6361. /**
  6362. * Constructs new JitsiPopover and attaches it to the element
  6363. * @param element jquery selector
  6364. * @param options the options for the popover.
  6365. * @constructor
  6366. */
  6367. function JitsiPopover(element, options)
  6368. {
  6369. this.options = {
  6370. skin: "white",
  6371. content: ""
  6372. };
  6373. if(options)
  6374. {
  6375. if(options.skin)
  6376. this.options.skin = options.skin;
  6377. if(options.content)
  6378. this.options.content = options.content;
  6379. }
  6380. this.elementIsHovered = false;
  6381. this.popoverIsHovered = false;
  6382. this.popoverShown = false;
  6383. element.data("jitsi_popover", this);
  6384. this.element = element;
  6385. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6386. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6387. '<div class="jitsiPopupmenuPadding"></div></div>';
  6388. var self = this;
  6389. this.element.on("mouseenter", function () {
  6390. self.elementIsHovered = true;
  6391. self.show();
  6392. }).on("mouseleave", function () {
  6393. self.elementIsHovered = false;
  6394. setTimeout(function () {
  6395. self.hide();
  6396. }, 10);
  6397. });
  6398. }
  6399. /**
  6400. * Shows the popover
  6401. */
  6402. JitsiPopover.prototype.show = function () {
  6403. if(!JitsiPopover.enabled)
  6404. return;
  6405. this.createPopover();
  6406. this.popoverShown = true;
  6407. };
  6408. /**
  6409. * Hides the popover
  6410. */
  6411. JitsiPopover.prototype.hide = function () {
  6412. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6413. this.popoverShown) {
  6414. this.forceHide();
  6415. }
  6416. };
  6417. /**
  6418. * Hides the popover.
  6419. */
  6420. JitsiPopover.prototype.forceHide = function () {
  6421. $(".jitsipopover").remove();
  6422. this.popoverShown = false;
  6423. };
  6424. /**
  6425. * Creates the popover html.
  6426. */
  6427. JitsiPopover.prototype.createPopover = function () {
  6428. $("body").append(this.template);
  6429. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6430. var self = this;
  6431. $(".jitsipopover").on("mouseenter", function () {
  6432. self.popoverIsHovered = true;
  6433. }).on("mouseleave", function () {
  6434. self.popoverIsHovered = false;
  6435. self.hide();
  6436. });
  6437. this.refreshPosition();
  6438. };
  6439. /**
  6440. * Refreshes the position of the popover.
  6441. */
  6442. JitsiPopover.prototype.refreshPosition = function () {
  6443. $(".jitsipopover").position({
  6444. my: "bottom",
  6445. at: "top",
  6446. collision: "fit",
  6447. of: this.element,
  6448. using: function (position, elements) {
  6449. var calcLeft = elements.target.left - elements.element.left +
  6450. elements.target.width/2;
  6451. $(".jitsipopover").css(
  6452. {top: position.top, left: position.left, display: "table"});
  6453. $(".jitsipopover > .arrow").css({left: calcLeft});
  6454. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6455. {left: calcLeft - 50});
  6456. }
  6457. });
  6458. };
  6459. /**
  6460. * Updates the content of popover.
  6461. * @param content new content
  6462. */
  6463. JitsiPopover.prototype.updateContent = function (content) {
  6464. this.options.content = content;
  6465. if(!this.popoverShown)
  6466. return;
  6467. $(".jitsipopover").remove();
  6468. this.createPopover();
  6469. };
  6470. JitsiPopover.enabled = true;
  6471. return JitsiPopover;
  6472. })();
  6473. module.exports = JitsiPopover;
  6474. },{}],31:[function(require,module,exports){
  6475. /* global $, APP, jQuery, toastr */
  6476. /**
  6477. * Flag for enable/disable of the notifications.
  6478. * @type {boolean}
  6479. */
  6480. var notificationsEnabled = true;
  6481. var messageHandler = (function(my) {
  6482. /**
  6483. * Shows a message to the user.
  6484. *
  6485. * @param titleKey the title of the message
  6486. * @param messageKey the text of the message
  6487. */
  6488. my.openMessageDialog = function(titleKey, messageKey) {
  6489. var title = null;
  6490. if(titleKey) {
  6491. title = APP.translation.generateTranslationHTML(titleKey);
  6492. }
  6493. var message = APP.translation.generateTranslationHTML(messageKey);
  6494. $.prompt(message,
  6495. {title: title, persistent: false}
  6496. );
  6497. };
  6498. /**
  6499. * Shows a message to the user with two buttons: first is given as a
  6500. * parameter and the second is Cancel.
  6501. *
  6502. * @param titleString the title of the message
  6503. * @param msgString the text of the message
  6504. * @param persistent boolean value which determines whether the message is
  6505. * persistent or not
  6506. * @param leftButton the fist button's text
  6507. * @param submitFunction function to be called on submit
  6508. * @param loadedFunction function to be called after the prompt is fully
  6509. * loaded
  6510. * @param closeFunction function to be called after the prompt is closed
  6511. * @param focus optional focus selector or button index to be focused after
  6512. * the dialog is opened
  6513. * @param defaultButton index of default button which will be activated when
  6514. * the user press 'enter'. Indexed from 0.
  6515. */
  6516. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6517. persistent, leftButtonKey, submitFunction, loadedFunction,
  6518. closeFunction, focus, defaultButton) {
  6519. var buttons = [];
  6520. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6521. buttons.push({ title: leftButton, value: true});
  6522. var cancelButton
  6523. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6524. buttons.push({title: cancelButton, value: false});
  6525. var message = msgString, title = titleString;
  6526. if (titleKey) {
  6527. title = APP.translation.generateTranslationHTML(titleKey);
  6528. }
  6529. if (msgKey) {
  6530. message = APP.translation.generateTranslationHTML(msgKey);
  6531. }
  6532. $.prompt(message, {
  6533. title: title,
  6534. persistent: false,
  6535. buttons: buttons,
  6536. defaultButton: defaultButton,
  6537. focus: focus,
  6538. loaded: loadedFunction,
  6539. submit: submitFunction,
  6540. close: closeFunction
  6541. });
  6542. };
  6543. /**
  6544. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6545. *
  6546. * @param titleString the title of the message
  6547. * @param msgString the text of the message
  6548. * @param persistent boolean value which determines whether the message is
  6549. * persistent or not
  6550. * @param buttons object with the buttons. The keys must be the name of the
  6551. * button and value is the value that will be passed to
  6552. * submitFunction
  6553. * @param submitFunction function to be called on submit
  6554. * @param loadedFunction function to be called after the prompt is fully
  6555. * loaded
  6556. */
  6557. my.openDialog = function (titleString, msgString, persistent, buttons,
  6558. submitFunction, loadedFunction) {
  6559. var args = {
  6560. title: titleString,
  6561. persistent: persistent,
  6562. buttons: buttons,
  6563. defaultButton: 1,
  6564. loaded: loadedFunction,
  6565. submit: submitFunction
  6566. };
  6567. if (persistent) {
  6568. args.closeText = '';
  6569. }
  6570. return new Impromptu(msgString, args);
  6571. };
  6572. /**
  6573. * Closes currently opened dialog.
  6574. */
  6575. my.closeDialog = function () {
  6576. $.prompt.close();
  6577. };
  6578. /**
  6579. * Shows a dialog with different states to the user.
  6580. *
  6581. * @param statesObject object containing all the states of the dialog.
  6582. */
  6583. my.openDialogWithStates = function (statesObject, options) {
  6584. return new Impromptu(statesObject, options);
  6585. };
  6586. /**
  6587. * Opens new popup window for given <tt>url</tt> centered over current
  6588. * window.
  6589. *
  6590. * @param url the URL to be displayed in the popup window
  6591. * @param w the width of the popup window
  6592. * @param h the height of the popup window
  6593. * @param onPopupClosed optional callback function called when popup window
  6594. * has been closed.
  6595. *
  6596. * @returns {object} popup window object if opened successfully or undefined
  6597. * in case we failed to open it(popup blocked)
  6598. */
  6599. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6600. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6601. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6602. var popup = window.open(
  6603. url, '_blank',
  6604. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6605. if (popup && onPopupClosed) {
  6606. var pollTimer = window.setInterval(function () {
  6607. if (popup.closed !== false) {
  6608. window.clearInterval(pollTimer);
  6609. onPopupClosed();
  6610. }
  6611. }, 200);
  6612. }
  6613. return popup;
  6614. };
  6615. /**
  6616. * Shows a dialog prompting the user to send an error report.
  6617. *
  6618. * @param titleKey the title of the message
  6619. * @param msgKey the text of the message
  6620. * @param error the error that is being reported
  6621. */
  6622. my.openReportDialog = function(titleKey, msgKey, error) {
  6623. my.openMessageDialog(titleKey, msgKey);
  6624. console.log(error);
  6625. //FIXME send the error to the server
  6626. };
  6627. /**
  6628. * Shows an error dialog to the user.
  6629. * @param titleKey the title of the message.
  6630. * @param msgKey the text of the message.
  6631. */
  6632. my.showError = function(titleKey, msgKey) {
  6633. if (!titleKey) {
  6634. titleKey = "dialog.oops";
  6635. }
  6636. if (!msgKey) {
  6637. msgKey = "dialog.defaultError";
  6638. }
  6639. messageHandler.openMessageDialog(titleKey, msgKey);
  6640. };
  6641. /**
  6642. * Displayes notification.
  6643. * @param displayName display name of the participant that is associated with the notification.
  6644. * @param displayNameKey the key from the language file for the display name.
  6645. * @param cls css class for the notification
  6646. * @param messageKey the key from the language file for the text of the message.
  6647. * @param messageArguments object with the arguments for the message.
  6648. * @param options object with language options.
  6649. */
  6650. my.notify = function(displayName, displayNameKey,
  6651. cls, messageKey, messageArguments, options) {
  6652. if(!notificationsEnabled)
  6653. return;
  6654. var displayNameSpan = '<span class="nickname" ';
  6655. if (displayName) {
  6656. displayNameSpan += ">" + displayName;
  6657. } else {
  6658. displayNameSpan += "data-i18n='" + displayNameKey +
  6659. "'>" + APP.translation.translateString(displayNameKey);
  6660. }
  6661. displayNameSpan += "</span>";
  6662. return toastr.info(
  6663. displayNameSpan + '<br>' +
  6664. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6665. (messageArguments?
  6666. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6667. : "") + ">" +
  6668. APP.translation.translateString(messageKey,
  6669. messageArguments) +
  6670. '</span>', null, options);
  6671. };
  6672. /**
  6673. * Removes the toaster.
  6674. * @param toasterElement
  6675. */
  6676. my.remove = function(toasterElement) {
  6677. toasterElement.remove();
  6678. };
  6679. /**
  6680. * Disables notifications.
  6681. */
  6682. my.disableNotifications = function () {
  6683. notificationsEnabled = false;
  6684. };
  6685. /**
  6686. * Enables notifications.
  6687. */
  6688. my.enableNotifications = function () {
  6689. notificationsEnabled = true;
  6690. };
  6691. return my;
  6692. }(messageHandler || {}));
  6693. module.exports = messageHandler;
  6694. },{}],32:[function(require,module,exports){
  6695. var UIEvents = require("../../../service/UI/UIEvents");
  6696. var nickname = null;
  6697. var eventEmitter = null;
  6698. var NicknameHandler = {
  6699. init: function (emitter) {
  6700. eventEmitter = emitter;
  6701. var storedDisplayName = window.localStorage.displayname;
  6702. if (storedDisplayName) {
  6703. nickname = storedDisplayName;
  6704. }
  6705. },
  6706. setNickname: function (newNickname) {
  6707. if (!newNickname || nickname === newNickname)
  6708. return;
  6709. nickname = newNickname;
  6710. window.localStorage.displayname = nickname;
  6711. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6712. },
  6713. getNickname: function () {
  6714. return nickname;
  6715. },
  6716. addListener: function (type, listener) {
  6717. eventEmitter.on(type, listener);
  6718. }
  6719. };
  6720. module.exports = NicknameHandler;
  6721. },{"../../../service/UI/UIEvents":107}],33:[function(require,module,exports){
  6722. /* global $ */
  6723. /**
  6724. * Created by hristo on 12/22/14.
  6725. */
  6726. module.exports = {
  6727. /**
  6728. * Returns the available video width.
  6729. */
  6730. getAvailableVideoWidth: function (isVisible) {
  6731. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6732. if(typeof isVisible === "undefined" || isVisible === null)
  6733. isVisible = PanelToggler.isVisible();
  6734. var rightPanelWidth
  6735. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6736. return window.innerWidth - rightPanelWidth;
  6737. },
  6738. /**
  6739. * Changes the style class of the element given by id.
  6740. */
  6741. buttonClick: function(id, classname) {
  6742. $(id).toggleClass(classname); // add the class to the clicked element
  6743. },
  6744. /**
  6745. * Returns the text width for the given element.
  6746. *
  6747. * @param el the element
  6748. */
  6749. getTextWidth: function (el) {
  6750. return (el.clientWidth + 1);
  6751. },
  6752. /**
  6753. * Returns the text height for the given element.
  6754. *
  6755. * @param el the element
  6756. */
  6757. getTextHeight: function (el) {
  6758. return (el.clientHeight + 1);
  6759. },
  6760. /**
  6761. * Plays the sound given by id.
  6762. *
  6763. * @param id the identifier of the audio element.
  6764. */
  6765. playSoundNotification: function (id) {
  6766. document.getElementById(id).play();
  6767. },
  6768. /**
  6769. * Escapes the given text.
  6770. */
  6771. escapeHtml: function (unsafeText) {
  6772. return $('<div/>').text(unsafeText).html();
  6773. },
  6774. imageToGrayScale: function (canvas) {
  6775. var context = canvas.getContext('2d');
  6776. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6777. var pixels = imgData.data;
  6778. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6779. var grayscale
  6780. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  6781. pixels[i ] = grayscale; // red
  6782. pixels[i+1] = grayscale; // green
  6783. pixels[i+2] = grayscale; // blue
  6784. // pixels[i+3] is alpha
  6785. }
  6786. // redraw the image in black & white
  6787. context.putImageData(imgData, 0, 0);
  6788. },
  6789. setTooltip: function (element, key, position) {
  6790. element.setAttribute("data-i18n", "[data-content]" + key);
  6791. element.setAttribute("data-toggle", "popover");
  6792. element.setAttribute("data-placement", position);
  6793. element.setAttribute("data-html", true);
  6794. element.setAttribute("data-container", "body");
  6795. }
  6796. };
  6797. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6798. /* global APP, $ */
  6799. var JitsiPopover = require("../util/JitsiPopover");
  6800. /**
  6801. * Constructs new connection indicator.
  6802. * @param videoContainer the video container associated with the indicator.
  6803. * @constructor
  6804. */
  6805. function ConnectionIndicator(videoContainer, jid) {
  6806. this.videoContainer = videoContainer;
  6807. this.bandwidth = null;
  6808. this.packetLoss = null;
  6809. this.bitrate = null;
  6810. this.showMoreValue = false;
  6811. this.resolution = null;
  6812. this.transport = [];
  6813. this.popover = null;
  6814. this.jid = jid;
  6815. this.create();
  6816. }
  6817. /**
  6818. * Values for the connection quality
  6819. * @type {{98: string,
  6820. * 81: string,
  6821. * 64: string,
  6822. * 47: string,
  6823. * 30: string,
  6824. * 0: string}}
  6825. */
  6826. ConnectionIndicator.connectionQualityValues = {
  6827. 98: "18px", //full
  6828. 81: "15px",//4 bars
  6829. 64: "11px",//3 bars
  6830. 47: "7px",//2 bars
  6831. 30: "3px",//1 bar
  6832. 0: "0px"//empty
  6833. };
  6834. ConnectionIndicator.getIP = function(value) {
  6835. return value.substring(0, value.lastIndexOf(":"));
  6836. };
  6837. ConnectionIndicator.getPort = function(value) {
  6838. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6839. };
  6840. ConnectionIndicator.getStringFromArray = function (array) {
  6841. var res = "";
  6842. for(var i = 0; i < array.length; i++) {
  6843. res += (i === 0? "" : ", ") + array[i];
  6844. }
  6845. return res;
  6846. };
  6847. /**
  6848. * Generates the html content.
  6849. * @returns {string} the html content.
  6850. */
  6851. ConnectionIndicator.prototype.generateText = function () {
  6852. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6853. var translate = APP.translation.translateString;
  6854. if(this.bitrate === null) {
  6855. downloadBitrate = "N/A";
  6856. uploadBitrate = "N/A";
  6857. }
  6858. else {
  6859. downloadBitrate =
  6860. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6861. uploadBitrate =
  6862. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6863. }
  6864. if(this.packetLoss === null) {
  6865. packetLoss = "N/A";
  6866. } else {
  6867. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6868. (this.packetLoss.download !== null ?
  6869. this.packetLoss.download : "N/A") +
  6870. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6871. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  6872. "%";
  6873. }
  6874. var resolutionValue = null;
  6875. if(this.resolution && this.jid != null) {
  6876. var keys = Object.keys(this.resolution);
  6877. for(var ssrc in this.resolution) {
  6878. resolutionValue = this.resolution[ssrc];
  6879. }
  6880. }
  6881. if(this.jid === null) {
  6882. resolution = "";
  6883. if(this.resolution === null || !Object.keys(this.resolution) ||
  6884. Object.keys(this.resolution).length === 0) {
  6885. resolution = "N/A";
  6886. } else {
  6887. for (i in this.resolution) {
  6888. resolutionValue = this.resolution[i];
  6889. if (resolutionValue) {
  6890. if (resolutionValue.height &&
  6891. resolutionValue.width) {
  6892. resolution += (resolution === "" ? "" : ", ") +
  6893. resolutionValue.width + "x" +
  6894. resolutionValue.height;
  6895. }
  6896. }
  6897. }
  6898. }
  6899. } else if(!resolutionValue ||
  6900. !resolutionValue.height ||
  6901. !resolutionValue.width) {
  6902. resolution = "N/A";
  6903. } else {
  6904. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6905. }
  6906. var result = "<table style='width:100%'>" +
  6907. "<tr>" +
  6908. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6909. translate("connectionindicator.bitrate") + "</span></td>" +
  6910. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6911. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6912. uploadBitrate + "</td>" +
  6913. "</tr><tr>" +
  6914. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6915. translate("connectionindicator.packetloss") + "</span></td>" +
  6916. "<td>" + packetLoss + "</td>" +
  6917. "</tr><tr>" +
  6918. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6919. translate("connectionindicator.resolution") + "</span></td>" +
  6920. "<td>" + resolution + "</td></tr></table>";
  6921. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6922. result += "<div class=\"jitsipopover_showmore\" " +
  6923. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6924. // FIXME: we do not know local jid when this text is generated
  6925. //this.jid + "')\" data-i18n='connectionindicator." +
  6926. "local')\" data-i18n='connectionindicator." +
  6927. (this.showMoreValue ? "less" : "more") + "'>" +
  6928. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6929. "</div><br />";
  6930. }
  6931. if (this.showMoreValue) {
  6932. var downloadBandwidth, uploadBandwidth, transport;
  6933. if (this.bandwidth === null) {
  6934. downloadBandwidth = "N/A";
  6935. uploadBandwidth = "N/A";
  6936. } else {
  6937. downloadBandwidth = this.bandwidth.download?
  6938. this.bandwidth.download + " Kbps" :
  6939. "N/A";
  6940. uploadBandwidth = this.bandwidth.upload?
  6941. this.bandwidth.upload + " Kbps" :
  6942. "N/A";
  6943. }
  6944. if (!this.transport || this.transport.length === 0) {
  6945. transport = "<tr>" +
  6946. "<td><span class='jitsipopover_blue' " +
  6947. "data-i18n='connectionindicator.address'>" +
  6948. translate("connectionindicator.address") + "</span></td>" +
  6949. "<td> N/A</td></tr>";
  6950. } else {
  6951. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  6952. for(i = 0; i < this.transport.length; i++) {
  6953. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  6954. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  6955. var localIP =
  6956. ConnectionIndicator.getIP(this.transport[i].localip);
  6957. var localPort =
  6958. ConnectionIndicator.getPort(this.transport[i].localip);
  6959. if(data.remoteIP.indexOf(ip) == -1) {
  6960. data.remoteIP.push(ip);
  6961. }
  6962. if(data.remotePort.indexOf(port) == -1) {
  6963. data.remotePort.push(port);
  6964. }
  6965. if(data.localIP.indexOf(localIP) == -1) {
  6966. data.localIP.push(localIP);
  6967. }
  6968. if(data.localPort.indexOf(localPort) == -1) {
  6969. data.localPort.push(localPort);
  6970. }
  6971. }
  6972. var local_address_key = "connectionindicator.localaddress";
  6973. var remote_address_key = "connectionindicator.remoteaddress";
  6974. var localTransport =
  6975. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6976. local_address_key +"' data-i18n-options='" +
  6977. JSON.stringify({count: data.localIP.length}) + "'>" +
  6978. translate(local_address_key, {count: data.localIP.length}) +
  6979. "</span></td><td> " +
  6980. ConnectionIndicator.getStringFromArray(data.localIP) +
  6981. "</td></tr>";
  6982. transport =
  6983. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6984. remote_address_key + "' data-i18n-options='" +
  6985. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  6986. translate(remote_address_key,
  6987. {count: data.remoteIP.length}) +
  6988. "</span></td><td> " +
  6989. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  6990. "</td></tr>";
  6991. var key_remote = "connectionindicator.remoteport",
  6992. key_local = "connectionindicator.localport";
  6993. transport += "<tr>" +
  6994. "<td>" +
  6995. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  6996. "' data-i18n-options='" +
  6997. JSON.stringify({count: this.transport.length}) + "'>" +
  6998. translate(key_remote, {count: this.transport.length}) +
  6999. "</span></td><td>";
  7000. localTransport += "<tr>" +
  7001. "<td>" +
  7002. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7003. "' data-i18n-options='" +
  7004. JSON.stringify({count: this.transport.length}) + "'>" +
  7005. translate(key_local, {count: this.transport.length}) +
  7006. "</span></td><td>";
  7007. transport +=
  7008. ConnectionIndicator.getStringFromArray(data.remotePort);
  7009. localTransport +=
  7010. ConnectionIndicator.getStringFromArray(data.localPort);
  7011. transport += "</td></tr>";
  7012. transport += localTransport + "</td></tr>";
  7013. transport +="<tr>" +
  7014. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7015. translate("connectionindicator.transport") + "</span></td>" +
  7016. "<td>" + this.transport[0].type + "</td></tr>";
  7017. }
  7018. result += "<table style='width:100%'>" +
  7019. "<tr>" +
  7020. "<td>" +
  7021. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7022. translate("connectionindicator.bandwidth") + "</span>" +
  7023. "</td><td>" +
  7024. "<span class='jitsipopover_green'>&darr;</span>" +
  7025. downloadBandwidth +
  7026. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7027. uploadBandwidth + "</td></tr>";
  7028. result += transport + "</table>";
  7029. }
  7030. return result;
  7031. };
  7032. /**
  7033. * Shows or hide the additional information.
  7034. */
  7035. ConnectionIndicator.prototype.showMore = function () {
  7036. this.showMoreValue = !this.showMoreValue;
  7037. this.updatePopoverData();
  7038. };
  7039. function createIcon(classes) {
  7040. var icon = document.createElement("span");
  7041. for(var i in classes) {
  7042. icon.classList.add(classes[i]);
  7043. }
  7044. icon.appendChild(
  7045. document.createElement("i")).classList.add("icon-connection");
  7046. return icon;
  7047. }
  7048. /**
  7049. * Creates the indicator
  7050. */
  7051. ConnectionIndicator.prototype.create = function () {
  7052. this.connectionIndicatorContainer = document.createElement("div");
  7053. this.connectionIndicatorContainer.className = "connectionindicator";
  7054. this.connectionIndicatorContainer.style.display = "none";
  7055. this.videoContainer.container.appendChild(
  7056. this.connectionIndicatorContainer);
  7057. this.popover = new JitsiPopover(
  7058. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7059. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7060. APP.translation.translateString("connectionindicator.na") + "</div>",
  7061. skin: "black"});
  7062. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7063. createIcon(["connection", "connection_empty"]));
  7064. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7065. createIcon(["connection", "connection_full"]));
  7066. };
  7067. /**
  7068. * Removes the indicator
  7069. */
  7070. ConnectionIndicator.prototype.remove = function() {
  7071. if (this.connectionIndicatorContainer.parentNode) {
  7072. this.connectionIndicatorContainer.parentNode.removeChild(
  7073. this.connectionIndicatorContainer);
  7074. }
  7075. this.popover.forceHide();
  7076. };
  7077. /**
  7078. * Updates the data of the indicator
  7079. * @param percent the percent of connection quality
  7080. * @param object the statistics data.
  7081. */
  7082. ConnectionIndicator.prototype.updateConnectionQuality =
  7083. function (percent, object) {
  7084. if (percent === null) {
  7085. this.connectionIndicatorContainer.style.display = "none";
  7086. this.popover.forceHide();
  7087. return;
  7088. } else {
  7089. if(this.connectionIndicatorContainer.style.display == "none") {
  7090. this.connectionIndicatorContainer.style.display = "block";
  7091. this.videoContainer.updateIconPositions();
  7092. }
  7093. }
  7094. this.bandwidth = object.bandwidth;
  7095. this.bitrate = object.bitrate;
  7096. this.packetLoss = object.packetLoss;
  7097. this.transport = object.transport;
  7098. if (object.resolution) {
  7099. this.resolution = object.resolution;
  7100. }
  7101. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7102. if (percent >= quality) {
  7103. this.fullIcon.style.width =
  7104. ConnectionIndicator.connectionQualityValues[quality];
  7105. }
  7106. }
  7107. this.updatePopoverData();
  7108. };
  7109. /**
  7110. * Updates the resolution
  7111. * @param resolution the new resolution
  7112. */
  7113. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7114. this.resolution = resolution;
  7115. this.updatePopoverData();
  7116. };
  7117. /**
  7118. * Updates the content of the popover
  7119. */
  7120. ConnectionIndicator.prototype.updatePopoverData = function () {
  7121. this.popover.updateContent(
  7122. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7123. APP.translation.translateElement($(".connection_info"));
  7124. };
  7125. /**
  7126. * Hides the popover
  7127. */
  7128. ConnectionIndicator.prototype.hide = function () {
  7129. this.popover.forceHide();
  7130. };
  7131. /**
  7132. * Hides the indicator
  7133. */
  7134. ConnectionIndicator.prototype.hideIndicator = function () {
  7135. this.connectionIndicatorContainer.style.display = "none";
  7136. if(this.popover)
  7137. this.popover.forceHide();
  7138. };
  7139. module.exports = ConnectionIndicator;
  7140. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7141. /* global $, APP, Strophe, interfaceConfig */
  7142. var Avatar = require("../avatar/Avatar");
  7143. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7144. var UIUtil = require("../util/UIUtil");
  7145. var UIEvents = require("../../../service/UI/UIEvents");
  7146. var xmpp = require("../../xmpp/xmpp");
  7147. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7148. // FIXME: With Temasys we have to re-select everytime
  7149. //var video = $('#largeVideo');
  7150. var currentVideoWidth = null;
  7151. var currentVideoHeight = null;
  7152. // By default we use camera
  7153. var getVideoSize = getCameraVideoSize;
  7154. var getVideoPosition = getCameraVideoPosition;
  7155. /**
  7156. * The small video instance that is displayed in the large video
  7157. * @type {SmallVideo}
  7158. */
  7159. var currentSmallVideo = null;
  7160. /**
  7161. * Indicates whether the large video is enabled.
  7162. * @type {boolean}
  7163. */
  7164. var isEnabled = true;
  7165. /**
  7166. * Current large video state.
  7167. * Possible values - video, prezi or etherpad.
  7168. * @type {string}
  7169. */
  7170. var state = "video";
  7171. /**
  7172. * Returns the html element associated with the passed state of large video
  7173. * @param state the state.
  7174. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7175. */
  7176. function getContainerByState(state)
  7177. {
  7178. var selector = null;
  7179. switch (state)
  7180. {
  7181. case "video":
  7182. selector = "#largeVideo";
  7183. break;
  7184. case "etherpad":
  7185. selector = "#etherpad>iframe";
  7186. break;
  7187. case "prezi":
  7188. selector = "#presentation>iframe";
  7189. break;
  7190. }
  7191. return (selector !== null)? $(selector) : null;
  7192. }
  7193. /**
  7194. * Sets the size and position of the given video element.
  7195. *
  7196. * @param video the video element to position
  7197. * @param width the desired video width
  7198. * @param height the desired video height
  7199. * @param horizontalIndent the left and right indent
  7200. * @param verticalIndent the top and bottom indent
  7201. */
  7202. function positionVideo(video,
  7203. width,
  7204. height,
  7205. horizontalIndent,
  7206. verticalIndent,
  7207. animate) {
  7208. if (animate) {
  7209. video.animate({
  7210. width: width,
  7211. height: height,
  7212. top: verticalIndent,
  7213. bottom: verticalIndent,
  7214. left: horizontalIndent,
  7215. right: horizontalIndent
  7216. },
  7217. {
  7218. queue: false,
  7219. duration: 500
  7220. });
  7221. } else {
  7222. video.width(width);
  7223. video.height(height);
  7224. video.css({ top: verticalIndent + 'px',
  7225. bottom: verticalIndent + 'px',
  7226. left: horizontalIndent + 'px',
  7227. right: horizontalIndent + 'px'});
  7228. }
  7229. }
  7230. /**
  7231. * Returns an array of the video dimensions, so that it keeps it's aspect
  7232. * ratio and fits available area with it's larger dimension. This method
  7233. * ensures that whole video will be visible and can leave empty areas.
  7234. *
  7235. * @return an array with 2 elements, the video width and the video height
  7236. */
  7237. function getDesktopVideoSize(videoWidth,
  7238. videoHeight,
  7239. videoSpaceWidth,
  7240. videoSpaceHeight) {
  7241. if (!videoWidth)
  7242. videoWidth = currentVideoWidth;
  7243. if (!videoHeight)
  7244. videoHeight = currentVideoHeight;
  7245. var aspectRatio = videoWidth / videoHeight;
  7246. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7247. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7248. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7249. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7250. {
  7251. availableHeight = videoSpaceHeight;
  7252. availableWidth = availableHeight * aspectRatio;
  7253. }
  7254. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7255. {
  7256. availableWidth = videoSpaceWidth;
  7257. availableHeight = availableWidth / aspectRatio;
  7258. }
  7259. return [availableWidth, availableHeight];
  7260. }
  7261. /**
  7262. * Returns an array of the video horizontal and vertical indents,
  7263. * so that if fits its parent.
  7264. *
  7265. * @return an array with 2 elements, the horizontal indent and the vertical
  7266. * indent
  7267. */
  7268. function getCameraVideoPosition(videoWidth,
  7269. videoHeight,
  7270. videoSpaceWidth,
  7271. videoSpaceHeight) {
  7272. // Parent height isn't completely calculated when we position the video in
  7273. // full screen mode and this is why we use the screen height in this case.
  7274. // Need to think it further at some point and implement it properly.
  7275. var isFullScreen = document.fullScreen ||
  7276. document.mozFullScreen ||
  7277. document.webkitIsFullScreen;
  7278. if (isFullScreen)
  7279. videoSpaceHeight = window.innerHeight;
  7280. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7281. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7282. return [horizontalIndent, verticalIndent];
  7283. }
  7284. /**
  7285. * Returns an array of the video horizontal and vertical indents.
  7286. * Centers horizontally and top aligns vertically.
  7287. *
  7288. * @return an array with 2 elements, the horizontal indent and the vertical
  7289. * indent
  7290. */
  7291. function getDesktopVideoPosition(videoWidth,
  7292. videoHeight,
  7293. videoSpaceWidth,
  7294. videoSpaceHeight) {
  7295. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7296. var verticalIndent = 0;// Top aligned
  7297. return [horizontalIndent, verticalIndent];
  7298. }
  7299. /**
  7300. * Returns an array of the video dimensions, so that it covers the screen.
  7301. * It leaves no empty areas, but some parts of the video might not be visible.
  7302. *
  7303. * @return an array with 2 elements, the video width and the video height
  7304. */
  7305. function getCameraVideoSize(videoWidth,
  7306. videoHeight,
  7307. videoSpaceWidth,
  7308. videoSpaceHeight) {
  7309. if (!videoWidth)
  7310. videoWidth = currentVideoWidth;
  7311. if (!videoHeight)
  7312. videoHeight = currentVideoHeight;
  7313. var aspectRatio = videoWidth / videoHeight;
  7314. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7315. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7316. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7317. availableHeight = videoSpaceHeight;
  7318. availableWidth = availableHeight * aspectRatio;
  7319. }
  7320. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7321. availableWidth = videoSpaceWidth;
  7322. availableHeight = availableWidth / aspectRatio;
  7323. }
  7324. return [availableWidth, availableHeight];
  7325. }
  7326. /**
  7327. * Updates the src of the active speaker avatar
  7328. * @param jid of the current active speaker
  7329. */
  7330. function updateActiveSpeakerAvatarSrc() {
  7331. var avatar = $("#activeSpeakerAvatar")[0];
  7332. var jid = currentSmallVideo.peerJid;
  7333. var url = Avatar.getActiveSpeakerUrl(jid);
  7334. if (avatar.src === url)
  7335. return;
  7336. if (jid) {
  7337. avatar.src = url;
  7338. currentSmallVideo.showAvatar();
  7339. }
  7340. }
  7341. /**
  7342. * Change the video source of the large video.
  7343. * @param isVisible
  7344. */
  7345. function changeVideo(isVisible) {
  7346. if (!currentSmallVideo) {
  7347. console.error("Unable to change large video - no 'currentSmallVideo'");
  7348. return;
  7349. }
  7350. updateActiveSpeakerAvatarSrc();
  7351. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7352. var videoTransform = document.getElementById('largeVideo')
  7353. .style.webkitTransform;
  7354. var flipX = currentSmallVideo.flipX;
  7355. if (flipX && videoTransform !== 'scaleX(-1)') {
  7356. document.getElementById('largeVideo').style.webkitTransform =
  7357. "scaleX(-1)";
  7358. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7359. document.getElementById('largeVideo').style.webkitTransform =
  7360. "none";
  7361. }
  7362. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7363. // Change the way we'll be measuring and positioning large video
  7364. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7365. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7366. getCameraVideoPosition;
  7367. // Only if the large video is currently visible.
  7368. if (isVisible) {
  7369. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7370. $('#largeVideo').fadeIn(300);
  7371. }
  7372. }
  7373. /**
  7374. * Creates the html elements for the large video.
  7375. */
  7376. function createLargeVideoHTML()
  7377. {
  7378. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7379. html += '<div id="presentation"></div>' +
  7380. '<div id="etherpad"></div>' +
  7381. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7382. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7383. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7384. '<span data-i18n="poweredby"></span> jitsi.org' +
  7385. '</a>'+
  7386. '<div id="activeSpeaker">' +
  7387. '<img id="activeSpeakerAvatar" src=""/>' +
  7388. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7389. '</div>' +
  7390. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7391. '<span id="videoConnectionMessage"></span>';
  7392. html += '</div>';
  7393. $(html).prependTo("#videospace");
  7394. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7395. var leftWatermarkDiv
  7396. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7397. leftWatermarkDiv.css({display: 'block'});
  7398. leftWatermarkDiv.parent().get(0).href
  7399. = interfaceConfig.JITSI_WATERMARK_LINK;
  7400. }
  7401. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7402. var rightWatermarkDiv
  7403. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7404. rightWatermarkDiv.css({display: 'block'});
  7405. rightWatermarkDiv.parent().get(0).href
  7406. = interfaceConfig.BRAND_WATERMARK_LINK;
  7407. rightWatermarkDiv.get(0).style.backgroundImage
  7408. = "url(images/rightwatermark.png)";
  7409. }
  7410. if (interfaceConfig.SHOW_POWERED_BY) {
  7411. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7412. }
  7413. if (!RTCBrowserType.isIExplorer()) {
  7414. $('#largeVideo').volume = 0;
  7415. }
  7416. }
  7417. var LargeVideo = {
  7418. init: function (VideoLayout, emitter) {
  7419. if(!isEnabled)
  7420. return;
  7421. createLargeVideoHTML();
  7422. this.VideoLayout = VideoLayout;
  7423. this.eventEmitter = emitter;
  7424. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7425. var self = this;
  7426. // Listen for large video size updates
  7427. var largeVideo = $('#largeVideo')[0];
  7428. var onplaying = function (arg1, arg2, arg3) {
  7429. // re-select
  7430. if (RTCBrowserType.isTemasysPluginUsed())
  7431. largeVideo = $('#largeVideo')[0];
  7432. currentVideoWidth = largeVideo.videoWidth;
  7433. currentVideoHeight = largeVideo.videoHeight;
  7434. self.position(currentVideoWidth, currentVideoHeight);
  7435. };
  7436. largeVideo.onplaying = onplaying;
  7437. },
  7438. /**
  7439. * Indicates if the large video is currently visible.
  7440. *
  7441. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7442. */
  7443. isLargeVideoVisible: function() {
  7444. return $('#largeVideo').is(':visible');
  7445. },
  7446. /**
  7447. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7448. */
  7449. isCurrentlyOnLarge: function (resourceJid) {
  7450. return currentSmallVideo && resourceJid &&
  7451. currentSmallVideo.getResourceJid() === resourceJid;
  7452. },
  7453. /**
  7454. * Updates the large video with the given new video source.
  7455. */
  7456. updateLargeVideo: function (resourceJid, forceUpdate) {
  7457. if(!isEnabled)
  7458. return;
  7459. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7460. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7461. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7462. $('#activeSpeaker').css('visibility', 'hidden');
  7463. var oldSmallVideo = null;
  7464. if (currentSmallVideo) {
  7465. oldSmallVideo = currentSmallVideo;
  7466. }
  7467. currentSmallVideo = newSmallVideo;
  7468. var oldJid = null;
  7469. if (oldSmallVideo)
  7470. oldJid = oldSmallVideo.peerJid;
  7471. if (oldJid !== resourceJid) {
  7472. // we want the notification to trigger even if userJid is undefined,
  7473. // or null.
  7474. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7475. }
  7476. if (RTCBrowserType.isSafari()) {
  7477. // FIXME In Safari fadeOut works only for the first time
  7478. changeVideo(this.isLargeVideoVisible());
  7479. } else {
  7480. $('#largeVideo').fadeOut(300,
  7481. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7482. }
  7483. } else {
  7484. if (currentSmallVideo) {
  7485. currentSmallVideo.showAvatar();
  7486. }
  7487. }
  7488. },
  7489. /**
  7490. * Shows/hides the large video.
  7491. */
  7492. setLargeVideoVisible: function(isVisible) {
  7493. if(!isEnabled)
  7494. return;
  7495. if (isVisible) {
  7496. $('#largeVideo').css({visibility: 'visible'});
  7497. $('.watermark').css({visibility: 'visible'});
  7498. if(currentSmallVideo)
  7499. currentSmallVideo.enableDominantSpeaker(true);
  7500. }
  7501. else {
  7502. $('#largeVideo').css({visibility: 'hidden'});
  7503. $('#activeSpeaker').css('visibility', 'hidden');
  7504. $('.watermark').css({visibility: 'hidden'});
  7505. if(currentSmallVideo)
  7506. currentSmallVideo.enableDominantSpeaker(false);
  7507. }
  7508. },
  7509. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7510. if (!isEnabled)
  7511. return;
  7512. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7513. {
  7514. var isDesktop = newVideoType === 'screen';
  7515. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7516. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7517. : getCameraVideoPosition;
  7518. this.position(null, null);
  7519. }
  7520. },
  7521. /**
  7522. * Positions the large video.
  7523. *
  7524. * @param videoWidth the stream video width
  7525. * @param videoHeight the stream video height
  7526. */
  7527. position: function (videoWidth, videoHeight,
  7528. videoSpaceWidth, videoSpaceHeight, animate) {
  7529. if(!isEnabled)
  7530. return;
  7531. if(!videoSpaceWidth)
  7532. videoSpaceWidth = $('#videospace').width();
  7533. if(!videoSpaceHeight)
  7534. videoSpaceHeight = window.innerHeight;
  7535. var videoSize = getVideoSize(videoWidth,
  7536. videoHeight,
  7537. videoSpaceWidth,
  7538. videoSpaceHeight);
  7539. var largeVideoWidth = videoSize[0];
  7540. var largeVideoHeight = videoSize[1];
  7541. var videoPosition = getVideoPosition(largeVideoWidth,
  7542. largeVideoHeight,
  7543. videoSpaceWidth,
  7544. videoSpaceHeight);
  7545. var horizontalIndent = videoPosition[0];
  7546. var verticalIndent = videoPosition[1];
  7547. positionVideo($('#largeVideo'),
  7548. largeVideoWidth,
  7549. largeVideoHeight,
  7550. horizontalIndent, verticalIndent, animate);
  7551. },
  7552. /**
  7553. * Resizes the large html elements.
  7554. * @param animate boolean property that indicates whether the resize should be animated or not.
  7555. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  7556. * If that parameter is null the method will check the chat pannel visibility.
  7557. * @param completeFunction a function to be called when the video space is resized
  7558. * @returns {*[]} array with the current width and height values of the largeVideo html element.
  7559. */
  7560. resize: function (animate, isVisible, completeFunction) {
  7561. if(!isEnabled)
  7562. return;
  7563. var availableHeight = window.innerHeight;
  7564. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7565. if (availableWidth < 0 || availableHeight < 0) return;
  7566. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7567. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7568. $('#activeSpeaker').css('top', top);
  7569. this.VideoLayout.resizeVideoSpace(animate, isVisible, completeFunction);
  7570. if(animate) {
  7571. $('#largeVideoContainer').animate({
  7572. width: availableWidth,
  7573. height: availableHeight
  7574. },
  7575. {
  7576. queue: false,
  7577. duration: 500
  7578. });
  7579. } else {
  7580. $('#largeVideoContainer').width(availableWidth);
  7581. $('#largeVideoContainer').height(availableHeight);
  7582. }
  7583. return [availableWidth, availableHeight];
  7584. },
  7585. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7586. if(!isEnabled)
  7587. return;
  7588. var size = this.resize(true, isVisible, completeFunction);
  7589. this.position(null, null, size[0], size[1], true);
  7590. },
  7591. getResourceJid: function () {
  7592. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7593. },
  7594. updateAvatar: function (resourceJid) {
  7595. if(!isEnabled)
  7596. return;
  7597. if (resourceJid === this.getResourceJid()) {
  7598. updateActiveSpeakerAvatarSrc();
  7599. }
  7600. },
  7601. showAvatar: function (resourceJid, show) {
  7602. if(!isEnabled)
  7603. return;
  7604. if(this.getResourceJid() === resourceJid && state === "video") {
  7605. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7606. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7607. return true;
  7608. }
  7609. return false;
  7610. },
  7611. /**
  7612. * Disables the large video
  7613. */
  7614. disable: function () {
  7615. isEnabled = false;
  7616. },
  7617. /**
  7618. * Enables the large video
  7619. */
  7620. enable: function () {
  7621. isEnabled = true;
  7622. },
  7623. /**
  7624. * Returns true if the video is enabled.
  7625. */
  7626. isEnabled: function () {
  7627. return isEnabled;
  7628. },
  7629. /**
  7630. * Creates the iframe used by the etherpad
  7631. * @param src the value for src attribute
  7632. * @param onloadHandler handler executed when the iframe loads it content
  7633. * @returns {HTMLElement} the iframe
  7634. */
  7635. createEtherpadIframe: function (src, onloadHandler) {
  7636. if(!isEnabled)
  7637. return;
  7638. var etherpadIFrame = document.createElement('iframe');
  7639. etherpadIFrame.src = src;
  7640. etherpadIFrame.frameBorder = 0;
  7641. etherpadIFrame.scrolling = "no";
  7642. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7643. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7644. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7645. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7646. etherpadIFrame.onload = onloadHandler;
  7647. return etherpadIFrame;
  7648. },
  7649. /**
  7650. * Changes the state of the large video.
  7651. * Possible values - video, prezi, etherpad.
  7652. * @param newState - the new state
  7653. */
  7654. setState: function (newState) {
  7655. if(state === newState)
  7656. return;
  7657. var currentContainer = getContainerByState(state);
  7658. if(!currentContainer)
  7659. return;
  7660. var self = this;
  7661. var oldState = state;
  7662. switch (newState)
  7663. {
  7664. case "etherpad":
  7665. $('#activeSpeaker').css('visibility', 'hidden');
  7666. currentContainer.fadeOut(300, function () {
  7667. if (oldState === "prezi") {
  7668. currentContainer.css({opacity: '0'});
  7669. $('#reloadPresentation').css({display: 'none'});
  7670. }
  7671. else {
  7672. self.setLargeVideoVisible(false);
  7673. }
  7674. });
  7675. $('#etherpad>iframe').fadeIn(300, function () {
  7676. document.body.style.background = '#eeeeee';
  7677. $('#etherpad>iframe').css({visibility: 'visible'});
  7678. $('#etherpad').css({zIndex: 2});
  7679. });
  7680. break;
  7681. case "prezi":
  7682. var prezi = $('#presentation>iframe');
  7683. currentContainer.fadeOut(300, function() {
  7684. document.body.style.background = 'black';
  7685. });
  7686. prezi.fadeIn(300, function() {
  7687. prezi.css({opacity:'1'});
  7688. ToolbarToggler.dockToolbar(true);//fix that
  7689. self.setLargeVideoVisible(false);
  7690. $('#etherpad>iframe').css({visibility: 'hidden'});
  7691. $('#etherpad').css({zIndex: 0});
  7692. });
  7693. $('#activeSpeaker').css('visibility', 'hidden');
  7694. break;
  7695. case "video":
  7696. currentContainer.fadeOut(300, function () {
  7697. $('#presentation>iframe').css({opacity:'0'});
  7698. $('#reloadPresentation').css({display:'none'});
  7699. $('#etherpad>iframe').css({visibility: 'hidden'});
  7700. $('#etherpad').css({zIndex: 0});
  7701. document.body.style.background = 'black';
  7702. ToolbarToggler.dockToolbar(false);//fix that
  7703. });
  7704. $('#largeVideo').fadeIn(300, function () {
  7705. self.setLargeVideoVisible(true);
  7706. });
  7707. break;
  7708. }
  7709. state = newState;
  7710. },
  7711. /**
  7712. * Returns the current state of the large video.
  7713. * @returns {string} the current state - video, prezi or etherpad.
  7714. */
  7715. getState: function () {
  7716. return state;
  7717. },
  7718. /**
  7719. * Sets hover handlers for the large video container div.
  7720. *
  7721. * @param inHandler
  7722. * @param outHandler
  7723. */
  7724. setHover: function(inHandler, outHandler)
  7725. {
  7726. $('#largeVideoContainer').hover(inHandler, outHandler);
  7727. },
  7728. /**
  7729. * Enables/disables the filter indicating a video problem to the user.
  7730. *
  7731. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  7732. */
  7733. enableVideoProblemFilter: function (enable) {
  7734. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  7735. }
  7736. };
  7737. module.exports = LargeVideo;
  7738. },{"../../../service/UI/UIEvents":107,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":67,"../avatar/Avatar":16,"../toolbars/ToolbarToggler":29,"../util/UIUtil":33}],36:[function(require,module,exports){
  7739. /* global $, interfaceConfig, APP */
  7740. var SmallVideo = require("./SmallVideo");
  7741. var ConnectionIndicator = require("./ConnectionIndicator");
  7742. var NicknameHandler = require("../util/NicknameHandler");
  7743. var UIUtil = require("../util/UIUtil");
  7744. var LargeVideo = require("./LargeVideo");
  7745. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7746. function LocalVideo(VideoLayout) {
  7747. this.videoSpanId = "localVideoContainer";
  7748. this.container = $("#localVideoContainer").get(0);
  7749. this.VideoLayout = VideoLayout;
  7750. this.flipX = true;
  7751. this.isLocal = true;
  7752. this.peerJid = null;
  7753. }
  7754. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7755. LocalVideo.prototype.constructor = LocalVideo;
  7756. /**
  7757. * Creates the edit display name button.
  7758. *
  7759. * @returns {object} the edit button
  7760. */
  7761. function createEditDisplayNameButton() {
  7762. var editButton = document.createElement('a');
  7763. editButton.className = 'displayname';
  7764. UIUtil.setTooltip(editButton,
  7765. "videothumbnail.editnickname",
  7766. "top");
  7767. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7768. return editButton;
  7769. }
  7770. /**
  7771. * Sets the display name for the given video span id.
  7772. */
  7773. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7774. if (!this.container) {
  7775. console.warn(
  7776. "Unable to set displayName - " + this.videoSpanId +
  7777. " does not exist");
  7778. return;
  7779. }
  7780. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7781. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7782. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7783. var meHTML;
  7784. // If we already have a display name for this video.
  7785. if (nameSpan.length > 0) {
  7786. if (nameSpan.text() !== displayName) {
  7787. if (displayName && displayName.length > 0) {
  7788. meHTML = APP.translation.generateTranslationHTML("me");
  7789. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7790. } else {
  7791. $('#localDisplayName').html(defaultLocalDisplayName);
  7792. }
  7793. }
  7794. } else {
  7795. var editButton = createEditDisplayNameButton();
  7796. nameSpan = document.createElement('span');
  7797. nameSpan.className = 'displayname';
  7798. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7799. if (displayName && displayName.length > 0) {
  7800. meHTML = APP.translation.generateTranslationHTML("me");
  7801. nameSpan.innerHTML = displayName + meHTML;
  7802. }
  7803. else {
  7804. nameSpan.innerHTML = defaultLocalDisplayName;
  7805. }
  7806. nameSpan.id = 'localDisplayName';
  7807. this.container.appendChild(editButton);
  7808. //translates popover of edit button
  7809. APP.translation.translateElement($("a.displayname"));
  7810. var editableText = document.createElement('input');
  7811. editableText.className = 'displayname';
  7812. editableText.type = 'text';
  7813. editableText.id = 'editDisplayName';
  7814. if (displayName && displayName.length) {
  7815. editableText.value = displayName;
  7816. }
  7817. var defaultNickname = APP.translation.translateString(
  7818. "defaultNickname", {name: "Jane Pink"});
  7819. editableText.setAttribute('style', 'display:none;');
  7820. editableText.setAttribute('data-18n',
  7821. '[placeholder]defaultNickname');
  7822. editableText.setAttribute("data-i18n-options",
  7823. JSON.stringify({name: "Jane Pink"}));
  7824. editableText.setAttribute("placeholder", defaultNickname);
  7825. this.container.appendChild(editableText);
  7826. var self = this;
  7827. $('#localVideoContainer .displayname')
  7828. .bind("click", function (e) {
  7829. var editDisplayName = $('#editDisplayName');
  7830. e.preventDefault();
  7831. e.stopPropagation();
  7832. $('#localDisplayName').hide();
  7833. editDisplayName.show();
  7834. editDisplayName.focus();
  7835. editDisplayName.select();
  7836. editDisplayName.one("focusout", function (e) {
  7837. self.VideoLayout.inputDisplayNameHandler(this.value);
  7838. });
  7839. editDisplayName.on('keydown', function (e) {
  7840. if (e.keyCode === 13) {
  7841. e.preventDefault();
  7842. self.VideoLayout.inputDisplayNameHandler(this.value);
  7843. }
  7844. });
  7845. });
  7846. }
  7847. };
  7848. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7849. NicknameHandler.setNickname(name);
  7850. var localDisplayName = $('#localDisplayName');
  7851. if (!localDisplayName.is(":visible")) {
  7852. if (NicknameHandler.getNickname()) {
  7853. var meHTML = APP.translation.generateTranslationHTML("me");
  7854. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  7855. meHTML + ")");
  7856. } else {
  7857. var defaultHTML = APP.translation.generateTranslationHTML(
  7858. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7859. localDisplayName .html(defaultHTML);
  7860. }
  7861. localDisplayName.show();
  7862. }
  7863. $('#editDisplayName').hide();
  7864. };
  7865. LocalVideo.prototype.createConnectionIndicator = function() {
  7866. if(this.connectionIndicator)
  7867. return;
  7868. this.connectionIndicator = new ConnectionIndicator(this, null);
  7869. };
  7870. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7871. var self = this;
  7872. function localVideoClick(event) {
  7873. // FIXME: with Temasys plugin event arg is not an event, but
  7874. // the clicked object itself, so we have to skip this call
  7875. if (event.stopPropagation) {
  7876. event.stopPropagation();
  7877. }
  7878. self.VideoLayout.handleVideoThumbClicked(
  7879. false,
  7880. APP.xmpp.myResource());
  7881. }
  7882. var localVideoContainerSelector = $('#localVideoContainer');
  7883. localVideoContainerSelector.off('click');
  7884. localVideoContainerSelector.on('click', localVideoClick);
  7885. // Add hover handler
  7886. localVideoContainerSelector.hover(
  7887. function() {
  7888. self.showDisplayName(true);
  7889. },
  7890. function() {
  7891. if (!LargeVideo.isLargeVideoVisible() ||
  7892. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  7893. self.showDisplayName(false);
  7894. }
  7895. }
  7896. );
  7897. if(isMuted) {
  7898. APP.UI.setVideoMute(true);
  7899. return;
  7900. }
  7901. this.flipX = stream.videoType != "screen";
  7902. var localVideo = document.createElement('video');
  7903. localVideo.id = 'localVideo_' +
  7904. APP.RTC.getStreamID(stream.getOriginalStream());
  7905. if (!RTCBrowserType.isIExplorer()) {
  7906. localVideo.autoplay = true;
  7907. localVideo.volume = 0; // is it required if audio is separated ?
  7908. }
  7909. localVideo.oncontextmenu = function () { return false; };
  7910. var localVideoContainer = document.getElementById('localVideoWrapper');
  7911. localVideoContainer.appendChild(localVideo);
  7912. var localVideoSelector = $('#' + localVideo.id);
  7913. // Add click handler to both video and video wrapper elements in case
  7914. // there's no video.
  7915. // onclick has to be used with Temasys plugin
  7916. localVideo.onclick = localVideoClick;
  7917. if (this.flipX) {
  7918. localVideoSelector.addClass("flipVideoX");
  7919. }
  7920. // Attach WebRTC stream
  7921. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7922. // Add stream ended handler
  7923. stream.getOriginalStream().onended = function () {
  7924. // We have to re-select after attach when Temasys plugin is used,
  7925. // because <video> element is replaced with <object>
  7926. localVideo = $('#' + localVideo.id)[0];
  7927. localVideoContainer.removeChild(localVideo);
  7928. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7929. };
  7930. };
  7931. LocalVideo.prototype.joined = function (jid) {
  7932. this.peerJid = jid;
  7933. };
  7934. LocalVideo.prototype.getResourceJid = function () {
  7935. var myResource = APP.xmpp.myResource();
  7936. if (!myResource) {
  7937. console.error("Requested local resource before we're in the MUC");
  7938. }
  7939. return myResource;
  7940. };
  7941. module.exports = LocalVideo;
  7942. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7943. /* global $, APP, require, Strophe, interfaceConfig */
  7944. var ConnectionIndicator = require("./ConnectionIndicator");
  7945. var SmallVideo = require("./SmallVideo");
  7946. var AudioLevels = require("../audio_levels/AudioLevels");
  7947. var LargeVideo = require("./LargeVideo");
  7948. var Avatar = require("../avatar/Avatar");
  7949. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7950. function RemoteVideo(peerJid, VideoLayout) {
  7951. this.peerJid = peerJid;
  7952. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7953. this.videoSpanId = 'participant_' + this.resourceJid;
  7954. this.VideoLayout = VideoLayout;
  7955. this.addRemoteVideoContainer();
  7956. this.connectionIndicator = new ConnectionIndicator(
  7957. this, this.peerJid);
  7958. this.setDisplayName();
  7959. var nickfield = document.createElement('span');
  7960. nickfield.className = "nick";
  7961. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7962. this.container.appendChild(nickfield);
  7963. this.flipX = false;
  7964. this.isLocal = false;
  7965. }
  7966. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7967. RemoteVideo.prototype.constructor = RemoteVideo;
  7968. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7969. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7970. if (APP.xmpp.isModerator())
  7971. this.addRemoteVideoMenu();
  7972. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7973. return this.container;
  7974. };
  7975. /**
  7976. * Adds the remote video menu element for the given <tt>jid</tt> in the
  7977. * given <tt>parentElement</tt>.
  7978. *
  7979. * @param jid the jid indicating the video for which we're adding a menu.
  7980. * @param parentElement the parent element where this menu will be added
  7981. */
  7982. if(!config.filmStripOnly) {
  7983. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  7984. var spanElement = document.createElement('span');
  7985. spanElement.className = 'remotevideomenu';
  7986. this.container.appendChild(spanElement);
  7987. var menuElement = document.createElement('i');
  7988. menuElement.className = 'fa fa-angle-down';
  7989. menuElement.title = 'Remote user controls';
  7990. spanElement.appendChild(menuElement);
  7991. var popupmenuElement = document.createElement('ul');
  7992. popupmenuElement.className = 'popupmenu';
  7993. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  7994. spanElement.appendChild(popupmenuElement);
  7995. var muteMenuItem = document.createElement('li');
  7996. var muteLinkItem = document.createElement('a');
  7997. var mutedIndicator = "<i style='float:left;' " +
  7998. "class='icon-mic-disabled'></i>";
  7999. if (!this.isMuted) {
  8000. muteLinkItem.innerHTML = mutedIndicator +
  8001. " <div style='width: 90px;margin-left: 20px;' " +
  8002. "data-i18n='videothumbnail.domute'></div>";
  8003. muteLinkItem.className = 'mutelink';
  8004. }
  8005. else {
  8006. muteLinkItem.innerHTML = mutedIndicator +
  8007. " <div style='width: 90px;margin-left: 20px;' " +
  8008. "data-i18n='videothumbnail.muted'></div>";
  8009. muteLinkItem.className = 'mutelink disabled';
  8010. }
  8011. var self = this;
  8012. muteLinkItem.onclick = function(){
  8013. if ($(this).attr('disabled') != undefined) {
  8014. event.preventDefault();
  8015. }
  8016. var isMute = self.isMuted == true;
  8017. APP.xmpp.setMute(self.peerJid, !isMute);
  8018. popupmenuElement.setAttribute('style', 'display:none;');
  8019. if (isMute) {
  8020. this.innerHTML = mutedIndicator +
  8021. " <div style='width: 90px;margin-left: 20px;' " +
  8022. "data-i18n='videothumbnail.muted'></div>";
  8023. this.className = 'mutelink disabled';
  8024. }
  8025. else {
  8026. this.innerHTML = mutedIndicator +
  8027. " <div style='width: 90px;margin-left: 20px;' " +
  8028. "data-i18n='videothumbnail.domute'></div>";
  8029. this.className = 'mutelink';
  8030. }
  8031. };
  8032. muteMenuItem.appendChild(muteLinkItem);
  8033. popupmenuElement.appendChild(muteMenuItem);
  8034. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8035. var ejectMenuItem = document.createElement('li');
  8036. var ejectLinkItem = document.createElement('a');
  8037. var ejectText = "<div style='width: 90px;margin-left: 20px;' " +
  8038. "data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8039. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8040. ejectLinkItem.onclick = function(){
  8041. APP.xmpp.eject(self.peerJid);
  8042. popupmenuElement.setAttribute('style', 'display:none;');
  8043. };
  8044. ejectMenuItem.appendChild(ejectLinkItem);
  8045. popupmenuElement.appendChild(ejectMenuItem);
  8046. var paddingSpan = document.createElement('span');
  8047. paddingSpan.className = 'popupmenuPadding';
  8048. popupmenuElement.appendChild(paddingSpan);
  8049. APP.translation.translateElement(
  8050. $("#" + popupmenuElement.id + " > li > a > div"));
  8051. };
  8052. } else {
  8053. RemoteVideo.prototype.addRemoteVideoMenu = function() {}
  8054. }
  8055. /**
  8056. * Removes the remote stream element corresponding to the given stream and
  8057. * parent container.
  8058. *
  8059. * @param stream the stream
  8060. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8061. */
  8062. RemoteVideo.prototype.removeRemoteStreamElement =
  8063. function (stream, isVideo, id) {
  8064. if (!this.container)
  8065. return false;
  8066. var select = null;
  8067. if (isVideo) {
  8068. select = $('#' + id);
  8069. }
  8070. else
  8071. select = $('#' + this.videoSpanId + '>audio');
  8072. select.remove();
  8073. console.info((isVideo ? "Video" : "Audio") +
  8074. " removed " + this.getResourceJid(), select);
  8075. if (isVideo)
  8076. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8077. };
  8078. /**
  8079. * Removes RemoteVideo from the page.
  8080. */
  8081. RemoteVideo.prototype.remove = function () {
  8082. console.log("Remove thumbnail", this.peerJid);
  8083. this.removeConnectionIndicator();
  8084. // Remove whole container
  8085. if (this.container.parentNode)
  8086. this.container.parentNode.removeChild(this.container);
  8087. };
  8088. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8089. var isVideo = stream.getVideoTracks().length > 0;
  8090. if (!isVideo || stream.id === 'mixedmslabel') {
  8091. return;
  8092. }
  8093. var self = this;
  8094. var resourceJid = this.getResourceJid();
  8095. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8096. // when video playback starts
  8097. var onPlayingHandler = function () {
  8098. // FIXME: why do i have to do this for FF?
  8099. if (RTCBrowserType.isFirefox()) {
  8100. APP.RTC.attachMediaStream(sel, stream);
  8101. }
  8102. if (RTCBrowserType.isTemasysPluginUsed()) {
  8103. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8104. }
  8105. self.VideoLayout.videoactive(sel, resourceJid);
  8106. sel[0].onplaying = null;
  8107. if (RTCBrowserType.isTemasysPluginUsed()) {
  8108. // 'currentTime' is used to check if the video has started
  8109. // and the value is not set by the plugin, so we do it
  8110. sel[0].currentTime = 1;
  8111. }
  8112. };
  8113. sel[0].onplaying = onPlayingHandler;
  8114. };
  8115. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8116. if (!this.container)
  8117. return;
  8118. var self = this;
  8119. var isVideo = stream.getVideoTracks().length > 0;
  8120. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8121. var newElementId = streamElement.id;
  8122. this.container.appendChild(streamElement);
  8123. var sel = $('#' + newElementId);
  8124. sel.hide();
  8125. // If the container is currently visible we attach the stream.
  8126. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8127. this.waitForPlayback(sel, stream);
  8128. APP.RTC.attachMediaStream(sel, stream);
  8129. }
  8130. stream.onended = function () {
  8131. console.log('stream ended', this);
  8132. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8133. };
  8134. // Name of video element name is different for IE/Safari
  8135. var videoElem = APP.RTC.getVideoElementName();
  8136. // Add click handler.
  8137. var onClickHandler = function (event) {
  8138. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8139. // On IE we need to populate this handler on video <object>
  8140. // and it does not give event instance as an argument,
  8141. // so we check here for methods.
  8142. if (event.stopPropagation && event.preventDefault) {
  8143. event.stopPropagation();
  8144. event.preventDefault();
  8145. }
  8146. return false;
  8147. };
  8148. this.container.onclick = onClickHandler;
  8149. // reselect
  8150. if (RTCBrowserType.isTemasysPluginUsed())
  8151. sel = $('#' + newElementId);
  8152. sel[0].onclick = onClickHandler;
  8153. //FIXME
  8154. // Add hover handler
  8155. $(this.container).hover(
  8156. function() {
  8157. self.showDisplayName(true);
  8158. },
  8159. function() {
  8160. // If the video has been "pinned" by the user we want to
  8161. // keep the display name on place.
  8162. if (!LargeVideo.isLargeVideoVisible() ||
  8163. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8164. self.showDisplayName(false);
  8165. }
  8166. );
  8167. },
  8168. /**
  8169. * Show/hide peer container for the given resourceJid.
  8170. */
  8171. RemoteVideo.prototype.showPeerContainer = function (state) {
  8172. if (!this.container)
  8173. return;
  8174. var isHide = state === 'hide';
  8175. var resizeThumbnails = false;
  8176. if (!isHide) {
  8177. if (!$(this.container).is(':visible')) {
  8178. resizeThumbnails = true;
  8179. $(this.container).show();
  8180. }
  8181. this.showAvatar(state !== 'show');
  8182. }
  8183. else if ($(this.container).is(':visible') && isHide)
  8184. {
  8185. resizeThumbnails = true;
  8186. $(this.container).hide();
  8187. if(this.connectionIndicator)
  8188. this.connectionIndicator.hide();
  8189. }
  8190. if (resizeThumbnails) {
  8191. this.VideoLayout.resizeThumbnails();
  8192. }
  8193. // We want to be able to pin a participant from the contact list, even
  8194. // if he's not in the lastN set!
  8195. // ContactList.setClickable(resourceJid, !isHide);
  8196. };
  8197. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8198. if (this.connectionIndicator)
  8199. this.connectionIndicator.remove();
  8200. };
  8201. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8202. if (this.connectionIndicator)
  8203. this.connectionIndicator.hide();
  8204. };
  8205. /**
  8206. * Updates the remote video menu.
  8207. *
  8208. * @param jid the jid indicating the video for which we're adding a menu.
  8209. * @param isMuted indicates the current mute state
  8210. */
  8211. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8212. var muteMenuItem
  8213. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8214. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8215. if (muteMenuItem.length) {
  8216. var muteLink = muteMenuItem.get(0);
  8217. if (isMuted === 'true') {
  8218. muteLink.innerHTML = mutedIndicator + ' Muted';
  8219. muteLink.className = 'mutelink disabled';
  8220. }
  8221. else {
  8222. muteLink.innerHTML = mutedIndicator + ' Mute';
  8223. muteLink.className = 'mutelink';
  8224. }
  8225. }
  8226. };
  8227. /**
  8228. * Sets the display name for the given video span id.
  8229. */
  8230. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8231. if (!this.container) {
  8232. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8233. " does not exist");
  8234. return;
  8235. }
  8236. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8237. // If we already have a display name for this video.
  8238. if (nameSpan.length > 0) {
  8239. if (displayName && displayName.length > 0) {
  8240. $('#' + this.videoSpanId + '_name').html(displayName);
  8241. }
  8242. else if (key && key.length > 0) {
  8243. var nameHtml = APP.translation.generateTranslationHTML(key);
  8244. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8245. }
  8246. else
  8247. $('#' + this.videoSpanId + '_name').text(
  8248. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8249. } else {
  8250. nameSpan = document.createElement('span');
  8251. nameSpan.className = 'displayname';
  8252. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8253. if (displayName && displayName.length > 0) {
  8254. nameSpan.innerText = displayName;
  8255. }
  8256. else
  8257. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8258. nameSpan.id = this.videoSpanId + '_name';
  8259. }
  8260. };
  8261. /**
  8262. * Removes remote video menu element from video element identified by
  8263. * given <tt>videoElementId</tt>.
  8264. *
  8265. * @param videoElementId the id of local or remote video element.
  8266. */
  8267. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8268. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8269. if (menuSpan.length) {
  8270. menuSpan.remove();
  8271. }
  8272. };
  8273. RemoteVideo.prototype.getResourceJid = function () {
  8274. if (!this.resourceJid) {
  8275. console.error("Undefined resource jid");
  8276. }
  8277. return this.resourceJid;
  8278. };
  8279. RemoteVideo.createContainer = function (spanId) {
  8280. var container = document.createElement('span');
  8281. container.id = spanId;
  8282. container.className = 'videocontainer';
  8283. var remotes = document.getElementById('remoteVideos');
  8284. return remotes.appendChild(container);
  8285. };
  8286. module.exports = RemoteVideo;
  8287. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8288. /* global $, APP, require */
  8289. var Avatar = require("../avatar/Avatar");
  8290. var UIUtil = require("../util/UIUtil");
  8291. var LargeVideo = require("./LargeVideo");
  8292. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8293. function SmallVideo() {
  8294. this.isMuted = false;
  8295. this.hasAvatar = false;
  8296. }
  8297. function setVisibility(selector, show) {
  8298. if (selector && selector.length > 0) {
  8299. selector.css("visibility", show ? "visible" : "hidden");
  8300. }
  8301. }
  8302. SmallVideo.prototype.showDisplayName = function(isShow) {
  8303. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8304. if (isShow) {
  8305. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8306. nameSpan.setAttribute("style", "display:inline-block;");
  8307. }
  8308. else {
  8309. if (nameSpan)
  8310. nameSpan.setAttribute("style", "display:none;");
  8311. }
  8312. };
  8313. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8314. if(!this.container)
  8315. return;
  8316. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8317. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8318. noMic.remove();
  8319. noVideo.remove();
  8320. if (!devices.audio) {
  8321. this.container.appendChild(
  8322. document.createElement("div")).setAttribute("class", "noMic");
  8323. }
  8324. if (!devices.video) {
  8325. this.container.appendChild(
  8326. document.createElement("div")).setAttribute("class", "noVideo");
  8327. }
  8328. if (!devices.audio && !devices.video) {
  8329. noMic.css("background-position", "75%");
  8330. noVideo.css("background-position", "25%");
  8331. noVideo.css("background-color", "transparent");
  8332. }
  8333. };
  8334. /**
  8335. * Sets the type of the video displayed by this instance.
  8336. * @param videoType 'camera' or 'screen'
  8337. */
  8338. SmallVideo.prototype.setVideoType = function (videoType) {
  8339. this.videoType = videoType;
  8340. };
  8341. /**
  8342. * Returns the type of the video displayed by this instance.
  8343. * @returns {String} 'camera', 'screen' or undefined.
  8344. */
  8345. SmallVideo.prototype.getVideoType = function () {
  8346. return this.videoType;
  8347. };
  8348. /**
  8349. * Shows the presence status message for the given video.
  8350. */
  8351. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8352. if (!this.container) {
  8353. // No container
  8354. return;
  8355. }
  8356. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8357. if (!statusSpan.length) {
  8358. //Add status span
  8359. statusSpan = document.createElement('span');
  8360. statusSpan.className = 'status';
  8361. statusSpan.id = this.videoSpanId + '_status';
  8362. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8363. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8364. }
  8365. // Display status
  8366. if (statusMsg && statusMsg.length) {
  8367. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8368. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8369. }
  8370. else {
  8371. // Hide
  8372. statusSpan.get(0).setAttribute("style", "display:none;");
  8373. }
  8374. };
  8375. /**
  8376. * Creates an audio or video stream element.
  8377. */
  8378. SmallVideo.createStreamElement = function (sid, stream) {
  8379. var isVideo = stream.getVideoTracks().length > 0;
  8380. var element = isVideo ? document.createElement('video')
  8381. : document.createElement('audio');
  8382. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8383. APP.RTC.getStreamID(stream);
  8384. element.id = id;
  8385. if (!RTCBrowserType.isIExplorer()) {
  8386. element.autoplay = true;
  8387. }
  8388. element.oncontextmenu = function () { return false; };
  8389. return element;
  8390. };
  8391. /**
  8392. * Updates the data for the indicator
  8393. * @param id the id of the indicator
  8394. * @param percent the percent for connection quality
  8395. * @param object the data
  8396. */
  8397. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8398. if(this.connectionIndicator)
  8399. this.connectionIndicator.updateConnectionQuality(percent, object);
  8400. };
  8401. SmallVideo.prototype.hideIndicator = function () {
  8402. if(this.connectionIndicator)
  8403. this.connectionIndicator.hideIndicator();
  8404. };
  8405. /**
  8406. * Shows audio muted indicator over small videos.
  8407. * @param {string} isMuted
  8408. */
  8409. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8410. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8411. if (!isMuted) {
  8412. if (audioMutedSpan.length > 0) {
  8413. audioMutedSpan.popover('hide');
  8414. audioMutedSpan.remove();
  8415. }
  8416. }
  8417. else {
  8418. if(audioMutedSpan.length == 0 ) {
  8419. audioMutedSpan = document.createElement('span');
  8420. audioMutedSpan.className = 'audioMuted';
  8421. UIUtil.setTooltip(audioMutedSpan,
  8422. "videothumbnail.mute",
  8423. "top");
  8424. this.container.appendChild(audioMutedSpan);
  8425. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8426. var mutedIndicator = document.createElement('i');
  8427. mutedIndicator.className = 'icon-mic-disabled';
  8428. audioMutedSpan.appendChild(mutedIndicator);
  8429. }
  8430. this.updateIconPositions();
  8431. }
  8432. this.isMuted = isMuted;
  8433. };
  8434. /**
  8435. * Shows video muted indicator over small videos.
  8436. */
  8437. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8438. this.showAvatar(isMuted);
  8439. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8440. if (isMuted === false) {
  8441. if (videoMutedSpan.length > 0) {
  8442. videoMutedSpan.remove();
  8443. }
  8444. }
  8445. else {
  8446. if(videoMutedSpan.length == 0) {
  8447. videoMutedSpan = document.createElement('span');
  8448. videoMutedSpan.className = 'videoMuted';
  8449. this.container.appendChild(videoMutedSpan);
  8450. var mutedIndicator = document.createElement('i');
  8451. mutedIndicator.className = 'icon-camera-disabled';
  8452. UIUtil.setTooltip(mutedIndicator,
  8453. "videothumbnail.videomute",
  8454. "top");
  8455. videoMutedSpan.appendChild(mutedIndicator);
  8456. //translate texts for muted indicator
  8457. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8458. }
  8459. this.updateIconPositions();
  8460. }
  8461. };
  8462. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8463. var resourceJid = this.getResourceJid();
  8464. var displayName = resourceJid;
  8465. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8466. if (nameSpan.length > 0)
  8467. displayName = nameSpan.html();
  8468. console.log("UI enable dominant speaker",
  8469. displayName,
  8470. resourceJid,
  8471. isEnable);
  8472. if (!this.container) {
  8473. return;
  8474. }
  8475. if (isEnable) {
  8476. this.showDisplayName(LargeVideo.getState() === "video");
  8477. if (!this.container.classList.contains("dominantspeaker"))
  8478. this.container.classList.add("dominantspeaker");
  8479. }
  8480. else {
  8481. this.showDisplayName(false);
  8482. if (this.container.classList.contains("dominantspeaker"))
  8483. this.container.classList.remove("dominantspeaker");
  8484. }
  8485. this.showAvatar();
  8486. };
  8487. SmallVideo.prototype.updateIconPositions = function () {
  8488. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8489. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8490. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8491. if(connectionIndicator.length > 0 &&
  8492. connectionIndicator[0].style.display != "none") {
  8493. audioMutedSpan.css({right: "23px"});
  8494. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8495. } else {
  8496. audioMutedSpan.css({right: "0px"});
  8497. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8498. }
  8499. };
  8500. /**
  8501. * Creates the element indicating the moderator(owner) of the conference.
  8502. *
  8503. * @param parentElement the parent element where the owner indicator will
  8504. * be added
  8505. */
  8506. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8507. // Show moderator indicator
  8508. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8509. if (!indicatorSpan || indicatorSpan.length === 0) {
  8510. indicatorSpan = document.createElement('span');
  8511. indicatorSpan.className = 'focusindicator';
  8512. this.container.appendChild(indicatorSpan);
  8513. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8514. }
  8515. if (indicatorSpan.children().length !== 0)
  8516. return;
  8517. var moderatorIndicator = document.createElement('i');
  8518. moderatorIndicator.className = 'fa fa-star';
  8519. indicatorSpan[0].appendChild(moderatorIndicator);
  8520. UIUtil.setTooltip(indicatorSpan[0],
  8521. "videothumbnail.moderator",
  8522. "top");
  8523. //translates text in focus indicators
  8524. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8525. };
  8526. SmallVideo.prototype.getSrc = function () {
  8527. var videoElement = APP.RTC.getVideoElementName();
  8528. return APP.RTC.getVideoSrc(
  8529. $('#' + this.videoSpanId).find(videoElement).get(0));
  8530. };
  8531. SmallVideo.prototype.focus = function(isFocused) {
  8532. if(!isFocused) {
  8533. this.container.classList.remove("videoContainerFocused");
  8534. } else {
  8535. this.container.classList.add("videoContainerFocused");
  8536. }
  8537. };
  8538. SmallVideo.prototype.hasVideo = function () {
  8539. return $("#" + this.videoSpanId).find(
  8540. APP.RTC.getVideoElementName()).length !== 0;
  8541. };
  8542. /**
  8543. * Hides or shows the user's avatar
  8544. * @param show whether we should show the avatar or not
  8545. * video because there is no dominant speaker and no focused speaker
  8546. */
  8547. SmallVideo.prototype.showAvatar = function (show) {
  8548. if (!this.hasAvatar) {
  8549. if (this.peerJid) {
  8550. // Init avatar
  8551. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8552. } else {
  8553. console.error("Unable to init avatar - no peerjid", this);
  8554. return;
  8555. }
  8556. }
  8557. var resourceJid = this.getResourceJid();
  8558. var videoElem = APP.RTC.getVideoElementName();
  8559. var video = $('#' + this.videoSpanId).find(videoElem);
  8560. var avatar = $('#avatar_' + resourceJid);
  8561. if (show === undefined || show === null) {
  8562. if (!this.isLocal &&
  8563. !this.VideoLayout.isInLastN(resourceJid)) {
  8564. show = true;
  8565. } else {
  8566. // We want to show the avatar when the video is muted or not exists
  8567. // that is when 'true' or 'null' is returned
  8568. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8569. }
  8570. }
  8571. if (LargeVideo.showAvatar(resourceJid, show)) {
  8572. setVisibility(avatar, false);
  8573. setVisibility(video, false);
  8574. } else {
  8575. if (video && video.length > 0) {
  8576. setVisibility(video, !show);
  8577. }
  8578. setVisibility(avatar, show);
  8579. }
  8580. };
  8581. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8582. var thumbnail = $('#' + this.videoSpanId);
  8583. var resourceJid = this.getResourceJid();
  8584. var avatar = $('#avatar_' + resourceJid);
  8585. this.hasAvatar = true;
  8586. // set the avatar in the thumbnail
  8587. if (avatar && avatar.length > 0) {
  8588. avatar[0].src = thumbUrl;
  8589. } else {
  8590. if (thumbnail && thumbnail.length > 0) {
  8591. avatar = document.createElement('img');
  8592. avatar.id = 'avatar_' + resourceJid;
  8593. avatar.className = 'userAvatar';
  8594. avatar.src = thumbUrl;
  8595. thumbnail.append(avatar);
  8596. }
  8597. }
  8598. };
  8599. module.exports = SmallVideo;
  8600. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8601. /* global config, APP, $, Strophe, require, interfaceConfig */
  8602. var AudioLevels = require("../audio_levels/AudioLevels");
  8603. var ContactList = require("../side_pannels/contactlist/ContactList");
  8604. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8605. var UIEvents = require("../../../service/UI/UIEvents");
  8606. var UIUtil = require("../util/UIUtil");
  8607. var RTC = require("../../RTC/RTC");
  8608. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8609. var RemoteVideo = require("./RemoteVideo");
  8610. var LargeVideo = require("./LargeVideo");
  8611. var LocalVideo = require("./LocalVideo");
  8612. var remoteVideos = {};
  8613. var remoteVideoTypes = {};
  8614. var localVideoThumbnail = null;
  8615. var currentDominantSpeaker = null;
  8616. var lastNCount = config.channelLastN;
  8617. var localLastNCount = config.channelLastN;
  8618. var localLastNSet = [];
  8619. var lastNEndpointsCache = [];
  8620. var lastNPickupJid = null;
  8621. var eventEmitter = null;
  8622. /**
  8623. * Currently focused video jid
  8624. * @type {String}
  8625. */
  8626. var focusedVideoResourceJid = null;
  8627. var VideoLayout = (function (my) {
  8628. my.init = function (emitter) {
  8629. eventEmitter = emitter;
  8630. localVideoThumbnail = new LocalVideo(VideoLayout);
  8631. if(config.filmStripOnly)
  8632. {
  8633. showLargeVideo = false;
  8634. LargeVideo.disable();
  8635. }
  8636. else
  8637. {
  8638. LargeVideo.init(VideoLayout, emitter);
  8639. }
  8640. VideoLayout.resizeLargeVideoContainer();
  8641. };
  8642. my.isInLastN = function(resource) {
  8643. return lastNCount < 0 || // lastN is disabled
  8644. // lastNEndpoints cache not built yet
  8645. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8646. (lastNEndpointsCache &&
  8647. lastNEndpointsCache.indexOf(resource) !== -1);
  8648. };
  8649. my.changeLocalStream = function (stream, isMuted) {
  8650. VideoLayout.changeLocalVideo(stream, isMuted);
  8651. };
  8652. my.changeLocalAudio = function(stream, isMuted) {
  8653. if (isMuted)
  8654. APP.UI.setAudioMuted(true, true);
  8655. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8656. var localAudio = document.getElementById('localAudio');
  8657. // Writing volume not allowed in IE
  8658. if (!RTCBrowserType.isIExplorer()) {
  8659. localAudio.autoplay = true;
  8660. localAudio.volume = 0;
  8661. }
  8662. };
  8663. my.changeLocalVideo = function(stream, isMuted) {
  8664. // Set default display name.
  8665. localVideoThumbnail.setDisplayName();
  8666. localVideoThumbnail.createConnectionIndicator();
  8667. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  8668. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8669. localVideoThumbnail.changeVideo(stream, isMuted);
  8670. /* force update if we're currently being displayed */
  8671. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8672. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8673. }
  8674. };
  8675. my.mucJoined = function () {
  8676. var myResourceJid = APP.xmpp.myResource();
  8677. localVideoThumbnail.joined(APP.xmpp.myJid());
  8678. if (!LargeVideo.getResourceJid())
  8679. LargeVideo.updateLargeVideo(myResourceJid, true);
  8680. };
  8681. /**
  8682. * Adds or removes icons for not available camera and microphone.
  8683. * @param resourceJid the jid of user
  8684. * @param devices available devices
  8685. */
  8686. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8687. if(!devices)
  8688. return;
  8689. if(!resourceJid) {
  8690. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8691. } else {
  8692. if(remoteVideos[resourceJid])
  8693. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8694. }
  8695. };
  8696. /**
  8697. * Checks if removed video is currently displayed and tries to display
  8698. * another one instead.
  8699. * @param removedVideoSrc src stream identifier of the video.
  8700. */
  8701. my.updateRemovedVideo = function(resourceJid) {
  8702. if (resourceJid === LargeVideo.getResourceJid()) {
  8703. var newResourceJid;
  8704. // We'll show user's avatar if he is the dominant speaker or if
  8705. // his video thumbnail is pinned
  8706. if (remoteVideos[resourceJid] &&
  8707. resourceJid === focusedVideoResourceJid ||
  8708. resourceJid === currentDominantSpeaker) {
  8709. newResourceJid = resourceJid;
  8710. } else {
  8711. // Otherwise select last visible video
  8712. newResourceJid = this.electLastVisibleVideo();
  8713. }
  8714. LargeVideo.updateLargeVideo(newResourceJid);
  8715. }
  8716. };
  8717. my.electLastVisibleVideo = function() {
  8718. // pick the last visible video in the row
  8719. // if nobody else is left, this picks the local video
  8720. var jid;
  8721. var videoElem = RTC.getVideoElementName();
  8722. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8723. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8724. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8725. } else {
  8726. console.info("Last visible video no longer exists");
  8727. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8728. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8729. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8730. } else {
  8731. // Try local video
  8732. console.info("Fallback to local video...");
  8733. jid = APP.xmpp.myResource();
  8734. }
  8735. }
  8736. console.info("electLastVisibleVideo: " + jid);
  8737. return jid;
  8738. };
  8739. my.onRemoteStreamAdded = function (stream) {
  8740. if (stream.peerjid) {
  8741. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8742. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8743. remoteVideos[resourceJid].addRemoteStreamElement(
  8744. stream.sid,
  8745. stream.getOriginalStream(),
  8746. stream.ssrc);
  8747. }
  8748. };
  8749. my.getLargeVideoJid = function () {
  8750. return LargeVideo.getResourceJid();
  8751. };
  8752. /**
  8753. * Called when large video update is finished
  8754. * @param currentSmallVideo small video currently displayed on large video
  8755. */
  8756. my.largeVideoUpdated = function (currentSmallVideo) {
  8757. // Makes sure that dominant speaker UI
  8758. // is enabled only on current small video
  8759. localVideoThumbnail.enableDominantSpeaker(
  8760. localVideoThumbnail === currentSmallVideo);
  8761. Object.keys(remoteVideos).forEach(
  8762. function (resourceJid) {
  8763. var remoteVideo = remoteVideos[resourceJid];
  8764. if (remoteVideo) {
  8765. remoteVideo.enableDominantSpeaker(
  8766. remoteVideo === currentSmallVideo);
  8767. }
  8768. }
  8769. );
  8770. };
  8771. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8772. resourceJid) {
  8773. if(focusedVideoResourceJid) {
  8774. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8775. if(oldSmallVideo && !config.filmStripOnly)
  8776. oldSmallVideo.focus(false);
  8777. }
  8778. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8779. // Unlock current focused.
  8780. if (focusedVideoResourceJid === resourceJid)
  8781. {
  8782. focusedVideoResourceJid = null;
  8783. // Enable the currently set dominant speaker.
  8784. if (currentDominantSpeaker) {
  8785. if(smallVideo && smallVideo.hasVideo()) {
  8786. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8787. }
  8788. }
  8789. if (!noPinnedEndpointChangedEvent) {
  8790. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8791. }
  8792. return;
  8793. }
  8794. // Lock new video
  8795. focusedVideoResourceJid = resourceJid;
  8796. // Update focused/pinned interface.
  8797. if (resourceJid) {
  8798. if(smallVideo && !config.filmStripOnly)
  8799. smallVideo.focus(true);
  8800. if (!noPinnedEndpointChangedEvent) {
  8801. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8802. }
  8803. }
  8804. LargeVideo.setState("video");
  8805. LargeVideo.updateLargeVideo(resourceJid);
  8806. // Writing volume not allowed in IE
  8807. if (!RTCBrowserType.isIExplorer()) {
  8808. $('audio').each(function (idx, el) {
  8809. el.volume = 0;
  8810. el.volume = 1;
  8811. });
  8812. }
  8813. };
  8814. /**
  8815. * Checks if container for participant identified by given peerJid exists
  8816. * in the document and creates it eventually.
  8817. *
  8818. * @param peerJid peer Jid to check.
  8819. *
  8820. * @return Returns <tt>true</tt> if the peer container exists,
  8821. * <tt>false</tt> - otherwise
  8822. */
  8823. my.ensurePeerContainerExists = function(peerJid) {
  8824. ContactList.ensureAddContact(peerJid);
  8825. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8826. if (!remoteVideos[resourceJid]) {
  8827. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  8828. remoteVideos[resourceJid] = remoteVideo;
  8829. var videoType = remoteVideoTypes[resourceJid];
  8830. if (videoType) {
  8831. remoteVideo.setVideoType(videoType);
  8832. }
  8833. // In case this is not currently in the last n we don't show it.
  8834. if (localLastNCount &&
  8835. localLastNCount > 0 &&
  8836. $('#remoteVideos>span').length >= localLastNCount + 2) {
  8837. remoteVideo.showPeerContainer('hide');
  8838. }
  8839. else
  8840. VideoLayout.resizeThumbnails();
  8841. }
  8842. };
  8843. my.inputDisplayNameHandler = function (name) {
  8844. localVideoThumbnail.inputDisplayNameHandler(name);
  8845. };
  8846. my.videoactive = function (videoelem, resourceJid) {
  8847. console.info(resourceJid + " video is now active");
  8848. videoelem.show();
  8849. VideoLayout.resizeThumbnails();
  8850. // Update the large video to the last added video only if there's no
  8851. // current dominant, focused speaker or prezi playing or update it to
  8852. // the current dominant speaker.
  8853. if ((!focusedVideoResourceJid &&
  8854. !currentDominantSpeaker &&
  8855. !require("../prezi/Prezi").isPresentationVisible()) ||
  8856. focusedVideoResourceJid === resourceJid ||
  8857. (resourceJid &&
  8858. currentDominantSpeaker === resourceJid)) {
  8859. LargeVideo.updateLargeVideo(resourceJid, true);
  8860. }
  8861. };
  8862. /**
  8863. * Shows the presence status message for the given video.
  8864. */
  8865. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8866. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8867. };
  8868. /**
  8869. * Shows a visual indicator for the moderator of the conference.
  8870. */
  8871. my.showModeratorIndicator = function () {
  8872. var isModerator = APP.xmpp.isModerator();
  8873. if (isModerator) {
  8874. localVideoThumbnail.createModeratorIndicatorElement();
  8875. }
  8876. var members = APP.xmpp.getMembers();
  8877. Object.keys(members).forEach(function (jid) {
  8878. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8879. // Skip server side focus
  8880. return;
  8881. }
  8882. var resourceJid = Strophe.getResourceFromJid(jid);
  8883. var member = members[jid];
  8884. if (member.role === 'moderator') {
  8885. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8886. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8887. } else if (isModerator) {
  8888. // We are moderator, but user is not - add menu
  8889. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8890. remoteVideos[resourceJid].addRemoteVideoMenu();
  8891. }
  8892. }
  8893. });
  8894. };
  8895. /*
  8896. * Shows or hides the audio muted indicator over the local thumbnail video.
  8897. * @param {boolean} isMuted
  8898. */
  8899. my.showLocalAudioIndicator = function(isMuted) {
  8900. localVideoThumbnail.showAudioIndicator(isMuted);
  8901. };
  8902. /**
  8903. * Resizes the large video container.
  8904. */
  8905. my.resizeLargeVideoContainer = function () {
  8906. if(LargeVideo.isEnabled()) {
  8907. LargeVideo.resize();
  8908. } else {
  8909. VideoLayout.resizeVideoSpace();
  8910. }
  8911. VideoLayout.resizeThumbnails();
  8912. LargeVideo.position();
  8913. };
  8914. /**
  8915. * Resizes thumbnails.
  8916. */
  8917. my.resizeThumbnails = function(animate) {
  8918. var videoSpaceWidth = $('#remoteVideos').width();
  8919. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8920. var width = thumbnailSize[0];
  8921. var height = thumbnailSize[1];
  8922. $('.userAvatar').css('left', (width - height) / 2);
  8923. if(animate) {
  8924. $('#remoteVideos').animate({
  8925. height: height + 2 // adds 2 px because of small video 1px border
  8926. },
  8927. {
  8928. queue: false,
  8929. duration: 500
  8930. });
  8931. $('#remoteVideos>span').animate({
  8932. height: height,
  8933. width: width
  8934. },
  8935. {
  8936. queue: false,
  8937. duration: 500,
  8938. complete: function () {
  8939. $(document).trigger(
  8940. "remotevideo.resized",
  8941. [width,
  8942. height]);
  8943. }
  8944. });
  8945. } else {
  8946. // size videos so that while keeping AR and max height, we have a
  8947. // nice fit
  8948. $('#remoteVideos').height(height + 2);// adds 2 px because of small video 1px border
  8949. $('#remoteVideos>span').width(width);
  8950. $('#remoteVideos>span').height(height);
  8951. $(document).trigger("remotevideo.resized", [width, height]);
  8952. }
  8953. };
  8954. /**
  8955. * Calculates the thumbnail size.
  8956. *
  8957. * @param videoSpaceWidth the width of the video space
  8958. */
  8959. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8960. // Calculate the available height, which is the inner window height minus
  8961. // 39px for the header minus 2px for the delimiter lines on the top and
  8962. // bottom of the large video, minus the 36px space inside the remoteVideos
  8963. // container used for highlighting shadow.
  8964. var availableHeight = 100;
  8965. var numvids = $('#remoteVideos>span:visible').length;
  8966. if (localLastNCount && localLastNCount > 0) {
  8967. numvids = Math.min(localLastNCount + 1, numvids);
  8968. }
  8969. // Remove the 3px borders arround videos and border around the remote
  8970. // videos area and the 4 pixels between the local video and the others
  8971. //TODO: Find out where the 4 pixels come from and remove them
  8972. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8973. var availableWidth = availableWinWidth / numvids;
  8974. var aspectRatio = 16.0 / 9.0;
  8975. var maxHeight = Math.min(160, availableHeight);
  8976. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio, window.innerHeight - 18);
  8977. if (availableHeight < availableWidth / aspectRatio) {
  8978. availableWidth = Math.floor(availableHeight * aspectRatio);
  8979. }
  8980. return [availableWidth, availableHeight];
  8981. };
  8982. /**
  8983. * Returns the corresponding resource jid to the given peer container
  8984. * DOM element.
  8985. *
  8986. * @return the corresponding resource jid to the given peer container
  8987. * DOM element
  8988. */
  8989. my.getPeerContainerResourceJid = function (containerElement) {
  8990. var i = containerElement.id.indexOf('participant_');
  8991. if (i >= 0)
  8992. return containerElement.id.substring(i + 12);
  8993. };
  8994. my.getPeerVideoSel = function (peerResourceJid) {
  8995. return $('#participant_' + peerResourceJid +
  8996. '>' + APP.RTC.getVideoElementName());
  8997. };
  8998. /**
  8999. * On contact list item clicked.
  9000. */
  9001. $(ContactList).bind('contactclicked', function(event, jid) {
  9002. if (!jid) {
  9003. return;
  9004. }
  9005. if (jid === APP.xmpp.myJid()) {
  9006. $("#localVideoContainer").click();
  9007. return;
  9008. }
  9009. var resource = Strophe.getResourceFromJid(jid);
  9010. var videoSel = VideoLayout.getPeerVideoSel(resource);
  9011. if (videoSel.length > 0) {
  9012. var videoThumb = videoSel[0];
  9013. // It is not always the case that a videoThumb exists (if there is
  9014. // no actual video).
  9015. if (RTC.getVideoSrc(videoThumb)) {
  9016. // We have a video src, great! Let's update the large video
  9017. // now.
  9018. VideoLayout.handleVideoThumbClicked(
  9019. false,
  9020. Strophe.getResourceFromJid(jid));
  9021. } else {
  9022. // If we don't have a video src for jid, there's absolutely
  9023. // no point in calling handleVideoThumbClicked; Quite
  9024. // simply, it won't work because it needs an src to attach
  9025. // to the large video.
  9026. //
  9027. // Instead, we trigger the pinned endpoint changed event to
  9028. // let the bridge adjust its lastN set for myjid and store
  9029. // the pinned user in the lastNPickupJid variable to be
  9030. // picked up later by the lastN changed event handler.
  9031. lastNPickupJid = jid;
  9032. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9033. Strophe.getResourceFromJid(jid));
  9034. }
  9035. }
  9036. });
  9037. /**
  9038. * On audio muted event.
  9039. */
  9040. my.onAudioMute = function (jid, isMuted) {
  9041. var resourceJid = Strophe.getResourceFromJid(jid);
  9042. if (resourceJid === APP.xmpp.myResource()) {
  9043. localVideoThumbnail.showAudioIndicator(isMuted);
  9044. } else {
  9045. VideoLayout.ensurePeerContainerExists(jid);
  9046. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9047. if (APP.xmpp.isModerator()) {
  9048. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9049. }
  9050. }
  9051. };
  9052. /**
  9053. * On video muted event.
  9054. */
  9055. my.onVideoMute = function (jid, value) {
  9056. if (jid !== APP.xmpp.myJid() &&
  9057. !APP.RTC.muteRemoteVideoStream(jid, value))
  9058. return;
  9059. if (jid === APP.xmpp.myJid()) {
  9060. localVideoThumbnail.showVideoIndicator(value);
  9061. } else {
  9062. var resource = Strophe.getResourceFromJid(jid);
  9063. VideoLayout.ensurePeerContainerExists(jid);
  9064. remoteVideos[resource].showVideoIndicator(value);
  9065. var el = VideoLayout.getPeerVideoSel(resource);
  9066. if (!value)
  9067. el.show();
  9068. else
  9069. el.hide();
  9070. }
  9071. };
  9072. /**
  9073. * Display name changed.
  9074. */
  9075. my.onDisplayNameChanged =
  9076. function (jid, displayName, status) {
  9077. if (jid === 'localVideoContainer' ||
  9078. jid === APP.xmpp.myJid()) {
  9079. localVideoThumbnail.setDisplayName(displayName);
  9080. } else {
  9081. VideoLayout.ensurePeerContainerExists(jid);
  9082. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9083. displayName,
  9084. status);
  9085. }
  9086. };
  9087. /**
  9088. * On dominant speaker changed event.
  9089. */
  9090. my.onDominantSpeakerChanged = function (resourceJid) {
  9091. // We ignore local user events.
  9092. if (resourceJid === APP.xmpp.myResource())
  9093. return;
  9094. var members = APP.xmpp.getMembers();
  9095. // Update the current dominant speaker.
  9096. if (resourceJid !== currentDominantSpeaker) {
  9097. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9098. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9099. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9100. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9101. remoteVideos[resourceJid].setDisplayName(null);
  9102. }
  9103. if(resourceJid && (!members || !members[newJID] ||
  9104. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9105. remoteVideos[resourceJid].setDisplayName(null,
  9106. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9107. }
  9108. currentDominantSpeaker = resourceJid;
  9109. } else {
  9110. return;
  9111. }
  9112. // Obtain container for new dominant speaker.
  9113. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9114. // Local video will not have container found, but that's ok
  9115. // since we don't want to switch to local video.
  9116. if (!focusedVideoResourceJid && videoSel.length) {
  9117. // Update the large video if the video source is already available,
  9118. // otherwise wait for the "videoactive.jingle" event.
  9119. if (videoSel[0].currentTime > 0) {
  9120. LargeVideo.updateLargeVideo(resourceJid);
  9121. }
  9122. }
  9123. };
  9124. /**
  9125. * On last N change event.
  9126. *
  9127. * @param lastNEndpoints the list of last N endpoints
  9128. * @param endpointsEnteringLastN the list currently entering last N
  9129. * endpoints
  9130. */
  9131. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9132. endpointsEnteringLastN,
  9133. stream) {
  9134. if (lastNCount !== lastNEndpoints.length)
  9135. lastNCount = lastNEndpoints.length;
  9136. lastNEndpointsCache = lastNEndpoints;
  9137. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9138. //
  9139. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9140. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9141. // so E sees them. C is only in E's local LastN set.
  9142. //
  9143. // If F starts talking and LastN = 3, then E should see thumbnails for
  9144. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9145. // enters E's local LastN ejecting C.
  9146. // Increase the local LastN set size, if necessary.
  9147. if (lastNCount > localLastNCount) {
  9148. localLastNCount = lastNCount;
  9149. }
  9150. // Update the local LastN set preserving the order in which the
  9151. // endpoints appeared in the LastN/local LastN set.
  9152. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9153. for (var i = 0; i < localLastNSet.length; i++) {
  9154. if (nextLocalLastNSet.length >= localLastNCount) {
  9155. break;
  9156. }
  9157. var resourceJid = localLastNSet[i];
  9158. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9159. nextLocalLastNSet.push(resourceJid);
  9160. }
  9161. }
  9162. localLastNSet = nextLocalLastNSet;
  9163. var updateLargeVideo = false;
  9164. // Handle LastN/local LastN changes.
  9165. $('#remoteVideos>span').each(function( index, element ) {
  9166. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9167. var isReceived = true;
  9168. if (resourceJid &&
  9169. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9170. localLastNSet.indexOf(resourceJid) < 0) {
  9171. console.log("Remove from last N", resourceJid);
  9172. remoteVideos[resourceJid].showPeerContainer('hide');
  9173. isReceived = false;
  9174. } else if (resourceJid &&
  9175. $('#participant_' + resourceJid).is(':visible') &&
  9176. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9177. localLastNSet.indexOf(resourceJid) >= 0) {
  9178. remoteVideos[resourceJid].showPeerContainer('avatar');
  9179. isReceived = false;
  9180. }
  9181. if (!isReceived) {
  9182. // resourceJid has dropped out of the server side lastN set, so
  9183. // it is no longer being received. If resourceJid was being
  9184. // displayed in the large video we have to switch to another
  9185. // user.
  9186. if (!updateLargeVideo &&
  9187. resourceJid === LargeVideo.getResourceJid()) {
  9188. updateLargeVideo = true;
  9189. }
  9190. }
  9191. });
  9192. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9193. endpointsEnteringLastN = lastNEndpoints;
  9194. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9195. endpointsEnteringLastN.forEach(function (resourceJid) {
  9196. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9197. remoteVideos[resourceJid].showPeerContainer('show');
  9198. if (!isVisible) {
  9199. console.log("Add to last N", resourceJid);
  9200. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9201. var mediaStream =
  9202. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9203. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9204. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9205. if (lastNPickupJid == mediaStream.peerjid) {
  9206. // Clean up the lastN pickup jid.
  9207. lastNPickupJid = null;
  9208. // Don't fire the events again, they've already
  9209. // been fired in the contact list click handler.
  9210. VideoLayout.handleVideoThumbClicked(
  9211. false,
  9212. Strophe.getResourceFromJid(mediaStream.peerjid));
  9213. updateLargeVideo = false;
  9214. }
  9215. remoteVideos[resourceJid].
  9216. waitForPlayback(sel, mediaStream.stream);
  9217. }
  9218. });
  9219. }
  9220. // The endpoint that was being shown in the large video has dropped out
  9221. // of the lastN set and there was no lastN pickup jid. We need to update
  9222. // the large video now.
  9223. if (updateLargeVideo) {
  9224. var resource;
  9225. var myResource
  9226. = APP.xmpp.myResource();
  9227. // Find out which endpoint to show in the large video.
  9228. for (i = 0; i < lastNEndpoints.length; i++) {
  9229. resource = lastNEndpoints[i];
  9230. if (!resource || resource === myResource)
  9231. continue;
  9232. // videoSrcToSsrc needs to be update for this call to succeed.
  9233. LargeVideo.updateLargeVideo(resource);
  9234. break;
  9235. }
  9236. }
  9237. };
  9238. /**
  9239. * Updates local stats
  9240. * @param percent
  9241. * @param object
  9242. */
  9243. my.updateLocalConnectionStats = function (percent, object) {
  9244. var resolution = null;
  9245. if (object.resolution !== null) {
  9246. resolution = object.resolution;
  9247. object.resolution = resolution[APP.xmpp.myJid()];
  9248. delete resolution[APP.xmpp.myJid()];
  9249. }
  9250. localVideoThumbnail.updateStatsIndicator(percent, object);
  9251. for (var jid in resolution) {
  9252. if (resolution[jid] === null)
  9253. continue;
  9254. var resourceJid = Strophe.getResourceFromJid(jid);
  9255. if (remoteVideos[resourceJid] &&
  9256. remoteVideos[resourceJid].connectionIndicator) {
  9257. remoteVideos[resourceJid].connectionIndicator.
  9258. updateResolution(resolution[jid]);
  9259. }
  9260. }
  9261. };
  9262. /**
  9263. * Updates remote stats.
  9264. * @param jid the jid associated with the stats
  9265. * @param percent the connection quality percent
  9266. * @param object the stats data
  9267. */
  9268. my.updateConnectionStats = function (jid, percent, object) {
  9269. var resourceJid = Strophe.getResourceFromJid(jid);
  9270. if (remoteVideos[resourceJid])
  9271. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9272. };
  9273. /**
  9274. * Hides the connection indicator
  9275. * @param jid
  9276. */
  9277. my.hideConnectionIndicator = function (jid) {
  9278. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9279. };
  9280. /**
  9281. * Hides all the indicators
  9282. */
  9283. my.onStatsStop = function () {
  9284. for(var video in remoteVideos) {
  9285. remoteVideos[video].hideIndicator();
  9286. }
  9287. localVideoThumbnail.hideIndicator();
  9288. };
  9289. my.participantLeft = function (jid) {
  9290. // Unlock large video
  9291. var resourceJid = Strophe.getResourceFromJid(jid);
  9292. if (focusedVideoResourceJid === resourceJid) {
  9293. console.info("Focused video owner has left the conference");
  9294. focusedVideoResourceJid = null;
  9295. }
  9296. if (currentDominantSpeaker === resourceJid)
  9297. {
  9298. console.info("Dominant speaker has left the conference");
  9299. currentDominantSpeaker = null;
  9300. }
  9301. var remoteVideo = remoteVideos[resourceJid];
  9302. if (remoteVideo) {
  9303. // Remove remote video
  9304. console.info("Removing remote video: " + resourceJid);
  9305. remoteVideo.remove();
  9306. delete remoteVideos[resourceJid];
  9307. } else {
  9308. console.warn("No remote video for " + resourceJid);
  9309. }
  9310. VideoLayout.resizeThumbnails();
  9311. };
  9312. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9313. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9314. return;
  9315. }
  9316. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9317. remoteVideoTypes[resourceJid] = newVideoType;
  9318. var smallVideo;
  9319. if (resourceJid === APP.xmpp.myResource()) {
  9320. if (!localVideoThumbnail) {
  9321. console.warn("Local video not ready yet");
  9322. return;
  9323. }
  9324. smallVideo = localVideoThumbnail;
  9325. } else if (remoteVideos[resourceJid]) {
  9326. smallVideo = remoteVideos[resourceJid];
  9327. } else {
  9328. return;
  9329. }
  9330. smallVideo.setVideoType(newVideoType);
  9331. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9332. };
  9333. my.showMore = function (jid) {
  9334. if (jid === 'local') {
  9335. localVideoThumbnail.connectionIndicator.showMore();
  9336. } else {
  9337. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9338. if (remoteVideo) {
  9339. remoteVideo.connectionIndicator.showMore();
  9340. } else {
  9341. console.info("Error - no remote video for jid: " + jid);
  9342. }
  9343. }
  9344. };
  9345. my.addPreziContainer = function (id) {
  9346. var container = RemoteVideo.createContainer(id);
  9347. VideoLayout.resizeThumbnails();
  9348. return container;
  9349. };
  9350. my.setLargeVideoVisible = function (isVisible) {
  9351. LargeVideo.setLargeVideoVisible(isVisible);
  9352. if(!isVisible && focusedVideoResourceJid) {
  9353. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9354. if(smallVideo) {
  9355. smallVideo.focus(false);
  9356. smallVideo.showAvatar();
  9357. }
  9358. focusedVideoResourceJid = null;
  9359. }
  9360. };
  9361. /**
  9362. * Resizes the video area
  9363. * @param callback a function to be called when the video space is
  9364. * resized.
  9365. */
  9366. my.resizeVideoArea = function(isVisible, callback) {
  9367. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9368. VideoLayout.resizeThumbnails(true);
  9369. };
  9370. /**
  9371. * Resizes the #videospace html element
  9372. * @param animate boolean property that indicates whether the resize should be animated or not.
  9373. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  9374. * If that parameter is null the method will check the chat pannel visibility.
  9375. * @param completeFunction a function to be called when the video space is resized
  9376. */
  9377. my.resizeVideoSpace = function (animate, isChatVisible, completeFunction) {
  9378. var availableHeight = window.innerHeight;
  9379. var availableWidth = UIUtil.getAvailableVideoWidth(isChatVisible);
  9380. if (availableWidth < 0 || availableHeight < 0) return;
  9381. if(animate) {
  9382. $('#videospace').animate({
  9383. right: window.innerWidth - availableWidth,
  9384. width: availableWidth,
  9385. height: availableHeight
  9386. },
  9387. {
  9388. queue: false,
  9389. duration: 500,
  9390. complete: completeFunction
  9391. });
  9392. } else {
  9393. $('#videospace').width(availableWidth);
  9394. $('#videospace').height(availableHeight);
  9395. }
  9396. };
  9397. my.getSmallVideo = function (resourceJid) {
  9398. if(resourceJid == APP.xmpp.myResource()) {
  9399. return localVideoThumbnail;
  9400. } else {
  9401. if(!remoteVideos[resourceJid])
  9402. return null;
  9403. return remoteVideos[resourceJid];
  9404. }
  9405. };
  9406. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9407. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9408. if(smallVideo)
  9409. smallVideo.avatarChanged(thumbUrl);
  9410. else
  9411. console.warn(
  9412. "Missed avatar update - no small video yet for " + resourceJid);
  9413. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9414. };
  9415. my.createEtherpadIframe = function(src, onloadHandler)
  9416. {
  9417. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9418. };
  9419. my.setLargeVideoState = function (state) {
  9420. LargeVideo.setState(state);
  9421. };
  9422. my.getLargeVideoState = function () {
  9423. return LargeVideo.getState();
  9424. };
  9425. my.setLargeVideoHover = function (inHandler, outHandler) {
  9426. LargeVideo.setHover(inHandler, outHandler);
  9427. };
  9428. /**
  9429. * Indicates that the video has been interrupted.
  9430. */
  9431. my.onVideoInterrupted = function () {
  9432. LargeVideo.enableVideoProblemFilter(true);
  9433. var reconnectingKey = "connection.RECONNECTING";
  9434. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9435. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9436. $('#videoConnectionMessage').css({display: "block"});
  9437. };
  9438. /**
  9439. * Indicates that the video has been restored.
  9440. */
  9441. my.onVideoRestored = function () {
  9442. LargeVideo.enableVideoProblemFilter(false);
  9443. $('#videoConnectionMessage').css({display: "none"});
  9444. };
  9445. return my;
  9446. }(VideoLayout || {}));
  9447. module.exports = VideoLayout;
  9448. },{"../../../service/RTC/MediaStreamTypes":103,"../../../service/UI/UIEvents":107,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"../util/UIUtil":33,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  9449. //var nouns = [
  9450. //];
  9451. var pluralNouns = [
  9452. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9453. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9454. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9455. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9456. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9457. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9458. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9459. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9460. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9461. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9462. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9463. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9464. ];
  9465. //var places = [
  9466. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9467. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9468. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9469. // "Bridge"
  9470. //];
  9471. var verbs = [
  9472. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9473. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9474. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9475. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9476. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9477. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9478. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9479. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9480. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9481. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9482. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9483. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9484. ];
  9485. var adverbs = [
  9486. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9487. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9488. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9489. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9490. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9491. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9492. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9493. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9494. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9495. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9496. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9497. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9498. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9499. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9500. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9501. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9502. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9503. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9504. ];
  9505. var adjectives = [
  9506. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9507. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9508. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9509. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9510. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9511. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9512. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9513. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9514. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9515. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9516. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9517. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9518. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9519. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9520. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9521. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9522. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9523. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9524. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9525. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9526. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9527. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9528. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9529. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9530. "Zealous"
  9531. ];
  9532. //var pronouns = [
  9533. //];
  9534. //var conjunctions = [
  9535. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9536. //];
  9537. /*
  9538. * Maps a string (category name) to the array of words from that category.
  9539. */
  9540. var CATEGORIES =
  9541. {
  9542. //"_NOUN_": nouns,
  9543. "_PLURALNOUN_": pluralNouns,
  9544. //"_PLACE_": places,
  9545. "_VERB_": verbs,
  9546. "_ADVERB_": adverbs,
  9547. "_ADJECTIVE_": adjectives
  9548. //"_PRONOUN_": pronouns,
  9549. //"_CONJUNCTION_": conjunctions,
  9550. };
  9551. var PATTERNS = [
  9552. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9553. // BeautifulFungiOrSpaghetti
  9554. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9555. // AmazinglyScaryToy
  9556. //"_ADVERB__ADJECTIVE__NOUN_",
  9557. // NeitherTrashNorRifle
  9558. //"Neither_NOUN_Nor_NOUN_",
  9559. //"Either_NOUN_Or_NOUN_",
  9560. // EitherCopulateOrInvestigate
  9561. //"Either_VERB_Or_VERB_",
  9562. //"Neither_VERB_Nor_VERB_",
  9563. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9564. //"The_ADVERB__ADJECTIVE__NOUN_",
  9565. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9566. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9567. // WolvesComputeBadly
  9568. //"_PLURALNOUN__VERB__ADVERB_",
  9569. // UniteFacilitateAndMerge
  9570. //"_VERB__VERB_And_VERB_",
  9571. //NastyWitchesAtThePub
  9572. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9573. ];
  9574. /*
  9575. * Returns a random element from the array 'arr'
  9576. */
  9577. function randomElement(arr) {
  9578. return arr[Math.floor(Math.random() * arr.length)];
  9579. }
  9580. /*
  9581. * Returns true if the string 's' contains one of the
  9582. * template strings.
  9583. */
  9584. function hasTemplate(s) {
  9585. for (var template in CATEGORIES){
  9586. if (s.indexOf(template) >= 0){
  9587. return true;
  9588. }
  9589. }
  9590. }
  9591. /**
  9592. * Generates new room name.
  9593. */
  9594. var RoomNameGenerator = {
  9595. generateRoomWithoutSeparator: function() {
  9596. // Note that if more than one pattern is available, the choice of
  9597. // 'name' won't have a uniform distribution amongst all patterns (names
  9598. // from patterns with fewer options will have higher probability of
  9599. // being chosen that names from patterns with more options).
  9600. var name = randomElement(PATTERNS);
  9601. var word;
  9602. while (hasTemplate(name)) {
  9603. for (var template in CATEGORIES) {
  9604. word = randomElement(CATEGORIES[template]);
  9605. name = name.replace(template, word);
  9606. }
  9607. }
  9608. return name;
  9609. }
  9610. };
  9611. module.exports = RoomNameGenerator;
  9612. },{}],41:[function(require,module,exports){
  9613. /* global $, interfaceConfig */
  9614. var animateTimeout, updateTimeout;
  9615. var RoomNameGenerator = require("./RoomnameGenerator");
  9616. function enter_room() {
  9617. var val = $("#enter_room_field").val();
  9618. if(!val) {
  9619. val = $("#enter_room_field").attr("room_name");
  9620. }
  9621. if (val) {
  9622. window.location.pathname = "/" + val;
  9623. }
  9624. }
  9625. function animate(word) {
  9626. var currentVal = $("#enter_room_field").attr("placeholder");
  9627. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9628. animateTimeout = setTimeout(function() {
  9629. animate(word.substring(1, word.length))
  9630. }, 70);
  9631. }
  9632. function update_roomname() {
  9633. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9634. $("#enter_room_field").attr("room_name", word);
  9635. $("#enter_room_field").attr("placeholder", "");
  9636. clearTimeout(animateTimeout);
  9637. animate(word);
  9638. updateTimeout = setTimeout(update_roomname, 10000);
  9639. }
  9640. function setupWelcomePage() {
  9641. $("#videoconference_page").hide();
  9642. $("#domain_name").text(
  9643. window.location.protocol + "//" + window.location.host + "/");
  9644. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9645. var leftWatermarkDiv =
  9646. $("#welcome_page_header div[class='watermark leftwatermark']");
  9647. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9648. leftWatermarkDiv.css({display: 'block'});
  9649. leftWatermarkDiv.parent().get(0).href =
  9650. interfaceConfig.JITSI_WATERMARK_LINK;
  9651. }
  9652. }
  9653. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9654. var rightWatermarkDiv =
  9655. $("#welcome_page_header div[class='watermark rightwatermark']");
  9656. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9657. rightWatermarkDiv.css({display: 'block'});
  9658. rightWatermarkDiv.parent().get(0).href =
  9659. interfaceConfig.BRAND_WATERMARK_LINK;
  9660. rightWatermarkDiv.get(0).style.backgroundImage =
  9661. "url(images/rightwatermark.png)";
  9662. }
  9663. }
  9664. if (interfaceConfig.SHOW_POWERED_BY) {
  9665. $("#welcome_page_header>a[class='poweredby']")
  9666. .css({display: 'block'});
  9667. }
  9668. $("#enter_room_button").click(function() {
  9669. enter_room();
  9670. });
  9671. $("#enter_room_field").keydown(function (event) {
  9672. if (event.keyCode === 13 /* enter */) {
  9673. enter_room();
  9674. }
  9675. });
  9676. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9677. var updateTimeout;
  9678. var animateTimeout;
  9679. var selector = $("#reload_roomname");
  9680. selector.click(function () {
  9681. clearTimeout(updateTimeout);
  9682. clearTimeout(animateTimeout);
  9683. update_roomname();
  9684. });
  9685. selector.show();
  9686. update_roomname();
  9687. }
  9688. $("#disable_welcome").click(function () {
  9689. window.localStorage.welcomePageDisabled =
  9690. $("#disable_welcome").is(":checked");
  9691. });
  9692. }
  9693. module.exports = setupWelcomePage;
  9694. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9695. /* global $, $iq, config */
  9696. var params = {};
  9697. function getConfigParamsFromUrl() {
  9698. if(!location.hash)
  9699. return {};
  9700. var hash = location.hash.substr(1);
  9701. var result = {};
  9702. hash.split("&").forEach(function(part) {
  9703. var item = part.split("=");
  9704. result[item[0]] = JSON.parse(
  9705. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9706. });
  9707. return result;
  9708. }
  9709. params = getConfigParamsFromUrl();
  9710. var URLProcessor = {
  9711. setConfigParametersFromUrl: function () {
  9712. for(var k in params)
  9713. {
  9714. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9715. continue;
  9716. var v = params[k];
  9717. var confKey = k.substr(7);
  9718. if(config[confKey] && typeof config[confKey] !== typeof v)
  9719. {
  9720. console.warn("The type of " + k +
  9721. " is wrong. That parameter won't be updated in config.js.");
  9722. continue;
  9723. }
  9724. config[confKey] = v;
  9725. }
  9726. }
  9727. };
  9728. module.exports = URLProcessor;
  9729. },{}],43:[function(require,module,exports){
  9730. /* global APP, require */
  9731. var EventEmitter = require("events");
  9732. var eventEmitter = new EventEmitter();
  9733. var CQEvents = require("../../service/connectionquality/CQEvents");
  9734. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9735. /**
  9736. * local stats
  9737. * @type {{}}
  9738. */
  9739. var stats = {};
  9740. /**
  9741. * remote stats
  9742. * @type {{}}
  9743. */
  9744. var remoteStats = {};
  9745. /**
  9746. * Interval for sending statistics to other participants
  9747. * @type {null}
  9748. */
  9749. var sendIntervalId = null;
  9750. /**
  9751. * Start statistics sending.
  9752. */
  9753. function startSendingStats() {
  9754. sendStats();
  9755. sendIntervalId = setInterval(sendStats, 10000);
  9756. }
  9757. /**
  9758. * Sends statistics to other participants
  9759. */
  9760. function sendStats() {
  9761. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9762. }
  9763. /**
  9764. * Converts statistics to format for sending through XMPP
  9765. * @param stats the statistics
  9766. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9767. */
  9768. function convertToMUCStats(stats) {
  9769. return {
  9770. "bitrate_download": stats.bitrate.download,
  9771. "bitrate_upload": stats.bitrate.upload,
  9772. "packetLoss_total": stats.packetLoss.total,
  9773. "packetLoss_download": stats.packetLoss.download,
  9774. "packetLoss_upload": stats.packetLoss.upload
  9775. };
  9776. }
  9777. /**
  9778. * Converts statistics to format used by VideoLayout
  9779. * @param stats
  9780. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9781. */
  9782. function parseMUCStats(stats) {
  9783. return {
  9784. bitrate: {
  9785. download: stats.bitrate_download,
  9786. upload: stats.bitrate_upload
  9787. },
  9788. packetLoss: {
  9789. total: stats.packetLoss_total,
  9790. download: stats.packetLoss_download,
  9791. upload: stats.packetLoss_upload
  9792. }
  9793. };
  9794. }
  9795. var ConnectionQuality = {
  9796. init: function () {
  9797. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9798. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9799. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9800. },
  9801. /**
  9802. * Updates the local statistics
  9803. * @param data new statistics
  9804. */
  9805. updateLocalStats: function (data) {
  9806. stats = data;
  9807. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9808. if (sendIntervalId == null) {
  9809. startSendingStats();
  9810. }
  9811. },
  9812. /**
  9813. * Updates remote statistics
  9814. * @param jid the jid associated with the statistics
  9815. * @param data the statistics
  9816. */
  9817. updateRemoteStats: function (jid, data) {
  9818. if (data == null || data.packetLoss_total == null) {
  9819. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9820. return;
  9821. }
  9822. remoteStats[jid] = parseMUCStats(data);
  9823. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9824. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9825. },
  9826. /**
  9827. * Stops statistics sending.
  9828. */
  9829. stopSendingStats: function () {
  9830. clearInterval(sendIntervalId);
  9831. sendIntervalId = null;
  9832. //notify UI about stopping statistics gathering
  9833. eventEmitter.emit(CQEvents.STOP);
  9834. },
  9835. /**
  9836. * Returns the local statistics.
  9837. */
  9838. getStats: function () {
  9839. return stats;
  9840. },
  9841. addListener: function (type, listener) {
  9842. eventEmitter.on(type, listener);
  9843. }
  9844. };
  9845. module.exports = ConnectionQuality;
  9846. },{"../../service/connectionquality/CQEvents":109,"../../service/xmpp/XMPPEvents":113,"events":114}],44:[function(require,module,exports){
  9847. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9848. getUserMediaWithConstraints */
  9849. /**
  9850. * Indicates that desktop stream is currently in use(for toggle purpose).
  9851. * @type {boolean}
  9852. */
  9853. var isUsingScreenStream = false;
  9854. /**
  9855. * Indicates that switch stream operation is in progress and prevent from
  9856. * triggering new events.
  9857. * @type {boolean}
  9858. */
  9859. var switchInProgress = false;
  9860. /**
  9861. * Method used to get screen sharing stream.
  9862. *
  9863. * @type {function (stream_callback, failure_callback}
  9864. */
  9865. var obtainDesktopStream = null;
  9866. /**
  9867. * Indicates whether desktop sharing extension is installed.
  9868. * @type {boolean}
  9869. */
  9870. var extInstalled = false;
  9871. /**
  9872. * Indicates whether update of desktop sharing extension is required.
  9873. * @type {boolean}
  9874. */
  9875. var extUpdateRequired = false;
  9876. var AdapterJS = require("../RTC/adapter.screenshare");
  9877. var EventEmitter = require("events");
  9878. var eventEmitter = new EventEmitter();
  9879. var DesktopSharingEventTypes
  9880. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9881. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9882. var RTCEvents = require("../../service/RTC/RTCEvents");
  9883. /**
  9884. * Method obtains desktop stream from WebRTC 'screen' source.
  9885. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9886. */
  9887. function obtainWebRTCScreen(streamCallback, failCallback) {
  9888. APP.RTC.getUserMediaWithConstraints(
  9889. ['screen'],
  9890. streamCallback,
  9891. failCallback
  9892. );
  9893. }
  9894. /**
  9895. * Constructs inline install URL for Chrome desktop streaming extension.
  9896. * The 'chromeExtensionId' must be defined in config.js.
  9897. * @returns {string}
  9898. */
  9899. function getWebStoreInstallUrl()
  9900. {
  9901. return "https://chrome.google.com/webstore/detail/" +
  9902. config.chromeExtensionId;
  9903. }
  9904. /**
  9905. * Checks whether extension update is required.
  9906. * @param minVersion minimal required version
  9907. * @param extVersion current extension version
  9908. * @returns {boolean}
  9909. */
  9910. function isUpdateRequired(minVersion, extVersion)
  9911. {
  9912. try
  9913. {
  9914. var s1 = minVersion.split('.');
  9915. var s2 = extVersion.split('.');
  9916. var len = Math.max(s1.length, s2.length);
  9917. for (var i = 0; i < len; i++)
  9918. {
  9919. var n1 = 0,
  9920. n2 = 0;
  9921. if (i < s1.length)
  9922. n1 = parseInt(s1[i]);
  9923. if (i < s2.length)
  9924. n2 = parseInt(s2[i]);
  9925. if (isNaN(n1) || isNaN(n2))
  9926. {
  9927. return true;
  9928. }
  9929. else if (n1 !== n2)
  9930. {
  9931. return n1 > n2;
  9932. }
  9933. }
  9934. // will happen if boths version has identical numbers in
  9935. // their components (even if one of them is longer, has more components)
  9936. return false;
  9937. }
  9938. catch (e)
  9939. {
  9940. console.error("Failed to parse extension version", e);
  9941. APP.UI.messageHandler.showError("dialog.error",
  9942. "dialog.detectext");
  9943. return true;
  9944. }
  9945. }
  9946. function checkChromeExtInstalled(callback) {
  9947. if (!chrome.runtime) {
  9948. // No API, so no extension for sure
  9949. callback(false, false);
  9950. return;
  9951. }
  9952. chrome.runtime.sendMessage(
  9953. config.chromeExtensionId,
  9954. { getVersion: true },
  9955. function (response) {
  9956. if (!response || !response.version) {
  9957. // Communication failure - assume that no endpoint exists
  9958. console.warn(
  9959. "Extension not installed?: ", chrome.runtime.lastError);
  9960. callback(false, false);
  9961. return;
  9962. }
  9963. // Check installed extension version
  9964. var extVersion = response.version;
  9965. console.log('Extension version is: ' + extVersion);
  9966. var updateRequired
  9967. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  9968. callback(!updateRequired, updateRequired);
  9969. }
  9970. );
  9971. }
  9972. function doGetStreamFromExtension(streamCallback, failCallback) {
  9973. // Sends 'getStream' msg to the extension.
  9974. // Extension id must be defined in the config.
  9975. chrome.runtime.sendMessage(
  9976. config.chromeExtensionId,
  9977. { getStream: true, sources: config.desktopSharingSources },
  9978. function (response) {
  9979. if (!response) {
  9980. failCallback(chrome.runtime.lastError);
  9981. return;
  9982. }
  9983. console.log("Response from extension: " + response);
  9984. if (response.streamId) {
  9985. APP.RTC.getUserMediaWithConstraints(
  9986. ['desktop'],
  9987. function (stream) {
  9988. streamCallback(stream);
  9989. },
  9990. failCallback,
  9991. null, null, null,
  9992. response.streamId);
  9993. } else {
  9994. failCallback("Extension failed to get the stream");
  9995. }
  9996. }
  9997. );
  9998. }
  9999. /**
  10000. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10001. * stream for returned stream token.
  10002. */
  10003. function obtainScreenFromExtension(streamCallback, failCallback) {
  10004. if (extInstalled) {
  10005. doGetStreamFromExtension(streamCallback, failCallback);
  10006. } else {
  10007. if (extUpdateRequired) {
  10008. alert(
  10009. 'Jitsi Desktop Streamer requires update. ' +
  10010. 'Changes will take effect after next Chrome restart.');
  10011. }
  10012. chrome.webstore.install(
  10013. getWebStoreInstallUrl(),
  10014. function (arg) {
  10015. console.log("Extension installed successfully", arg);
  10016. extInstalled = true;
  10017. // We need to give a moment for the endpoint to become available
  10018. window.setTimeout(function () {
  10019. doGetStreamFromExtension(streamCallback, failCallback);
  10020. }, 500);
  10021. },
  10022. function (arg) {
  10023. console.log("Failed to install the extension", arg);
  10024. failCallback(arg);
  10025. APP.UI.messageHandler.showError("dialog.error",
  10026. "dialog.failtoinstall");
  10027. }
  10028. );
  10029. }
  10030. }
  10031. /**
  10032. * Call this method to toggle desktop sharing feature.
  10033. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10034. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10035. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10036. * enabled), pass any other string or nothing in order to disable this
  10037. * feature completely.
  10038. */
  10039. function setDesktopSharing(method) {
  10040. obtainDesktopStream = null;
  10041. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10042. // care about 'method' parameter
  10043. if (RTCBrowserType.isTemasysPluginUsed()) {
  10044. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10045. console.info("Screensharing not supported by this plugin version");
  10046. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10047. console.info(
  10048. "Screensharing not available with Temasys plugin on this site");
  10049. } else {
  10050. obtainDesktopStream = obtainWebRTCScreen;
  10051. console.info("Using Temasys plugin for desktop sharing");
  10052. }
  10053. } else if (RTCBrowserType.isChrome()) {
  10054. if (method == "ext") {
  10055. if (RTCBrowserType.getChromeVersion() >= 34) {
  10056. obtainDesktopStream = obtainScreenFromExtension;
  10057. console.info("Using Chrome extension for desktop sharing");
  10058. initChromeExtension();
  10059. } else {
  10060. console.info("Chrome extension not supported until ver 34");
  10061. }
  10062. } else if (method == "webrtc") {
  10063. obtainDesktopStream = obtainWebRTCScreen;
  10064. console.info("Using Chrome WebRTC for desktop sharing");
  10065. }
  10066. }
  10067. if (!obtainDesktopStream) {
  10068. console.info("Desktop sharing disabled");
  10069. }
  10070. }
  10071. /**
  10072. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10073. * config.js to support inline installs. Host site must be selected as main
  10074. * website of published extension.
  10075. */
  10076. function initInlineInstalls()
  10077. {
  10078. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10079. }
  10080. function initChromeExtension() {
  10081. // Initialize Chrome extension inline installs
  10082. initInlineInstalls();
  10083. // Check if extension is installed
  10084. checkChromeExtInstalled(function (installed, updateRequired) {
  10085. extInstalled = installed;
  10086. extUpdateRequired = updateRequired;
  10087. console.info(
  10088. "Chrome extension installed: " + extInstalled +
  10089. " updateRequired: " + extUpdateRequired);
  10090. });
  10091. }
  10092. function getVideoStreamFailed(error) {
  10093. console.error("Failed to obtain the stream to switch to", error);
  10094. switchInProgress = false;
  10095. isUsingScreenStream = false;
  10096. newStreamCreated(null);
  10097. }
  10098. function getDesktopStreamFailed(error) {
  10099. console.error("Failed to obtain the stream to switch to", error);
  10100. switchInProgress = false;
  10101. }
  10102. function streamSwitchDone() {
  10103. switchInProgress = false;
  10104. eventEmitter.emit(
  10105. DesktopSharingEventTypes.SWITCHING_DONE,
  10106. isUsingScreenStream);
  10107. }
  10108. function newStreamCreated(stream)
  10109. {
  10110. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10111. stream, isUsingScreenStream, streamSwitchDone);
  10112. }
  10113. function onEndedHandler(stream) {
  10114. if (!switchInProgress && isUsingScreenStream) {
  10115. APP.desktopsharing.toggleScreenSharing();
  10116. }
  10117. //FIXME: to be verified
  10118. if (stream.removeEventListener) {
  10119. stream.removeEventListener('ended', onEndedHandler);
  10120. } else {
  10121. stream.detachEvent('ended', onEndedHandler);
  10122. }
  10123. }
  10124. // Called when RTC finishes initialization
  10125. function onWebRtcReady() {
  10126. setDesktopSharing(config.desktopSharing);
  10127. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10128. }
  10129. module.exports = {
  10130. isUsingScreenStream: function () {
  10131. return isUsingScreenStream;
  10132. },
  10133. /**
  10134. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10135. * and enabled.
  10136. */
  10137. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10138. init: function () {
  10139. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10140. },
  10141. addListener: function (listener, type)
  10142. {
  10143. eventEmitter.on(type, listener);
  10144. },
  10145. removeListener: function (listener, type) {
  10146. eventEmitter.removeListener(type, listener);
  10147. },
  10148. /*
  10149. * Toggles screen sharing.
  10150. */
  10151. toggleScreenSharing: function () {
  10152. if (switchInProgress || !obtainDesktopStream) {
  10153. console.warn("Switch in progress or no method defined");
  10154. return;
  10155. }
  10156. switchInProgress = true;
  10157. if (!isUsingScreenStream)
  10158. {
  10159. // Switch to desktop stream
  10160. obtainDesktopStream(
  10161. function (stream) {
  10162. // We now use screen stream
  10163. isUsingScreenStream = true;
  10164. // Hook 'ended' event to restore camera
  10165. // when screen stream stops
  10166. //FIXME: to be verified
  10167. if (stream.addEventListener) {
  10168. stream.addEventListener('ended', function () {
  10169. onEndedHandler(stream);
  10170. });
  10171. } else {
  10172. stream.attachEvent('ended', function () {
  10173. onEndedHandler(stream);
  10174. });
  10175. }
  10176. newStreamCreated(stream);
  10177. },
  10178. getDesktopStreamFailed);
  10179. } else {
  10180. // Disable screen stream
  10181. APP.RTC.getUserMediaWithConstraints(
  10182. ['video'],
  10183. function (stream) {
  10184. // We are now using camera stream
  10185. isUsingScreenStream = false;
  10186. newStreamCreated(stream);
  10187. },
  10188. getVideoStreamFailed, config.resolution || '360'
  10189. );
  10190. }
  10191. }
  10192. };
  10193. },{"../../service/RTC/RTCEvents":104,"../../service/desktopsharing/DesktopSharingEventTypes":110,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":114}],45:[function(require,module,exports){
  10194. /* global APP, $ */
  10195. //maps keycode to character, id of popover for given function and function
  10196. var shortcuts = {};
  10197. function initShortcutHandlers() {
  10198. shortcuts = {
  10199. 67: {
  10200. character: "C",
  10201. id: "toggleChatPopover",
  10202. function: APP.UI.toggleChat
  10203. },
  10204. 70: {
  10205. character: "F",
  10206. id: "filmstripPopover",
  10207. function: APP.UI.toggleFilmStrip
  10208. },
  10209. 77: {
  10210. character: "M",
  10211. id: "mutePopover",
  10212. function: APP.UI.toggleAudio
  10213. },
  10214. 84: {
  10215. character: "T",
  10216. function: function() {
  10217. if(!APP.RTC.localAudio.isMuted()) {
  10218. APP.UI.toggleAudio();
  10219. }
  10220. }
  10221. },
  10222. 86: {
  10223. character: "V",
  10224. id: "toggleVideoPopover",
  10225. function: APP.UI.toggleVideo
  10226. }
  10227. };
  10228. }
  10229. var KeyboardShortcut = {
  10230. init: function () {
  10231. initShortcutHandlers();
  10232. window.onkeyup = function(e) {
  10233. var keycode = e.which;
  10234. if(!($(":focus").is("input[type=text]") ||
  10235. $(":focus").is("input[type=password]") ||
  10236. $(":focus").is("textarea"))) {
  10237. if (typeof shortcuts[keycode] === "object") {
  10238. shortcuts[keycode].function();
  10239. }
  10240. else if (keycode >= "0".charCodeAt(0) &&
  10241. keycode <= "9".charCodeAt(0)) {
  10242. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10243. }
  10244. //esc while the smileys are visible hides them
  10245. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10246. APP.UI.toggleSmileys();
  10247. }
  10248. };
  10249. window.onkeydown = function(e) {
  10250. if(!($(":focus").is("input[type=text]") ||
  10251. $(":focus").is("input[type=password]") ||
  10252. $(":focus").is("textarea"))) {
  10253. if(e.which === "T".charCodeAt(0)) {
  10254. if(APP.RTC.localAudio.isMuted()) {
  10255. APP.UI.toggleAudio();
  10256. }
  10257. }
  10258. }
  10259. };
  10260. var self = this;
  10261. $('body').popover({ selector: '[data-toggle=popover]',
  10262. trigger: 'click hover',
  10263. content: function() {
  10264. return this.getAttribute("content") +
  10265. self.getShortcut(this.getAttribute("shortcut"));
  10266. }
  10267. });
  10268. },
  10269. /**
  10270. *
  10271. * @param id indicates the popover associated with the shortcut
  10272. * @returns {string} the keyboard shortcut used for the id given
  10273. */
  10274. getShortcut: function (id) {
  10275. for (var keycode in shortcuts) {
  10276. if (shortcuts.hasOwnProperty(keycode)) {
  10277. if (shortcuts[keycode].id === id) {
  10278. return " (" + shortcuts[keycode].character + ")";
  10279. }
  10280. }
  10281. }
  10282. return "";
  10283. }
  10284. };
  10285. module.exports = KeyboardShortcut;
  10286. },{}],46:[function(require,module,exports){
  10287. /* global APP, require, $ */
  10288. /**
  10289. * This module is meant to (eventually) contain and manage all information
  10290. * about members/participants of the conference, so that other modules don't
  10291. * have to do it on their own, and so that other modules can access members'
  10292. * information from a single place.
  10293. *
  10294. * Currently this module only manages information about the support of jingle
  10295. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10296. * be added as needed.
  10297. */
  10298. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10299. var Events = require("../../service/members/Events");
  10300. var EventEmitter = require("events");
  10301. var eventEmitter = new EventEmitter();
  10302. /**
  10303. * The actual container.
  10304. */
  10305. var members = {};
  10306. /**
  10307. * There is at least one member that supports DTMF (i.e. is jigasi).
  10308. */
  10309. var atLeastOneDtmf = false;
  10310. function registerListeners() {
  10311. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10312. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10313. }
  10314. /**
  10315. * Handles a new member joining the MUC.
  10316. */
  10317. function onMucMemberJoined(jid, id, displayName) {
  10318. var member = {
  10319. displayName: displayName
  10320. };
  10321. APP.xmpp.getConnection().disco.info(
  10322. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10323. members[jid] = member;
  10324. }
  10325. /**
  10326. * Handles a member leaving the MUC.
  10327. */
  10328. function onMucMemberLeft(jid) {
  10329. delete members[jid];
  10330. updateAtLeastOneDtmf();
  10331. }
  10332. /**
  10333. * Handles the reception of a disco#info packet from a particular JID.
  10334. * @param jid the JID sending the packet.
  10335. * @param iq the packet.
  10336. */
  10337. function onDiscoInfoReceived(jid, iq) {
  10338. if (!members[jid])
  10339. return;
  10340. var supportsDtmf
  10341. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10342. updateDtmf(jid, supportsDtmf);
  10343. }
  10344. /**
  10345. * Updates the 'supportsDtmf' field for a member.
  10346. * @param jid the jid of the member.
  10347. * @param newValue the new value for the 'supportsDtmf' field.
  10348. */
  10349. function updateDtmf(jid, newValue) {
  10350. var oldValue = members[jid].supportsDtmf;
  10351. members[jid].supportsDtmf = newValue;
  10352. if (newValue != oldValue) {
  10353. updateAtLeastOneDtmf();
  10354. }
  10355. }
  10356. /**
  10357. * Checks each member's 'supportsDtmf' field and updates
  10358. * 'atLastOneSupportsDtmf'.
  10359. */
  10360. function updateAtLeastOneDtmf() {
  10361. var newAtLeastOneDtmf = false;
  10362. for (var key in members) {
  10363. if (typeof members[key].supportsDtmf !== 'undefined'
  10364. && members[key].supportsDtmf) {
  10365. newAtLeastOneDtmf= true;
  10366. break;
  10367. }
  10368. }
  10369. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10370. atLeastOneDtmf = newAtLeastOneDtmf;
  10371. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10372. }
  10373. }
  10374. /**
  10375. * Exported interface.
  10376. */
  10377. var Members = {
  10378. start: function() {
  10379. registerListeners();
  10380. },
  10381. addListener: function(type, listener) {
  10382. eventEmitter.on(type, listener);
  10383. },
  10384. removeListener: function (type, listener) {
  10385. eventEmitter.removeListener(type, listener);
  10386. },
  10387. size: function () {
  10388. return Object.keys(members).length;
  10389. },
  10390. getMembers: function () {
  10391. return members;
  10392. }
  10393. };
  10394. module.exports = Members;
  10395. },{"../../service/members/Events":111,"../../service/xmpp/XMPPEvents":113,"events":114}],47:[function(require,module,exports){
  10396. var email = '';
  10397. var displayName = '';
  10398. var userId;
  10399. var language = null;
  10400. function supportsLocalStorage() {
  10401. try {
  10402. return 'localStorage' in window && window.localStorage !== null;
  10403. } catch (e) {
  10404. console.log("localstorage is not supported");
  10405. return false;
  10406. }
  10407. }
  10408. function generateUniqueId() {
  10409. function _p8() {
  10410. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10411. }
  10412. return _p8() + _p8() + _p8() + _p8();
  10413. }
  10414. if (supportsLocalStorage()) {
  10415. if (!window.localStorage.jitsiMeetId) {
  10416. window.localStorage.jitsiMeetId = generateUniqueId();
  10417. console.log("generated id", window.localStorage.jitsiMeetId);
  10418. }
  10419. userId = window.localStorage.jitsiMeetId || '';
  10420. email = window.localStorage.email || '';
  10421. displayName = window.localStorage.displayname || '';
  10422. language = window.localStorage.language;
  10423. } else {
  10424. console.log("local storage is not supported");
  10425. userId = generateUniqueId();
  10426. }
  10427. var Settings = {
  10428. setDisplayName: function (newDisplayName) {
  10429. displayName = newDisplayName;
  10430. window.localStorage.displayname = displayName;
  10431. return displayName;
  10432. },
  10433. setEmail: function (newEmail) {
  10434. email = newEmail;
  10435. window.localStorage.email = newEmail;
  10436. return email;
  10437. },
  10438. getSettings: function () {
  10439. return {
  10440. email: email,
  10441. displayName: displayName,
  10442. uid: userId,
  10443. language: language
  10444. };
  10445. },
  10446. setLanguage: function (lang) {
  10447. language = lang;
  10448. window.localStorage.language = lang;
  10449. }
  10450. };
  10451. module.exports = Settings;
  10452. },{}],48:[function(require,module,exports){
  10453. /* global config, $, APP, Strophe, callstats */
  10454. var callStats = null;
  10455. function initCallback (err, msg) {
  10456. console.log("Initializing Status: err="+err+" msg="+msg);
  10457. }
  10458. var CallStats = {
  10459. init: function (jingleSession) {
  10460. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10461. return;
  10462. callStats = new callstats($,io,jsSHA);
  10463. this.session = jingleSession;
  10464. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10465. this.userID = APP.xmpp.myResource();
  10466. var location = window.location;
  10467. this.confID = location.protocol + "//" +
  10468. location.hostname + location.pathname;
  10469. //userID is generated or given by the origin server
  10470. callStats.initialize(config.callStatsID,
  10471. config.callStatsSecret,
  10472. this.userID,
  10473. initCallback);
  10474. var usage = callStats.fabricUsage.multiplex;
  10475. callStats.addNewFabric(this.peerconnection,
  10476. Strophe.getResourceFromJid(jingleSession.peerjid),
  10477. usage,
  10478. this.confID,
  10479. this.pcCallback.bind(this));
  10480. },
  10481. pcCallback: function (err, msg) {
  10482. if (!callStats)
  10483. return;
  10484. console.log("Monitoring status: "+ err + " msg: " + msg);
  10485. callStats.sendFabricEvent(this.peerconnection,
  10486. callStats.fabricEvent.fabricSetup, this.confID);
  10487. },
  10488. sendMuteEvent: function (mute, type) {
  10489. if (!callStats)
  10490. return;
  10491. var event = null;
  10492. if (type === "video") {
  10493. event = (mute? callStats.fabricEvent.videoPause :
  10494. callStats.fabricEvent.videoResume);
  10495. }
  10496. else {
  10497. event = (mute? callStats.fabricEvent.audioMute :
  10498. callStats.fabricEvent.audioUnmute);
  10499. }
  10500. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10501. },
  10502. sendTerminateEvent: function () {
  10503. if(!callStats) {
  10504. return;
  10505. }
  10506. callStats.sendFabricEvent(this.peerconnection,
  10507. callStats.fabricEvent.fabricTerminated, this.confID);
  10508. },
  10509. sendSetupFailedEvent: function () {
  10510. if(!callStats) {
  10511. return;
  10512. }
  10513. callStats.sendFabricEvent(this.peerconnection,
  10514. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10515. }
  10516. };
  10517. module.exports = CallStats;
  10518. },{}],49:[function(require,module,exports){
  10519. /* global config */
  10520. /**
  10521. * Provides statistics for the local stream.
  10522. */
  10523. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10524. /**
  10525. * Size of the webaudio analyzer buffer.
  10526. * @type {number}
  10527. */
  10528. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10529. /**
  10530. * Value of the webaudio analyzer smoothing time parameter.
  10531. * @type {number}
  10532. */
  10533. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10534. /**
  10535. * Converts time domain data array to audio level.
  10536. * @param samples the time domain data array.
  10537. * @returns {number} the audio level
  10538. */
  10539. function timeDomainDataToAudioLevel(samples) {
  10540. var maxVolume = 0;
  10541. var length = samples.length;
  10542. for (var i = 0; i < length; i++) {
  10543. if (maxVolume < samples[i])
  10544. maxVolume = samples[i];
  10545. }
  10546. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10547. }
  10548. /**
  10549. * Animates audio level change
  10550. * @param newLevel the new audio level
  10551. * @param lastLevel the last audio level
  10552. * @returns {Number} the audio level to be set
  10553. */
  10554. function animateLevel(newLevel, lastLevel) {
  10555. var value = 0;
  10556. var diff = lastLevel - newLevel;
  10557. if(diff > 0.2) {
  10558. value = lastLevel - 0.2;
  10559. }
  10560. else if(diff < -0.4) {
  10561. value = lastLevel + 0.4;
  10562. }
  10563. else {
  10564. value = newLevel;
  10565. }
  10566. return parseFloat(value.toFixed(3));
  10567. }
  10568. /**
  10569. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10570. *
  10571. * @param stream the local stream
  10572. * @param interval stats refresh interval given in ms.
  10573. * @constructor
  10574. */
  10575. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10576. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10577. this.stream = stream;
  10578. this.intervalId = null;
  10579. this.intervalMilis = interval;
  10580. this.eventEmitter = eventEmitter;
  10581. this.audioLevel = 0;
  10582. this.statisticsService = statisticsService;
  10583. }
  10584. /**
  10585. * Starts the collecting the statistics.
  10586. */
  10587. LocalStatsCollector.prototype.start = function () {
  10588. if (config.disableAudioLevels || !window.AudioContext ||
  10589. RTCBrowserType.isTemasysPluginUsed())
  10590. return;
  10591. var context = new AudioContext();
  10592. var analyser = context.createAnalyser();
  10593. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10594. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10595. var source = context.createMediaStreamSource(this.stream);
  10596. source.connect(analyser);
  10597. var self = this;
  10598. this.intervalId = setInterval(
  10599. function () {
  10600. var array = new Uint8Array(analyser.frequencyBinCount);
  10601. analyser.getByteTimeDomainData(array);
  10602. var audioLevel = timeDomainDataToAudioLevel(array);
  10603. if (audioLevel != self.audioLevel) {
  10604. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10605. self.eventEmitter.emit(
  10606. "statistics.audioLevel",
  10607. self.statisticsService.LOCAL_JID,
  10608. self.audioLevel);
  10609. }
  10610. },
  10611. this.intervalMilis
  10612. );
  10613. };
  10614. /**
  10615. * Stops collecting the statistics.
  10616. */
  10617. LocalStatsCollector.prototype.stop = function () {
  10618. if (this.intervalId) {
  10619. clearInterval(this.intervalId);
  10620. this.intervalId = null;
  10621. }
  10622. };
  10623. module.exports = LocalStatsCollector;
  10624. },{"../RTC/RTCBrowserType":8}],50:[function(require,module,exports){
  10625. /* global require, ssrc2jid */
  10626. /* jshint -W117 */
  10627. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10628. /* Whether we support the browser we are running into for logging statistics */
  10629. var browserSupported = RTCBrowserType.isChrome() ||
  10630. RTCBrowserType.isOpera();
  10631. /**
  10632. * Calculates packet lost percent using the number of lost packets and the
  10633. * number of all packet.
  10634. * @param lostPackets the number of lost packets
  10635. * @param totalPackets the number of all packets.
  10636. * @returns {number} packet loss percent
  10637. */
  10638. function calculatePacketLoss(lostPackets, totalPackets) {
  10639. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10640. return 0;
  10641. return Math.round((lostPackets/totalPackets)*100);
  10642. }
  10643. function getStatValue(item, name) {
  10644. var browserType = RTCBrowserType.getBrowserType();
  10645. if (!keyMap[browserType][name])
  10646. throw "The property isn't supported!";
  10647. var key = keyMap[browserType][name];
  10648. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10649. item.stat(key) : item[key];
  10650. }
  10651. /**
  10652. * Peer statistics data holder.
  10653. * @constructor
  10654. */
  10655. function PeerStats()
  10656. {
  10657. this.ssrc2Loss = {};
  10658. this.ssrc2AudioLevel = {};
  10659. this.ssrc2bitrate = {};
  10660. this.ssrc2resolution = {};
  10661. }
  10662. /**
  10663. * The bandwidth
  10664. * @type {{}}
  10665. */
  10666. PeerStats.bandwidth = {};
  10667. /**
  10668. * The bit rate
  10669. * @type {{}}
  10670. */
  10671. PeerStats.bitrate = {};
  10672. /**
  10673. * The packet loss rate
  10674. * @type {{}}
  10675. */
  10676. PeerStats.packetLoss = null;
  10677. /**
  10678. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10679. * represented by this instance.
  10680. * @param ssrc audio or video RTP stream SSRC.
  10681. * @param lossRate new packet loss rate value to be set.
  10682. */
  10683. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10684. {
  10685. this.ssrc2Loss[ssrc] = lossRate;
  10686. };
  10687. /**
  10688. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10689. * represented by this instance.
  10690. * @param ssrc audio or video RTP stream SSRC.
  10691. * @param resolution new resolution value to be set.
  10692. */
  10693. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10694. {
  10695. if(resolution === null && this.ssrc2resolution[ssrc])
  10696. {
  10697. delete this.ssrc2resolution[ssrc];
  10698. }
  10699. else if(resolution !== null)
  10700. this.ssrc2resolution[ssrc] = resolution;
  10701. };
  10702. /**
  10703. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10704. * represented by this instance.
  10705. * @param ssrc audio or video RTP stream SSRC.
  10706. * @param bitrate new bitrate value to be set.
  10707. */
  10708. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10709. {
  10710. if(this.ssrc2bitrate[ssrc])
  10711. {
  10712. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10713. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10714. }
  10715. else {
  10716. this.ssrc2bitrate[ssrc] = bitrate;
  10717. }
  10718. };
  10719. /**
  10720. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10721. * the stream which belongs to the peer represented by this instance.
  10722. * @param ssrc RTP stream SSRC for which current audio level value will be
  10723. * updated.
  10724. * @param audioLevel the new audio level value to be set. Value is truncated to
  10725. * fit the range from 0 to 1.
  10726. */
  10727. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10728. {
  10729. // Range limit 0 - 1
  10730. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10731. };
  10732. function formatAudioLevel(audioLevel) {
  10733. return Math.min(Math.max(audioLevel, 0), 1);
  10734. }
  10735. /**
  10736. * Array with the transport information.
  10737. * @type {Array}
  10738. */
  10739. PeerStats.transport = [];
  10740. /**
  10741. * <tt>StatsCollector</tt> registers for stats updates of given
  10742. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10743. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10744. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10745. * instance as an event source.
  10746. *
  10747. * @param peerconnection webRTC peer connection object.
  10748. * @param interval stats refresh interval given in ms.
  10749. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10750. * called on stats update.
  10751. * @constructor
  10752. */
  10753. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10754. {
  10755. this.peerconnection = peerconnection;
  10756. this.baselineAudioLevelsReport = null;
  10757. this.currentAudioLevelsReport = null;
  10758. this.currentStatsReport = null;
  10759. this.baselineStatsReport = null;
  10760. this.audioLevelsIntervalId = null;
  10761. this.eventEmitter = eventEmitter;
  10762. /**
  10763. * Gather PeerConnection stats once every this many milliseconds.
  10764. */
  10765. this.GATHER_INTERVAL = 15000;
  10766. /**
  10767. * Log stats via the focus once every this many milliseconds.
  10768. */
  10769. this.LOG_INTERVAL = 60000;
  10770. /**
  10771. * Gather stats and store them in this.statsToBeLogged.
  10772. */
  10773. this.gatherStatsIntervalId = null;
  10774. /**
  10775. * Send the stats already saved in this.statsToBeLogged to be logged via
  10776. * the focus.
  10777. */
  10778. this.logStatsIntervalId = null;
  10779. /**
  10780. * Stores the statistics which will be send to the focus to be logged.
  10781. */
  10782. this.statsToBeLogged =
  10783. {
  10784. timestamps: [],
  10785. stats: {}
  10786. };
  10787. // Updates stats interval
  10788. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10789. this.statsIntervalId = null;
  10790. this.statsIntervalMilis = statsInterval;
  10791. // Map of jids to PeerStats
  10792. this.jid2stats = {};
  10793. }
  10794. module.exports = StatsCollector;
  10795. /**
  10796. * Stops stats updates.
  10797. */
  10798. StatsCollector.prototype.stop = function () {
  10799. if (this.audioLevelsIntervalId) {
  10800. clearInterval(this.audioLevelsIntervalId);
  10801. this.audioLevelsIntervalId = null;
  10802. }
  10803. if (this.statsIntervalId)
  10804. {
  10805. clearInterval(this.statsIntervalId);
  10806. this.statsIntervalId = null;
  10807. }
  10808. if(this.logStatsIntervalId)
  10809. {
  10810. clearInterval(this.logStatsIntervalId);
  10811. this.logStatsIntervalId = null;
  10812. }
  10813. if(this.gatherStatsIntervalId)
  10814. {
  10815. clearInterval(this.gatherStatsIntervalId);
  10816. this.gatherStatsIntervalId = null;
  10817. }
  10818. };
  10819. /**
  10820. * Callback passed to <tt>getStats</tt> method.
  10821. * @param error an error that occurred on <tt>getStats</tt> call.
  10822. */
  10823. StatsCollector.prototype.errorCallback = function (error)
  10824. {
  10825. console.error("Get stats error", error);
  10826. this.stop();
  10827. };
  10828. /**
  10829. * Starts stats updates.
  10830. */
  10831. StatsCollector.prototype.start = function ()
  10832. {
  10833. var self = this;
  10834. if (!config.disableAudioLevels) {
  10835. this.audioLevelsIntervalId = setInterval(
  10836. function () {
  10837. // Interval updates
  10838. self.peerconnection.getStats(
  10839. function (report) {
  10840. var results = null;
  10841. if (!report || !report.result ||
  10842. typeof report.result != 'function') {
  10843. results = report;
  10844. }
  10845. else {
  10846. results = report.result();
  10847. }
  10848. //console.error("Got interval report", results);
  10849. self.currentAudioLevelsReport = results;
  10850. self.processAudioLevelReport();
  10851. self.baselineAudioLevelsReport =
  10852. self.currentAudioLevelsReport;
  10853. },
  10854. self.errorCallback
  10855. );
  10856. },
  10857. self.audioLevelsIntervalMilis
  10858. );
  10859. }
  10860. if (!config.disableStats && browserSupported) {
  10861. this.statsIntervalId = setInterval(
  10862. function () {
  10863. // Interval updates
  10864. self.peerconnection.getStats(
  10865. function (report) {
  10866. var results = null;
  10867. if (!report || !report.result ||
  10868. typeof report.result != 'function') {
  10869. //firefox
  10870. results = report;
  10871. }
  10872. else {
  10873. //chrome
  10874. results = report.result();
  10875. }
  10876. //console.error("Got interval report", results);
  10877. self.currentStatsReport = results;
  10878. try {
  10879. self.processStatsReport();
  10880. }
  10881. catch (e) {
  10882. console.error("Unsupported key:" + e, e);
  10883. }
  10884. self.baselineStatsReport = self.currentStatsReport;
  10885. },
  10886. self.errorCallback
  10887. );
  10888. },
  10889. self.statsIntervalMilis
  10890. );
  10891. }
  10892. if (config.logStats && browserSupported) {
  10893. this.gatherStatsIntervalId = setInterval(
  10894. function () {
  10895. self.peerconnection.getStats(
  10896. function (report) {
  10897. self.addStatsToBeLogged(report.result());
  10898. },
  10899. function () {
  10900. }
  10901. );
  10902. },
  10903. this.GATHER_INTERVAL
  10904. );
  10905. this.logStatsIntervalId = setInterval(
  10906. function() { self.logStats(); },
  10907. this.LOG_INTERVAL);
  10908. }
  10909. };
  10910. /**
  10911. * Checks whether a certain record should be included in the logged statistics.
  10912. */
  10913. function acceptStat(reportId, reportType, statName) {
  10914. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10915. return false;
  10916. if (reportType == "ssrc") {
  10917. if (statName == "googTrackId" ||
  10918. statName == "transportId" ||
  10919. statName == "ssrc")
  10920. return false;
  10921. }
  10922. return true;
  10923. }
  10924. /**
  10925. * Checks whether a certain record should be included in the logged statistics.
  10926. */
  10927. function acceptReport(id, type) {
  10928. if (id.substring(0, 15) == "googCertificate" ||
  10929. id.substring(0, 9) == "googTrack" ||
  10930. id.substring(0, 20) == "googLibjingleSession")
  10931. return false;
  10932. if (type == "googComponent")
  10933. return false;
  10934. return true;
  10935. }
  10936. /**
  10937. * Converts the stats to the format used for logging, and saves the data in
  10938. * this.statsToBeLogged.
  10939. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10940. */
  10941. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10942. var self = this;
  10943. var num_records = this.statsToBeLogged.timestamps.length;
  10944. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10945. reports.map(function (report) {
  10946. if (!acceptReport(report.id, report.type))
  10947. return;
  10948. var stat = self.statsToBeLogged.stats[report.id];
  10949. if (!stat) {
  10950. stat = self.statsToBeLogged.stats[report.id] = {};
  10951. }
  10952. stat.type = report.type;
  10953. report.names().map(function (name) {
  10954. if (!acceptStat(report.id, report.type, name))
  10955. return;
  10956. var values = stat[name];
  10957. if (!values) {
  10958. values = stat[name] = [];
  10959. }
  10960. while (values.length < num_records) {
  10961. values.push(null);
  10962. }
  10963. values.push(report.stat(name));
  10964. });
  10965. });
  10966. };
  10967. StatsCollector.prototype.logStats = function () {
  10968. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10969. return;
  10970. // Reset the stats
  10971. this.statsToBeLogged.stats = {};
  10972. this.statsToBeLogged.timestamps = [];
  10973. };
  10974. var keyMap = {};
  10975. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10976. "ssrc": "ssrc",
  10977. "packetsReceived": "packetsReceived",
  10978. "packetsLost": "packetsLost",
  10979. "packetsSent": "packetsSent",
  10980. "bytesReceived": "bytesReceived",
  10981. "bytesSent": "bytesSent"
  10982. };
  10983. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10984. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10985. "sendBandwidth": "googAvailableSendBandwidth",
  10986. "remoteAddress": "googRemoteAddress",
  10987. "transportType": "googTransportType",
  10988. "localAddress": "googLocalAddress",
  10989. "activeConnection": "googActiveConnection",
  10990. "ssrc": "ssrc",
  10991. "packetsReceived": "packetsReceived",
  10992. "packetsSent": "packetsSent",
  10993. "packetsLost": "packetsLost",
  10994. "bytesReceived": "bytesReceived",
  10995. "bytesSent": "bytesSent",
  10996. "googFrameHeightReceived": "googFrameHeightReceived",
  10997. "googFrameWidthReceived": "googFrameWidthReceived",
  10998. "googFrameHeightSent": "googFrameHeightSent",
  10999. "googFrameWidthSent": "googFrameWidthSent",
  11000. "audioInputLevel": "audioInputLevel",
  11001. "audioOutputLevel": "audioOutputLevel"
  11002. };
  11003. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11004. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11005. /**
  11006. * Stats processing logic.
  11007. */
  11008. StatsCollector.prototype.processStatsReport = function () {
  11009. if (!this.baselineStatsReport) {
  11010. return;
  11011. }
  11012. for (var idx in this.currentStatsReport) {
  11013. var now = this.currentStatsReport[idx];
  11014. try {
  11015. if (getStatValue(now, 'receiveBandwidth') ||
  11016. getStatValue(now, 'sendBandwidth')) {
  11017. PeerStats.bandwidth = {
  11018. "download": Math.round(
  11019. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11020. "upload": Math.round(
  11021. (getStatValue(now, 'sendBandwidth')) / 1000)
  11022. };
  11023. }
  11024. }
  11025. catch(e){/*not supported*/}
  11026. if(now.type == 'googCandidatePair')
  11027. {
  11028. var ip, type, localIP, active;
  11029. try {
  11030. ip = getStatValue(now, 'remoteAddress');
  11031. type = getStatValue(now, "transportType");
  11032. localIP = getStatValue(now, "localAddress");
  11033. active = getStatValue(now, "activeConnection");
  11034. }
  11035. catch(e){/*not supported*/}
  11036. if(!ip || !type || !localIP || active != "true")
  11037. continue;
  11038. var addressSaved = false;
  11039. for(var i = 0; i < PeerStats.transport.length; i++)
  11040. {
  11041. if(PeerStats.transport[i].ip == ip &&
  11042. PeerStats.transport[i].type == type &&
  11043. PeerStats.transport[i].localip == localIP)
  11044. {
  11045. addressSaved = true;
  11046. }
  11047. }
  11048. if(addressSaved)
  11049. continue;
  11050. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11051. continue;
  11052. }
  11053. if(now.type == "candidatepair")
  11054. {
  11055. if(now.state == "succeeded")
  11056. continue;
  11057. var local = this.currentStatsReport[now.localCandidateId];
  11058. var remote = this.currentStatsReport[now.remoteCandidateId];
  11059. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11060. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11061. }
  11062. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11063. now.type != "inboundrtp") {
  11064. continue;
  11065. }
  11066. var before = this.baselineStatsReport[idx];
  11067. if (!before) {
  11068. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11069. continue;
  11070. }
  11071. var ssrc = getStatValue(now, 'ssrc');
  11072. if(!ssrc)
  11073. continue;
  11074. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11075. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11076. console.warn("No jid for ssrc: " + ssrc);
  11077. continue;
  11078. }
  11079. var jidStats = this.jid2stats[jid];
  11080. if (!jidStats) {
  11081. jidStats = new PeerStats();
  11082. this.jid2stats[jid] = jidStats;
  11083. }
  11084. var isDownloadStream = true;
  11085. var key = 'packetsReceived';
  11086. if (!getStatValue(now, key))
  11087. {
  11088. isDownloadStream = false;
  11089. key = 'packetsSent';
  11090. if (!getStatValue(now, key))
  11091. {
  11092. console.warn("No packetsReceived nor packetSent stat found");
  11093. continue;
  11094. }
  11095. }
  11096. var packetsNow = getStatValue(now, key);
  11097. if(!packetsNow || packetsNow < 0)
  11098. packetsNow = 0;
  11099. var packetsBefore = getStatValue(before, key);
  11100. if(!packetsBefore || packetsBefore < 0)
  11101. packetsBefore = 0;
  11102. var packetRate = packetsNow - packetsBefore;
  11103. if(!packetRate || packetRate < 0)
  11104. packetRate = 0;
  11105. var currentLoss = getStatValue(now, 'packetsLost');
  11106. if(!currentLoss || currentLoss < 0)
  11107. currentLoss = 0;
  11108. var previousLoss = getStatValue(before, 'packetsLost');
  11109. if(!previousLoss || previousLoss < 0)
  11110. previousLoss = 0;
  11111. var lossRate = currentLoss - previousLoss;
  11112. if(!lossRate || lossRate < 0)
  11113. lossRate = 0;
  11114. var packetsTotal = (packetRate + lossRate);
  11115. jidStats.setSsrcLoss(ssrc,
  11116. {"packetsTotal": packetsTotal,
  11117. "packetsLost": lossRate,
  11118. "isDownloadStream": isDownloadStream});
  11119. var bytesReceived = 0, bytesSent = 0;
  11120. if(getStatValue(now, "bytesReceived"))
  11121. {
  11122. bytesReceived = getStatValue(now, "bytesReceived") -
  11123. getStatValue(before, "bytesReceived");
  11124. }
  11125. if(getStatValue(now, "bytesSent"))
  11126. {
  11127. bytesSent = getStatValue(now, "bytesSent") -
  11128. getStatValue(before, "bytesSent");
  11129. }
  11130. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11131. if(bytesReceived <= 0 || time <= 0)
  11132. {
  11133. bytesReceived = 0;
  11134. }
  11135. else
  11136. {
  11137. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11138. }
  11139. if(bytesSent <= 0 || time <= 0)
  11140. {
  11141. bytesSent = 0;
  11142. }
  11143. else
  11144. {
  11145. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11146. }
  11147. jidStats.setSsrcBitrate(ssrc, {
  11148. "download": bytesReceived,
  11149. "upload": bytesSent});
  11150. var resolution = {height: null, width: null};
  11151. try {
  11152. if (getStatValue(now, "googFrameHeightReceived") &&
  11153. getStatValue(now, "googFrameWidthReceived")) {
  11154. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11155. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11156. }
  11157. else if (getStatValue(now, "googFrameHeightSent") &&
  11158. getStatValue(now, "googFrameWidthSent")) {
  11159. resolution.height = getStatValue(now, "googFrameHeightSent");
  11160. resolution.width = getStatValue(now, "googFrameWidthSent");
  11161. }
  11162. }
  11163. catch(e){/*not supported*/}
  11164. if(resolution.height && resolution.width)
  11165. {
  11166. jidStats.setSsrcResolution(ssrc, resolution);
  11167. }
  11168. else
  11169. {
  11170. jidStats.setSsrcResolution(ssrc, null);
  11171. }
  11172. }
  11173. var self = this;
  11174. // Jid stats
  11175. var totalPackets = {download: 0, upload: 0};
  11176. var lostPackets = {download: 0, upload: 0};
  11177. var bitrateDownload = 0;
  11178. var bitrateUpload = 0;
  11179. var resolutions = {};
  11180. Object.keys(this.jid2stats).forEach(
  11181. function (jid)
  11182. {
  11183. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11184. function (ssrc)
  11185. {
  11186. var type = "upload";
  11187. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11188. type = "download";
  11189. totalPackets[type] +=
  11190. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11191. lostPackets[type] +=
  11192. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11193. }
  11194. );
  11195. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11196. function (ssrc) {
  11197. bitrateDownload +=
  11198. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11199. bitrateUpload +=
  11200. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11201. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11202. }
  11203. );
  11204. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11205. }
  11206. );
  11207. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11208. PeerStats.packetLoss = {
  11209. total:
  11210. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11211. totalPackets.download + totalPackets.upload),
  11212. download:
  11213. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11214. upload:
  11215. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11216. };
  11217. this.eventEmitter.emit("statistics.connectionstats",
  11218. {
  11219. "bitrate": PeerStats.bitrate,
  11220. "packetLoss": PeerStats.packetLoss,
  11221. "bandwidth": PeerStats.bandwidth,
  11222. "resolution": resolutions,
  11223. "transport": PeerStats.transport
  11224. });
  11225. PeerStats.transport = [];
  11226. };
  11227. /**
  11228. * Stats processing logic.
  11229. */
  11230. StatsCollector.prototype.processAudioLevelReport = function () {
  11231. if (!this.baselineAudioLevelsReport) {
  11232. return;
  11233. }
  11234. for (var idx in this.currentAudioLevelsReport) {
  11235. var now = this.currentAudioLevelsReport[idx];
  11236. if (now.type != 'ssrc') {
  11237. continue;
  11238. }
  11239. var before = this.baselineAudioLevelsReport[idx];
  11240. if (!before) {
  11241. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11242. continue;
  11243. }
  11244. var ssrc = getStatValue(now, 'ssrc');
  11245. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11246. if (!jid) {
  11247. if((Date.now() - now.timestamp) < 3000)
  11248. console.warn("No jid for ssrc: " + ssrc);
  11249. continue;
  11250. }
  11251. var jidStats = this.jid2stats[jid];
  11252. if (!jidStats) {
  11253. jidStats = new PeerStats();
  11254. this.jid2stats[jid] = jidStats;
  11255. }
  11256. // Audio level
  11257. var audioLevel = null;
  11258. try {
  11259. audioLevel = getStatValue(now, 'audioInputLevel');
  11260. if (!audioLevel)
  11261. audioLevel = getStatValue(now, 'audioOutputLevel');
  11262. }
  11263. catch(e) {/*not supported*/
  11264. console.warn("Audio Levels are not available in the statistics.");
  11265. clearInterval(this.audioLevelsIntervalId);
  11266. return;
  11267. }
  11268. if (audioLevel) {
  11269. // TODO: can't find specs about what this value really is,
  11270. // but it seems to vary between 0 and around 32k.
  11271. audioLevel = audioLevel / 32767;
  11272. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11273. if(jid != APP.xmpp.myJid())
  11274. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11275. }
  11276. }
  11277. };
  11278. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11279. /* global require, APP */
  11280. /**
  11281. * Created by hristo on 8/4/14.
  11282. */
  11283. var LocalStats = require("./LocalStatsCollector.js");
  11284. var RTPStats = require("./RTPStatsCollector.js");
  11285. var EventEmitter = require("events");
  11286. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11287. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11288. var CallStats = require("./CallStats");
  11289. var RTCEvents = require("../../service/RTC/RTCEvents");
  11290. var eventEmitter = new EventEmitter();
  11291. var localStats = null;
  11292. var rtpStats = null;
  11293. function stopLocal() {
  11294. if (localStats) {
  11295. localStats.stop();
  11296. localStats = null;
  11297. }
  11298. }
  11299. function stopRemote() {
  11300. if (rtpStats) {
  11301. rtpStats.stop();
  11302. eventEmitter.emit("statistics.stop");
  11303. rtpStats = null;
  11304. }
  11305. }
  11306. function startRemoteStats (peerconnection) {
  11307. if (rtpStats) {
  11308. rtpStats.stop();
  11309. }
  11310. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11311. rtpStats.start();
  11312. }
  11313. function onStreamCreated(stream) {
  11314. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11315. return;
  11316. }
  11317. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11318. eventEmitter);
  11319. localStats.start();
  11320. }
  11321. function onDisposeConference(onUnload) {
  11322. CallStats.sendTerminateEvent();
  11323. stopRemote();
  11324. if(onUnload) {
  11325. stopLocal();
  11326. eventEmitter.removeAllListeners();
  11327. }
  11328. }
  11329. var statistics = {
  11330. /**
  11331. * Indicates that this audio level is for local jid.
  11332. * @type {string}
  11333. */
  11334. LOCAL_JID: 'local',
  11335. addAudioLevelListener: function(listener)
  11336. {
  11337. eventEmitter.on("statistics.audioLevel", listener);
  11338. },
  11339. removeAudioLevelListener: function(listener)
  11340. {
  11341. eventEmitter.removeListener("statistics.audioLevel", listener);
  11342. },
  11343. addConnectionStatsListener: function(listener)
  11344. {
  11345. eventEmitter.on("statistics.connectionstats", listener);
  11346. },
  11347. removeConnectionStatsListener: function(listener)
  11348. {
  11349. eventEmitter.removeListener("statistics.connectionstats", listener);
  11350. },
  11351. addRemoteStatsStopListener: function(listener)
  11352. {
  11353. eventEmitter.on("statistics.stop", listener);
  11354. },
  11355. removeRemoteStatsStopListener: function(listener)
  11356. {
  11357. eventEmitter.removeListener("statistics.stop", listener);
  11358. },
  11359. stop: function () {
  11360. stopLocal();
  11361. stopRemote();
  11362. if(eventEmitter)
  11363. {
  11364. eventEmitter.removeAllListeners();
  11365. }
  11366. },
  11367. stopRemoteStatistics: function()
  11368. {
  11369. stopRemote();
  11370. },
  11371. start: function () {
  11372. APP.RTC.addStreamListener(onStreamCreated,
  11373. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11374. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11375. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11376. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11377. startRemoteStats(event.peerconnection);
  11378. // CallStats.init(event);
  11379. });
  11380. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11381. CallStats.init(session);
  11382. });
  11383. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11384. CallStats.sendMuteEvent(mute, "audio");
  11385. });
  11386. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11387. CallStats.sendSetupFailedEvent();
  11388. });
  11389. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11390. CallStats.sendMuteEvent(mute, "video");
  11391. });
  11392. }
  11393. };
  11394. module.exports = statistics;
  11395. },{"../../service/RTC/RTCEvents":104,"../../service/RTC/StreamEventTypes.js":106,"../../service/xmpp/XMPPEvents":113,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":114}],52:[function(require,module,exports){
  11396. /* global $, require, config, interfaceConfig */
  11397. var i18n = require("i18next-client");
  11398. var languages = require("../../service/translation/languages");
  11399. var Settings = require("../settings/Settings");
  11400. var DEFAULT_LANG = languages.EN;
  11401. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11402. return value.replace("__app__", interfaceConfig.APP_NAME);
  11403. });
  11404. var defaultOptions = {
  11405. detectLngQS: "lang",
  11406. useCookie: false,
  11407. fallbackLng: DEFAULT_LANG,
  11408. load: "unspecific",
  11409. resGetPath: 'lang/__ns__-__lng__.json',
  11410. ns: {
  11411. namespaces: ['main', 'languages'],
  11412. defaultNs: 'main'
  11413. },
  11414. lngWhitelist : languages.getLanguages(),
  11415. fallbackOnNull: true,
  11416. fallbackOnEmpty: true,
  11417. useDataAttrOptions: true,
  11418. app: interfaceConfig.APP_NAME,
  11419. getAsync: false,
  11420. defaultValueFromContent: false,
  11421. customLoad: function(lng, ns, options, done) {
  11422. var resPath = "lang/__ns__-__lng__.json";
  11423. if(lng === languages.EN)
  11424. resPath = "lang/__ns__.json";
  11425. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11426. i18n.functions.ajax({
  11427. url: url,
  11428. success: function(data, status, xhr) {
  11429. i18n.functions.log('loaded: ' + url);
  11430. done(null, data);
  11431. },
  11432. error : function(xhr, status, error) {
  11433. if ((status && status == 200) ||
  11434. (xhr && xhr.status && xhr.status == 200)) {
  11435. // file loaded but invalid json, stop waste time !
  11436. i18n.functions.error('There is a typo in: ' + url);
  11437. } else if ((status && status == 404) ||
  11438. (xhr && xhr.status && xhr.status == 404)) {
  11439. i18n.functions.log('Does not exist: ' + url);
  11440. } else {
  11441. var theStatus = status ? status :
  11442. ((xhr && xhr.status) ? xhr.status : null);
  11443. i18n.functions.log(theStatus + ' when loading ' + url);
  11444. }
  11445. done(error, {});
  11446. },
  11447. dataType: "json",
  11448. async : options.getAsync
  11449. });
  11450. }
  11451. // options for caching
  11452. // useLocalStorage: true,
  11453. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11454. };
  11455. function initCompleted(t) {
  11456. $("[data-i18n]").i18n();
  11457. }
  11458. function checkForParameter() {
  11459. var query = window.location.search.substring(1);
  11460. var vars = query.split("&");
  11461. for (var i=0;i<vars.length;i++) {
  11462. var pair = vars[i].split("=");
  11463. if(pair[0] == "lang")
  11464. {
  11465. return pair[1];
  11466. }
  11467. }
  11468. return null;
  11469. }
  11470. module.exports = {
  11471. init: function (lang) {
  11472. var options = defaultOptions;
  11473. if(!lang)
  11474. {
  11475. lang = checkForParameter();
  11476. if(!lang)
  11477. {
  11478. var settings = Settings.getSettings();
  11479. if(settings)
  11480. lang = settings.language;
  11481. if(!lang && config.defaultLanguage)
  11482. {
  11483. lang = config.defaultLanguage;
  11484. }
  11485. }
  11486. }
  11487. if(lang) {
  11488. options.lng = lang;
  11489. }
  11490. i18n.init(options, initCompleted);
  11491. },
  11492. translateString: function (key, options) {
  11493. return i18n.t(key, options);
  11494. },
  11495. setLanguage: function (lang) {
  11496. if(!lang)
  11497. lang = DEFAULT_LANG;
  11498. i18n.setLng(lang, defaultOptions, initCompleted);
  11499. },
  11500. getCurrentLanguage: function () {
  11501. return i18n.lng();
  11502. },
  11503. translateElement: function (selector) {
  11504. selector.i18n();
  11505. },
  11506. generateTranslationHTML: function (key, options) {
  11507. var str = "<span data-i18n=\"" + key + "\"";
  11508. if(options)
  11509. {
  11510. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11511. }
  11512. str += ">";
  11513. str += this.translateString(key, options);
  11514. str += "</span>";
  11515. return str;
  11516. }
  11517. };
  11518. },{"../../service/translation/languages":112,"../settings/Settings":47,"i18next-client":69}],53:[function(require,module,exports){
  11519. /* jshint -W117 */
  11520. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11521. var SDPDiffer = require("./SDPDiffer");
  11522. var SDPUtil = require("./SDPUtil");
  11523. var SDP = require("./SDP");
  11524. var async = require("async");
  11525. var transform = require("sdp-transform");
  11526. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11527. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11528. var VideoSSRCHack = require("./VideoSSRCHack");
  11529. // Jingle stuff
  11530. function JingleSession(me, sid, connection, service, eventEmitter) {
  11531. this.me = me;
  11532. this.sid = sid;
  11533. this.connection = connection;
  11534. this.initiator = null;
  11535. this.responder = null;
  11536. this.isInitiator = null;
  11537. this.peerjid = null;
  11538. this.state = null;
  11539. this.localSDP = null;
  11540. this.remoteSDP = null;
  11541. this.relayedStreams = [];
  11542. this.startTime = null;
  11543. this.stopTime = null;
  11544. this.media_constraints = null;
  11545. this.pc_constraints = null;
  11546. this.ice_config = {};
  11547. this.drip_container = [];
  11548. this.service = service;
  11549. this.eventEmitter = eventEmitter;
  11550. this.usetrickle = true;
  11551. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11552. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11553. this.hadstuncandidate = false;
  11554. this.hadturncandidate = false;
  11555. this.lasticecandidate = false;
  11556. this.statsinterval = null;
  11557. this.reason = null;
  11558. this.addssrc = [];
  11559. this.removessrc = [];
  11560. this.pendingop = null;
  11561. this.switchstreams = false;
  11562. this.wait = true;
  11563. this.localStreamsSSRC = null;
  11564. this.ssrcOwners = {};
  11565. this.ssrcVideoTypes = {};
  11566. this.eventEmitter = eventEmitter;
  11567. /**
  11568. * The indicator which determines whether the (local) video has been muted
  11569. * in response to a user command in contrast to an automatic decision made
  11570. * by the application logic.
  11571. */
  11572. this.videoMuteByUser = false;
  11573. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11574. // We start with the queue paused. We resume it when the signaling state is
  11575. // stable and the ice connection state is connected.
  11576. this.modifySourcesQueue.pause();
  11577. }
  11578. JingleSession.prototype.updateModifySourcesQueue = function() {
  11579. var signalingState = this.peerconnection.signalingState;
  11580. var iceConnectionState = this.peerconnection.iceConnectionState;
  11581. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11582. this.modifySourcesQueue.resume();
  11583. } else {
  11584. this.modifySourcesQueue.pause();
  11585. }
  11586. };
  11587. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11588. var self = this;
  11589. if (this.state !== null) {
  11590. console.error('attempt to initiate on session ' + this.sid +
  11591. 'in state ' + this.state);
  11592. return;
  11593. }
  11594. this.isInitiator = isInitiator;
  11595. this.state = 'pending';
  11596. this.initiator = isInitiator ? this.me : peerjid;
  11597. this.responder = !isInitiator ? this.me : peerjid;
  11598. this.peerjid = peerjid;
  11599. this.hadstuncandidate = false;
  11600. this.hadturncandidate = false;
  11601. this.lasticecandidate = false;
  11602. this.isreconnect = false;
  11603. this.peerconnection
  11604. = new TraceablePeerConnection(
  11605. this.connection.jingle.ice_config,
  11606. this.connection.jingle.pc_constraints,
  11607. this);
  11608. this.peerconnection.onicecandidate = function (event) {
  11609. self.sendIceCandidate(event.candidate);
  11610. };
  11611. this.peerconnection.onaddstream = function (event) {
  11612. if (event.stream.id !== 'default') {
  11613. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11614. self.remoteStreamAdded(event);
  11615. } else {
  11616. // This is a recvonly stream. Clients that implement Unified Plan,
  11617. // such as Firefox use recvonly "streams/channels/tracks" for
  11618. // receiving remote stream/tracks, as opposed to Plan B where there
  11619. // are only 3 channels: audio, video and data.
  11620. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11621. }
  11622. };
  11623. this.peerconnection.onremovestream = function (event) {
  11624. // Remove the stream from remoteStreams
  11625. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11626. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11627. };
  11628. this.peerconnection.onsignalingstatechange = function (event) {
  11629. if (!(self && self.peerconnection)) return;
  11630. self.updateModifySourcesQueue();
  11631. };
  11632. /**
  11633. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  11634. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  11635. * RTCPeerConnection.iceConnectionState changes.
  11636. *
  11637. * @param event the event containing information about the change
  11638. */
  11639. this.peerconnection.oniceconnectionstatechange = function (event) {
  11640. if (!(self && self.peerconnection)) return;
  11641. self.updateModifySourcesQueue();
  11642. switch (self.peerconnection.iceConnectionState) {
  11643. case 'connected':
  11644. self.startTime = new Date();
  11645. // Informs interested parties that the connection has been restored.
  11646. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  11647. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  11648. self.isreconnect = false;
  11649. break;
  11650. case 'disconnected':
  11651. self.isreconnect = true;
  11652. self.stopTime = new Date();
  11653. // Informs interested parties that the connection has been interrupted.
  11654. if (self.peerconnection.signalingState === 'stable')
  11655. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  11656. break;
  11657. case 'failed':
  11658. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11659. break;
  11660. }
  11661. onIceConnectionStateChange(self.sid, self);
  11662. };
  11663. this.peerconnection.onnegotiationneeded = function (event) {
  11664. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11665. };
  11666. // add any local and relayed stream
  11667. APP.RTC.localStreams.forEach(function(stream) {
  11668. self.peerconnection.addStream(stream.getOriginalStream());
  11669. });
  11670. this.relayedStreams.forEach(function(stream) {
  11671. self.peerconnection.addStream(stream);
  11672. });
  11673. };
  11674. function onIceConnectionStateChange(sid, session) {
  11675. switch (session.peerconnection.iceConnectionState) {
  11676. case 'checking':
  11677. session.timeChecking = (new Date()).getTime();
  11678. session.firstconnect = true;
  11679. break;
  11680. case 'completed': // on caller side
  11681. case 'connected':
  11682. if (session.firstconnect) {
  11683. session.firstconnect = false;
  11684. var metadata = {};
  11685. metadata.setupTime
  11686. = (new Date()).getTime() - session.timeChecking;
  11687. session.peerconnection.getStats(function (res) {
  11688. if(res && res.result) {
  11689. res.result().forEach(function (report) {
  11690. if (report.type == 'googCandidatePair' &&
  11691. report.stat('googActiveConnection') == 'true') {
  11692. metadata.localCandidateType
  11693. = report.stat('googLocalCandidateType');
  11694. metadata.remoteCandidateType
  11695. = report.stat('googRemoteCandidateType');
  11696. // log pair as well so we can get nice pie
  11697. // charts
  11698. metadata.candidatePair
  11699. = report.stat('googLocalCandidateType') +
  11700. ';' +
  11701. report.stat('googRemoteCandidateType');
  11702. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11703. {
  11704. metadata.ipv6 = true;
  11705. }
  11706. }
  11707. });
  11708. }
  11709. });
  11710. }
  11711. break;
  11712. }
  11713. }
  11714. JingleSession.prototype.accept = function () {
  11715. this.state = 'active';
  11716. var pranswer = this.peerconnection.localDescription;
  11717. if (!pranswer || pranswer.type != 'pranswer') {
  11718. return;
  11719. }
  11720. console.log('going from pranswer to answer');
  11721. if (this.usetrickle) {
  11722. // remove candidates already sent from session-accept
  11723. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11724. for (var i = 0; i < lines.length; i++) {
  11725. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11726. }
  11727. }
  11728. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11729. // FIXME: change any inactive to sendrecv or whatever they were originally
  11730. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11731. }
  11732. var prsdp = new SDP(pranswer.sdp);
  11733. var accept = $iq({to: this.peerjid,
  11734. type: 'set'})
  11735. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11736. action: 'session-accept',
  11737. initiator: this.initiator,
  11738. responder: this.responder,
  11739. sid: this.sid });
  11740. // FIXME why do we generate session-accept in 3 different places ?
  11741. prsdp.toJingle(
  11742. accept,
  11743. this.initiator == this.me ? 'initiator' : 'responder',
  11744. this.localStreamsSSRC);
  11745. var sdp = this.peerconnection.localDescription.sdp;
  11746. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11747. // FIXME: change any inactive to sendrecv or whatever they were originally
  11748. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11749. }
  11750. var self = this;
  11751. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11752. function () {
  11753. //console.log('setLocalDescription success');
  11754. self.setLocalDescription();
  11755. VideoSSRCHack.processSessionInit(accept);
  11756. self.connection.sendIQ(accept,
  11757. function () {
  11758. var ack = {};
  11759. ack.source = 'answer';
  11760. $(document).trigger('ack.jingle', [self.sid, ack]);
  11761. },
  11762. function (stanza) {
  11763. var error = ($(stanza).find('error').length) ? {
  11764. code: $(stanza).find('error').attr('code'),
  11765. reason: $(stanza).find('error :first')[0].tagName
  11766. }:{};
  11767. error.source = 'answer';
  11768. JingleSession.onJingleError(self.sid, error);
  11769. },
  11770. 10000);
  11771. },
  11772. function (e) {
  11773. console.error('setLocalDescription failed', e);
  11774. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11775. }
  11776. );
  11777. };
  11778. JingleSession.prototype.terminate = function (reason) {
  11779. this.state = 'ended';
  11780. this.reason = reason;
  11781. this.peerconnection.close();
  11782. if (this.statsinterval !== null) {
  11783. window.clearInterval(this.statsinterval);
  11784. this.statsinterval = null;
  11785. }
  11786. };
  11787. JingleSession.prototype.active = function () {
  11788. return this.state == 'active';
  11789. };
  11790. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11791. var self = this;
  11792. if (candidate && !this.lasticecandidate) {
  11793. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11794. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11795. if (!(ice && jcand)) {
  11796. console.error('failed to get ice && jcand');
  11797. return;
  11798. }
  11799. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11800. if (jcand.type === 'srflx') {
  11801. this.hadstuncandidate = true;
  11802. } else if (jcand.type === 'relay') {
  11803. this.hadturncandidate = true;
  11804. }
  11805. if (this.usetrickle) {
  11806. if (this.usedrip) {
  11807. if (this.drip_container.length === 0) {
  11808. // start 20ms callout
  11809. window.setTimeout(function () {
  11810. if (self.drip_container.length === 0) return;
  11811. self.sendIceCandidates(self.drip_container);
  11812. self.drip_container = [];
  11813. }, 20);
  11814. }
  11815. this.drip_container.push(candidate);
  11816. return;
  11817. } else {
  11818. self.sendIceCandidate([candidate]);
  11819. }
  11820. }
  11821. } else {
  11822. //console.log('sendIceCandidate: last candidate.');
  11823. if (!this.usetrickle) {
  11824. //console.log('should send full offer now...');
  11825. //FIXME why do we generate session-accept in 3 different places ?
  11826. var init = $iq({to: this.peerjid,
  11827. type: 'set'})
  11828. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11829. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11830. initiator: this.initiator,
  11831. sid: this.sid});
  11832. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11833. var self = this;
  11834. var sendJingle = function (ssrc) {
  11835. if(!ssrc)
  11836. ssrc = {};
  11837. self.localSDP.toJingle(
  11838. init,
  11839. self.initiator == self.me ? 'initiator' : 'responder',
  11840. ssrc);
  11841. VideoSSRCHack.processSessionInit(init);
  11842. self.connection.sendIQ(init,
  11843. function () {
  11844. //console.log('session initiate ack');
  11845. var ack = {};
  11846. ack.source = 'offer';
  11847. $(document).trigger('ack.jingle', [self.sid, ack]);
  11848. },
  11849. function (stanza) {
  11850. self.state = 'error';
  11851. self.peerconnection.close();
  11852. var error = ($(stanza).find('error').length) ? {
  11853. code: $(stanza).find('error').attr('code'),
  11854. reason: $(stanza).find('error :first')[0].tagName,
  11855. }:{};
  11856. error.source = 'offer';
  11857. JingleSession.onJingleError(self.sid, error);
  11858. },
  11859. 10000);
  11860. }
  11861. sendJingle();
  11862. }
  11863. this.lasticecandidate = true;
  11864. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11865. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11866. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11867. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11868. }
  11869. }
  11870. };
  11871. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11872. console.log('sendIceCandidates', candidates);
  11873. var cand = $iq({to: this.peerjid, type: 'set'})
  11874. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11875. action: 'transport-info',
  11876. initiator: this.initiator,
  11877. sid: this.sid});
  11878. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11879. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11880. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11881. if (cands.length > 0) {
  11882. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11883. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11884. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11885. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11886. }).c('transport', ice);
  11887. for (var i = 0; i < cands.length; i++) {
  11888. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11889. }
  11890. // add fingerprint
  11891. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11892. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11893. tmp.required = true;
  11894. cand.c(
  11895. 'fingerprint',
  11896. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11897. .t(tmp.fingerprint);
  11898. delete tmp.fingerprint;
  11899. cand.attrs(tmp);
  11900. cand.up();
  11901. }
  11902. cand.up(); // transport
  11903. cand.up(); // content
  11904. }
  11905. }
  11906. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11907. //console.log('was this the last candidate', this.lasticecandidate);
  11908. this.connection.sendIQ(cand,
  11909. function () {
  11910. var ack = {};
  11911. ack.source = 'transportinfo';
  11912. $(document).trigger('ack.jingle', [this.sid, ack]);
  11913. },
  11914. function (stanza) {
  11915. var error = ($(stanza).find('error').length) ? {
  11916. code: $(stanza).find('error').attr('code'),
  11917. reason: $(stanza).find('error :first')[0].tagName,
  11918. }:{};
  11919. error.source = 'transportinfo';
  11920. JingleSession.onJingleError(this.sid, error);
  11921. },
  11922. 10000);
  11923. };
  11924. JingleSession.prototype.sendOffer = function () {
  11925. //console.log('sendOffer...');
  11926. var self = this;
  11927. this.peerconnection.createOffer(function (sdp) {
  11928. self.createdOffer(sdp);
  11929. },
  11930. function (e) {
  11931. console.error('createOffer failed', e);
  11932. },
  11933. this.media_constraints
  11934. );
  11935. };
  11936. // FIXME createdOffer is never used in jitsi-meet
  11937. JingleSession.prototype.createdOffer = function (sdp) {
  11938. //console.log('createdOffer', sdp);
  11939. var self = this;
  11940. this.localSDP = new SDP(sdp.sdp);
  11941. //this.localSDP.mangle();
  11942. var sendJingle = function () {
  11943. var init = $iq({to: this.peerjid,
  11944. type: 'set'})
  11945. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11946. action: 'session-initiate',
  11947. initiator: this.initiator,
  11948. sid: this.sid});
  11949. self.localSDP.toJingle(
  11950. init,
  11951. this.initiator == this.me ? 'initiator' : 'responder',
  11952. this.localStreamsSSRC);
  11953. VideoSSRCHack.processSessionInit(init);
  11954. self.connection.sendIQ(init,
  11955. function () {
  11956. var ack = {};
  11957. ack.source = 'offer';
  11958. $(document).trigger('ack.jingle', [self.sid, ack]);
  11959. },
  11960. function (stanza) {
  11961. self.state = 'error';
  11962. self.peerconnection.close();
  11963. var error = ($(stanza).find('error').length) ? {
  11964. code: $(stanza).find('error').attr('code'),
  11965. reason: $(stanza).find('error :first')[0].tagName,
  11966. }:{};
  11967. error.source = 'offer';
  11968. JingleSession.onJingleError(self.sid, error);
  11969. },
  11970. 10000);
  11971. }
  11972. sdp.sdp = this.localSDP.raw;
  11973. this.peerconnection.setLocalDescription(sdp,
  11974. function () {
  11975. if(self.usetrickle)
  11976. {
  11977. sendJingle();
  11978. }
  11979. self.setLocalDescription();
  11980. //console.log('setLocalDescription success');
  11981. },
  11982. function (e) {
  11983. console.error('setLocalDescription failed', e);
  11984. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11985. }
  11986. );
  11987. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11988. for (var i = 0; i < cands.length; i++) {
  11989. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11990. if (cand.type == 'srflx') {
  11991. this.hadstuncandidate = true;
  11992. } else if (cand.type == 'relay') {
  11993. this.hadturncandidate = true;
  11994. }
  11995. }
  11996. };
  11997. JingleSession.prototype.readSsrcInfo = function (contents) {
  11998. var self = this;
  11999. $(contents).each(function (idx, content) {
  12000. var name = $(content).attr('name');
  12001. var mediaType = this.getAttribute('name');
  12002. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12003. ssrcs.each(function () {
  12004. var ssrc = this.getAttribute('ssrc');
  12005. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12006. function () {
  12007. var owner = this.getAttribute('owner');
  12008. self.ssrcOwners[ssrc] = owner;
  12009. }
  12010. );
  12011. });
  12012. });
  12013. };
  12014. JingleSession.prototype.getSsrcOwner = function (ssrc) {
  12015. return this.ssrcOwners[ssrc];
  12016. };
  12017. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  12018. //console.log('setting remote description... ', desctype);
  12019. this.remoteSDP = new SDP('');
  12020. this.remoteSDP.fromJingle(elem);
  12021. this.readSsrcInfo($(elem).find(">content"));
  12022. if (this.peerconnection.remoteDescription !== null) {
  12023. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12024. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12025. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12026. for (var i = 0; i < pranswer.media.length; i++) {
  12027. // make sure we have ice ufrag and pwd
  12028. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12029. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12030. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12031. } else {
  12032. console.warn('no ice ufrag?');
  12033. }
  12034. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12035. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12036. } else {
  12037. console.warn('no ice pwd?');
  12038. }
  12039. }
  12040. // copy over candidates
  12041. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12042. for (var j = 0; j < lines.length; j++) {
  12043. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12044. }
  12045. }
  12046. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12047. }
  12048. }
  12049. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12050. this.peerconnection.setRemoteDescription(remotedesc,
  12051. function () {
  12052. //console.log('setRemoteDescription success');
  12053. },
  12054. function (e) {
  12055. console.error('setRemoteDescription error', e);
  12056. JingleSession.onJingleFatalError(self, e);
  12057. }
  12058. );
  12059. };
  12060. JingleSession.prototype.addIceCandidate = function (elem) {
  12061. var self = this;
  12062. if (this.peerconnection.signalingState == 'closed') {
  12063. return;
  12064. }
  12065. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12066. console.log('trickle ice candidate arriving before session accept...');
  12067. // create a PRANSWER for setRemoteDescription
  12068. if (!this.remoteSDP) {
  12069. var cobbled = 'v=0\r\n' +
  12070. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12071. 's=-\r\n' +
  12072. 't=0 0\r\n';
  12073. // first, take some things from the local description
  12074. for (var i = 0; i < this.localSDP.media.length; i++) {
  12075. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12076. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12077. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12078. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12079. }
  12080. cobbled += 'a=inactive\r\n';
  12081. }
  12082. this.remoteSDP = new SDP(cobbled);
  12083. }
  12084. // then add things like ice and dtls from remote candidate
  12085. elem.each(function () {
  12086. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12087. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12088. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12089. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12090. var tmp = $(this).find('transport');
  12091. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12092. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12093. tmp = $(this).find('transport>fingerprint');
  12094. if (tmp.length) {
  12095. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12096. } else {
  12097. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12098. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12099. }
  12100. break;
  12101. }
  12102. }
  12103. }
  12104. });
  12105. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12106. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12107. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12108. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12109. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12110. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12111. }).length == this.remoteSDP.media.length;
  12112. if (iscomplete) {
  12113. console.log('setting pranswer');
  12114. try {
  12115. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12116. function() {
  12117. },
  12118. function(e) {
  12119. console.log('setRemoteDescription pranswer failed', e.toString());
  12120. });
  12121. } catch (e) {
  12122. console.error('setting pranswer failed', e);
  12123. }
  12124. } else {
  12125. //console.log('not yet setting pranswer');
  12126. }
  12127. }
  12128. // operate on each content element
  12129. elem.each(function () {
  12130. // would love to deactivate this, but firefox still requires it
  12131. var idx = -1;
  12132. var i;
  12133. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12134. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12135. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12136. idx = i;
  12137. break;
  12138. }
  12139. }
  12140. if (idx == -1) { // fall back to localdescription
  12141. for (i = 0; i < self.localSDP.media.length; i++) {
  12142. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12143. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12144. idx = i;
  12145. break;
  12146. }
  12147. }
  12148. }
  12149. var name = $(this).attr('name');
  12150. // TODO: check ice-pwd and ice-ufrag?
  12151. $(this).find('transport>candidate').each(function () {
  12152. var line, candidate;
  12153. line = SDPUtil.candidateFromJingle(this);
  12154. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12155. sdpMid: name,
  12156. candidate: line});
  12157. try {
  12158. self.peerconnection.addIceCandidate(candidate);
  12159. } catch (e) {
  12160. console.error('addIceCandidate failed', e.toString(), line);
  12161. }
  12162. });
  12163. });
  12164. };
  12165. JingleSession.prototype.sendAnswer = function (provisional) {
  12166. //console.log('createAnswer', provisional);
  12167. var self = this;
  12168. this.peerconnection.createAnswer(
  12169. function (sdp) {
  12170. self.createdAnswer(sdp, provisional);
  12171. },
  12172. function (e) {
  12173. console.error('createAnswer failed', e);
  12174. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12175. },
  12176. this.media_constraints
  12177. );
  12178. };
  12179. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  12180. //console.log('createAnswer callback');
  12181. var self = this;
  12182. this.localSDP = new SDP(sdp.sdp);
  12183. //this.localSDP.mangle();
  12184. this.usepranswer = provisional === true;
  12185. if (this.usetrickle) {
  12186. if (this.usepranswer) {
  12187. sdp.type = 'pranswer';
  12188. for (var i = 0; i < this.localSDP.media.length; i++) {
  12189. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12190. }
  12191. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12192. }
  12193. }
  12194. var self = this;
  12195. var sendJingle = function (ssrcs) {
  12196. // FIXME why do we generate session-accept in 3 different places ?
  12197. var accept = $iq({to: self.peerjid,
  12198. type: 'set'})
  12199. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12200. action: 'session-accept',
  12201. initiator: self.initiator,
  12202. responder: self.responder,
  12203. sid: self.sid });
  12204. self.localSDP.toJingle(
  12205. accept,
  12206. self.initiator == self.me ? 'initiator' : 'responder',
  12207. ssrcs);
  12208. VideoSSRCHack.processSessionInit(accept);
  12209. self.connection.sendIQ(accept,
  12210. function () {
  12211. var ack = {};
  12212. ack.source = 'answer';
  12213. $(document).trigger('ack.jingle', [self.sid, ack]);
  12214. },
  12215. function (stanza) {
  12216. var error = ($(stanza).find('error').length) ? {
  12217. code: $(stanza).find('error').attr('code'),
  12218. reason: $(stanza).find('error :first')[0].tagName,
  12219. }:{};
  12220. error.source = 'answer';
  12221. JingleSession.onJingleError(self.sid, error);
  12222. },
  12223. 10000);
  12224. }
  12225. sdp.sdp = this.localSDP.raw;
  12226. this.peerconnection.setLocalDescription(sdp,
  12227. function () {
  12228. //console.log('setLocalDescription success');
  12229. if (self.usetrickle && !self.usepranswer) {
  12230. sendJingle();
  12231. }
  12232. self.setLocalDescription();
  12233. },
  12234. function (e) {
  12235. console.error('setLocalDescription failed', e);
  12236. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12237. }
  12238. );
  12239. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12240. for (var j = 0; j < cands.length; j++) {
  12241. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12242. if (cand.type == 'srflx') {
  12243. this.hadstuncandidate = true;
  12244. } else if (cand.type == 'relay') {
  12245. this.hadturncandidate = true;
  12246. }
  12247. }
  12248. };
  12249. JingleSession.prototype.sendTerminate = function (reason, text) {
  12250. var self = this,
  12251. term = $iq({to: this.peerjid,
  12252. type: 'set'})
  12253. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12254. action: 'session-terminate',
  12255. initiator: this.initiator,
  12256. sid: this.sid})
  12257. .c('reason')
  12258. .c(reason || 'success');
  12259. if (text) {
  12260. term.up().c('text').t(text);
  12261. }
  12262. this.connection.sendIQ(term,
  12263. function () {
  12264. self.peerconnection.close();
  12265. self.peerconnection = null;
  12266. self.terminate();
  12267. var ack = {};
  12268. ack.source = 'terminate';
  12269. $(document).trigger('ack.jingle', [self.sid, ack]);
  12270. },
  12271. function (stanza) {
  12272. var error = ($(stanza).find('error').length) ? {
  12273. code: $(stanza).find('error').attr('code'),
  12274. reason: $(stanza).find('error :first')[0].tagName,
  12275. }:{};
  12276. $(document).trigger('ack.jingle', [self.sid, error]);
  12277. },
  12278. 10000);
  12279. if (this.statsinterval !== null) {
  12280. window.clearInterval(this.statsinterval);
  12281. this.statsinterval = null;
  12282. }
  12283. };
  12284. JingleSession.prototype.addSource = function (elem, fromJid) {
  12285. var self = this;
  12286. // FIXME: dirty waiting
  12287. if (!this.peerconnection.localDescription)
  12288. {
  12289. console.warn("addSource - localDescription not ready yet")
  12290. setTimeout(function()
  12291. {
  12292. self.addSource(elem, fromJid);
  12293. },
  12294. 200
  12295. );
  12296. return;
  12297. }
  12298. console.log('addssrc', new Date().getTime());
  12299. console.log('ice', this.peerconnection.iceConnectionState);
  12300. this.readSsrcInfo(elem);
  12301. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12302. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12303. $(elem).each(function (idx, content) {
  12304. var name = $(content).attr('name');
  12305. var lines = '';
  12306. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12307. var semantics = this.getAttribute('semantics');
  12308. var ssrcs = $(this).find('>source').map(function () {
  12309. return this.getAttribute('ssrc');
  12310. }).get();
  12311. if (ssrcs.length != 0) {
  12312. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12313. }
  12314. });
  12315. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12316. tmp.each(function () {
  12317. var ssrc = $(this).attr('ssrc');
  12318. if(mySdp.containsSSRC(ssrc)){
  12319. /**
  12320. * This happens when multiple participants change their streams at the same time and
  12321. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12322. * addssrc are scheduled for update IQ. See
  12323. */
  12324. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12325. return;
  12326. }
  12327. if (sdp.containsSSRC(ssrc)) {
  12328. console.warn("Source-add request for existing SSRC: " + ssrc);
  12329. return;
  12330. }
  12331. $(this).find('>parameter').each(function () {
  12332. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12333. if ($(this).attr('value') && $(this).attr('value').length)
  12334. lines += ':' + $(this).attr('value');
  12335. lines += '\r\n';
  12336. });
  12337. });
  12338. sdp.media.forEach(function(media, idx) {
  12339. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12340. return;
  12341. sdp.media[idx] += lines;
  12342. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12343. self.addssrc[idx] += lines;
  12344. });
  12345. sdp.raw = sdp.session + sdp.media.join('');
  12346. });
  12347. this.modifySourcesQueue.push(function() {
  12348. // When a source is added and if this is FF, a new channel is allocated
  12349. // for receiving the added source. We need to diffuse the SSRC of this
  12350. // new recvonly channel to the rest of the peers.
  12351. console.log('modify sources done');
  12352. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12353. console.log("SDPs", mySdp, newSdp);
  12354. self.notifyMySSRCUpdate(mySdp, newSdp);
  12355. });
  12356. };
  12357. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12358. var self = this;
  12359. // FIXME: dirty waiting
  12360. if (!this.peerconnection.localDescription)
  12361. {
  12362. console.warn("removeSource - localDescription not ready yet")
  12363. setTimeout(function()
  12364. {
  12365. self.removeSource(elem, fromJid);
  12366. },
  12367. 200
  12368. );
  12369. return;
  12370. }
  12371. console.log('removessrc', new Date().getTime());
  12372. console.log('ice', this.peerconnection.iceConnectionState);
  12373. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12374. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12375. $(elem).each(function (idx, content) {
  12376. var name = $(content).attr('name');
  12377. var lines = '';
  12378. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12379. var semantics = this.getAttribute('semantics');
  12380. var ssrcs = $(this).find('>source').map(function () {
  12381. return this.getAttribute('ssrc');
  12382. }).get();
  12383. if (ssrcs.length != 0) {
  12384. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12385. }
  12386. });
  12387. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12388. tmp.each(function () {
  12389. var ssrc = $(this).attr('ssrc');
  12390. // This should never happen, but can be useful for bug detection
  12391. if(mySdp.containsSSRC(ssrc)){
  12392. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12393. return;
  12394. }
  12395. $(this).find('>parameter').each(function () {
  12396. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12397. if ($(this).attr('value') && $(this).attr('value').length)
  12398. lines += ':' + $(this).attr('value');
  12399. lines += '\r\n';
  12400. });
  12401. });
  12402. sdp.media.forEach(function(media, idx) {
  12403. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12404. return;
  12405. sdp.media[idx] += lines;
  12406. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12407. self.removessrc[idx] += lines;
  12408. });
  12409. sdp.raw = sdp.session + sdp.media.join('');
  12410. });
  12411. this.modifySourcesQueue.push(function() {
  12412. // When a source is removed and if this is FF, the recvonly channel that
  12413. // receives the remote stream is deactivated . We need to diffuse the
  12414. // recvonly SSRC removal to the rest of the peers.
  12415. console.log('modify sources done');
  12416. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12417. console.log("SDPs", mySdp, newSdp);
  12418. self.notifyMySSRCUpdate(mySdp, newSdp);
  12419. });
  12420. };
  12421. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12422. var self = this;
  12423. if (this.peerconnection.signalingState == 'closed') return;
  12424. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12425. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12426. this.setLocalDescription();
  12427. if(successCallback){
  12428. successCallback();
  12429. }
  12430. queueCallback();
  12431. return;
  12432. }
  12433. // Reset switch streams flag
  12434. this.switchstreams = false;
  12435. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12436. // add sources
  12437. this.addssrc.forEach(function(lines, idx) {
  12438. sdp.media[idx] += lines;
  12439. });
  12440. this.addssrc = [];
  12441. // remove sources
  12442. this.removessrc.forEach(function(lines, idx) {
  12443. lines = lines.split('\r\n');
  12444. lines.pop(); // remove empty last element;
  12445. lines.forEach(function(line) {
  12446. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12447. });
  12448. });
  12449. this.removessrc = [];
  12450. sdp.raw = sdp.session + sdp.media.join('');
  12451. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12452. function() {
  12453. if(self.signalingState == 'closed') {
  12454. console.error("createAnswer attempt on closed state");
  12455. queueCallback("createAnswer attempt on closed state");
  12456. return;
  12457. }
  12458. self.peerconnection.createAnswer(
  12459. function(modifiedAnswer) {
  12460. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12461. if (self.pendingop !== null) {
  12462. var sdp = new SDP(modifiedAnswer.sdp);
  12463. if (sdp.media.length > 1) {
  12464. switch(self.pendingop) {
  12465. case 'mute':
  12466. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12467. break;
  12468. case 'unmute':
  12469. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12470. break;
  12471. }
  12472. sdp.raw = sdp.session + sdp.media.join('');
  12473. modifiedAnswer.sdp = sdp.raw;
  12474. }
  12475. self.pendingop = null;
  12476. }
  12477. // FIXME: pushing down an answer while ice connection state
  12478. // is still checking is bad...
  12479. //console.log(self.peerconnection.iceConnectionState);
  12480. // trying to work around another chrome bug
  12481. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12482. self.peerconnection.setLocalDescription(modifiedAnswer,
  12483. function() {
  12484. //console.log('modified setLocalDescription ok');
  12485. self.setLocalDescription();
  12486. if(successCallback){
  12487. successCallback();
  12488. }
  12489. queueCallback();
  12490. },
  12491. function(error) {
  12492. console.error('modified setLocalDescription failed', error);
  12493. queueCallback(error);
  12494. }
  12495. );
  12496. },
  12497. function(error) {
  12498. console.error('modified answer failed', error);
  12499. queueCallback(error);
  12500. }
  12501. );
  12502. },
  12503. function(error) {
  12504. console.error('modify failed', error);
  12505. queueCallback(error);
  12506. }
  12507. );
  12508. };
  12509. /**
  12510. * Switches video streams.
  12511. * @param new_stream new stream that will be used as video of this session.
  12512. * @param oldStream old video stream of this session.
  12513. * @param success_callback callback executed after successful stream switch.
  12514. */
  12515. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12516. var self = this;
  12517. // Remember SDP to figure out added/removed SSRCs
  12518. var oldSdp = null;
  12519. if(self.peerconnection) {
  12520. if(self.peerconnection.localDescription) {
  12521. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12522. }
  12523. self.peerconnection.removeStream(oldStream, true);
  12524. if(new_stream)
  12525. self.peerconnection.addStream(new_stream);
  12526. }
  12527. // Conference is not active
  12528. if(!oldSdp || !self.peerconnection) {
  12529. success_callback();
  12530. return;
  12531. }
  12532. self.switchstreams = true;
  12533. self.modifySourcesQueue.push(function() {
  12534. console.log('modify sources done');
  12535. success_callback();
  12536. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12537. console.log("SDPs", oldSdp, newSdp);
  12538. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12539. });
  12540. };
  12541. /**
  12542. * Figures out added/removed ssrcs and send update IQs.
  12543. * @param old_sdp SDP object for old description.
  12544. * @param new_sdp SDP object for new description.
  12545. */
  12546. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12547. if (!(this.peerconnection.signalingState == 'stable' &&
  12548. this.peerconnection.iceConnectionState == 'connected')){
  12549. console.log("Too early to send updates");
  12550. return;
  12551. }
  12552. // send source-remove IQ.
  12553. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12554. var remove = $iq({to: this.peerjid, type: 'set'})
  12555. .c('jingle', {
  12556. xmlns: 'urn:xmpp:jingle:1',
  12557. action: 'source-remove',
  12558. initiator: this.initiator,
  12559. sid: this.sid
  12560. }
  12561. );
  12562. var removed = sdpDiffer.toJingle(remove);
  12563. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  12564. // it in the current form
  12565. if (removed)
  12566. remove = VideoSSRCHack.processSourceRemove(remove);
  12567. if (removed && remove) {
  12568. this.connection.sendIQ(remove,
  12569. function (res) {
  12570. console.info('got remove result', res);
  12571. },
  12572. function (err) {
  12573. console.error('got remove error', err);
  12574. }
  12575. );
  12576. } else {
  12577. console.log('removal not necessary');
  12578. }
  12579. // send source-add IQ.
  12580. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12581. var add = $iq({to: this.peerjid, type: 'set'})
  12582. .c('jingle', {
  12583. xmlns: 'urn:xmpp:jingle:1',
  12584. action: 'source-add',
  12585. initiator: this.initiator,
  12586. sid: this.sid
  12587. }
  12588. );
  12589. var added = sdpDiffer.toJingle(add);
  12590. // Let 'source-add' IQ through the hack and see if we're allowed to send
  12591. // it in the current form
  12592. if (added)
  12593. add = VideoSSRCHack.processSourceAdd(add);
  12594. if (added & add) {
  12595. this.connection.sendIQ(add,
  12596. function (res) {
  12597. console.info('got add result', res);
  12598. },
  12599. function (err) {
  12600. console.error('got add error', err);
  12601. }
  12602. );
  12603. } else {
  12604. console.log('addition not necessary');
  12605. }
  12606. };
  12607. /**
  12608. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12609. *
  12610. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12611. * tracks; otherwise, <tt>false</tt>
  12612. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12613. * tracks have been enabled/disabled. The function may, optionally, return
  12614. * another function which is to be invoked after the whole mute/unmute operation
  12615. * has completed successfully.
  12616. * @param options an object which specifies optional arguments such as the
  12617. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12618. * specifies whether the method was initiated in response to a user command (in
  12619. * contrast to an automatic decision made by the application logic)
  12620. */
  12621. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12622. var byUser;
  12623. if (options) {
  12624. byUser = options.byUser;
  12625. if (typeof byUser === 'undefined') {
  12626. byUser = true;
  12627. }
  12628. } else {
  12629. byUser = true;
  12630. }
  12631. // The user's command to mute the (local) video takes precedence over any
  12632. // automatic decision made by the application logic.
  12633. if (byUser) {
  12634. this.videoMuteByUser = mute;
  12635. } else if (this.videoMuteByUser) {
  12636. return;
  12637. }
  12638. this.hardMuteVideo(mute);
  12639. var self = this;
  12640. var oldSdp = null;
  12641. if(self.peerconnection) {
  12642. if(self.peerconnection.localDescription) {
  12643. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12644. }
  12645. }
  12646. this.modifySourcesQueue.push(function() {
  12647. console.log('modify sources done');
  12648. callback(mute);
  12649. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12650. console.log("SDPs", oldSdp, newSdp);
  12651. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12652. });
  12653. };
  12654. JingleSession.prototype.hardMuteVideo = function (muted) {
  12655. this.pendingop = muted ? 'mute' : 'unmute';
  12656. };
  12657. JingleSession.prototype.sendMute = function (muted, content) {
  12658. var info = $iq({to: this.peerjid,
  12659. type: 'set'})
  12660. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12661. action: 'session-info',
  12662. initiator: this.initiator,
  12663. sid: this.sid });
  12664. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12665. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12666. if (content) {
  12667. info.attrs({'name': content});
  12668. }
  12669. this.connection.send(info);
  12670. };
  12671. JingleSession.prototype.sendRinging = function () {
  12672. var info = $iq({to: this.peerjid,
  12673. type: 'set'})
  12674. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12675. action: 'session-info',
  12676. initiator: this.initiator,
  12677. sid: this.sid });
  12678. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12679. this.connection.send(info);
  12680. };
  12681. JingleSession.prototype.getStats = function (interval) {
  12682. var self = this;
  12683. var recv = {audio: 0, video: 0};
  12684. var lost = {audio: 0, video: 0};
  12685. var lastrecv = {audio: 0, video: 0};
  12686. var lastlost = {audio: 0, video: 0};
  12687. var loss = {audio: 0, video: 0};
  12688. var delta = {audio: 0, video: 0};
  12689. this.statsinterval = window.setInterval(function () {
  12690. if (self && self.peerconnection && self.peerconnection.getStats) {
  12691. self.peerconnection.getStats(function (stats) {
  12692. var results = stats.result();
  12693. // TODO: there are so much statistics you can get from this..
  12694. for (var i = 0; i < results.length; ++i) {
  12695. if (results[i].type == 'ssrc') {
  12696. var packetsrecv = results[i].stat('packetsReceived');
  12697. var packetslost = results[i].stat('packetsLost');
  12698. if (packetsrecv && packetslost) {
  12699. packetsrecv = parseInt(packetsrecv, 10);
  12700. packetslost = parseInt(packetslost, 10);
  12701. if (results[i].stat('googFrameRateReceived')) {
  12702. lastlost.video = lost.video;
  12703. lastrecv.video = recv.video;
  12704. recv.video = packetsrecv;
  12705. lost.video = packetslost;
  12706. } else {
  12707. lastlost.audio = lost.audio;
  12708. lastrecv.audio = recv.audio;
  12709. recv.audio = packetsrecv;
  12710. lost.audio = packetslost;
  12711. }
  12712. }
  12713. }
  12714. }
  12715. delta.audio = recv.audio - lastrecv.audio;
  12716. delta.video = recv.video - lastrecv.video;
  12717. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12718. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12719. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12720. });
  12721. }
  12722. }, interval || 3000);
  12723. return this.statsinterval;
  12724. };
  12725. JingleSession.onJingleError = function (session, error)
  12726. {
  12727. console.error("Jingle error", error);
  12728. }
  12729. JingleSession.onJingleFatalError = function (session, error)
  12730. {
  12731. this.service.sessionTerminated = true;
  12732. this.connection.emuc.doLeave();
  12733. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12734. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12735. }
  12736. JingleSession.prototype.setLocalDescription = function () {
  12737. var self = this;
  12738. var newssrcs = [];
  12739. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12740. session.media.forEach(function (media) {
  12741. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12742. // TODO(gp) maybe exclude FID streams?
  12743. media.ssrcs.forEach(function (ssrc) {
  12744. if (ssrc.attribute !== 'cname') {
  12745. return;
  12746. }
  12747. newssrcs.push({
  12748. 'ssrc': ssrc.id,
  12749. 'type': media.type
  12750. });
  12751. });
  12752. }
  12753. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12754. {
  12755. newssrcs.push({
  12756. 'ssrc': self.localStreamsSSRC[media.type],
  12757. 'type': media.type
  12758. });
  12759. }
  12760. });
  12761. console.log('new ssrcs', newssrcs);
  12762. // Bind us as local SSRCs owner
  12763. if (newssrcs.length > 0) {
  12764. for (var i = 1; i <= newssrcs.length; i ++) {
  12765. var ssrc = newssrcs[i-1].ssrc;
  12766. var myJid = self.connection.emuc.myroomjid;
  12767. self.ssrcOwners[ssrc] = myJid;
  12768. }
  12769. }
  12770. }
  12771. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12772. function sendKeyframe(pc) {
  12773. console.log('sendkeyframe', pc.iceConnectionState);
  12774. if (pc.iceConnectionState !== 'connected') return; // safe...
  12775. var self = this;
  12776. pc.setRemoteDescription(
  12777. pc.remoteDescription,
  12778. function () {
  12779. pc.createAnswer(
  12780. function (modifiedAnswer) {
  12781. pc.setLocalDescription(
  12782. modifiedAnswer,
  12783. function () {
  12784. // noop
  12785. },
  12786. function (error) {
  12787. console.log('triggerKeyframe setLocalDescription failed', error);
  12788. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  12789. }
  12790. );
  12791. },
  12792. function (error) {
  12793. console.log('triggerKeyframe createAnswer failed', error);
  12794. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  12795. }
  12796. );
  12797. },
  12798. function (error) {
  12799. console.log('triggerKeyframe setRemoteDescription failed', error);
  12800. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  12801. }
  12802. );
  12803. }
  12804. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12805. var self = this;
  12806. var thessrc;
  12807. var streamId = APP.RTC.getStreamID(data.stream);
  12808. // look up an associated JID for a stream id
  12809. if (!streamId) {
  12810. console.error("No stream ID for", data.stream);
  12811. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12812. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12813. var ssrclines
  12814. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12815. ssrclines = ssrclines.filter(function (line) {
  12816. // NOTE(gp) previously we filtered on the mslabel, but that property
  12817. // is not always present.
  12818. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12819. if (RTCBrowserType.isTemasysPluginUsed()) {
  12820. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12821. } else {
  12822. return ((line.indexOf('msid:' + streamId) !== -1));
  12823. }
  12824. });
  12825. if (ssrclines.length) {
  12826. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12827. if (!self.ssrcOwners[thessrc]) {
  12828. console.error("No SSRC owner known for: " + thessrc);
  12829. return;
  12830. }
  12831. data.peerjid = self.ssrcOwners[thessrc];
  12832. console.log('associated jid', self.ssrcOwners[thessrc]);
  12833. } else {
  12834. console.error("No SSRC lines for ", streamId);
  12835. }
  12836. }
  12837. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12838. var isVideo = data.stream.getVideoTracks().length > 0;
  12839. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12840. if (isVideo &&
  12841. data.peerjid && this.peerjid === data.peerjid &&
  12842. data.stream.getVideoTracks().length === 0 &&
  12843. APP.RTC.localVideo.getTracks().length > 0) {
  12844. window.setTimeout(function () {
  12845. sendKeyframe(self.peerconnection);
  12846. }, 3000);
  12847. }
  12848. }
  12849. module.exports = JingleSession;
  12850. },{"../../service/xmpp/XMPPEvents":113,"../RTC/RTCBrowserType":8,"./SDP":54,"./SDPDiffer":55,"./SDPUtil":56,"./TraceablePeerConnection":57,"./VideoSSRCHack":58,"async":68,"sdp-transform":100}],54:[function(require,module,exports){
  12851. /* jshint -W117 */
  12852. var SDPUtil = require("./SDPUtil");
  12853. // SDP STUFF
  12854. function SDP(sdp) {
  12855. this.media = sdp.split('\r\nm=');
  12856. for (var i = 1; i < this.media.length; i++) {
  12857. this.media[i] = 'm=' + this.media[i];
  12858. if (i != this.media.length - 1) {
  12859. this.media[i] += '\r\n';
  12860. }
  12861. }
  12862. this.session = this.media.shift() + '\r\n';
  12863. this.raw = this.session + this.media.join('');
  12864. }
  12865. /**
  12866. * Returns map of MediaChannel mapped per channel idx.
  12867. */
  12868. SDP.prototype.getMediaSsrcMap = function() {
  12869. var self = this;
  12870. var media_ssrcs = {};
  12871. var tmp;
  12872. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12873. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12874. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12875. var media = {
  12876. mediaindex: mediaindex,
  12877. mid: mid,
  12878. ssrcs: {},
  12879. ssrcGroups: []
  12880. };
  12881. media_ssrcs[mediaindex] = media;
  12882. tmp.forEach(function (line) {
  12883. var linessrc = line.substring(7).split(' ')[0];
  12884. // allocate new ChannelSsrc
  12885. if(!media.ssrcs[linessrc]) {
  12886. media.ssrcs[linessrc] = {
  12887. ssrc: linessrc,
  12888. lines: []
  12889. };
  12890. }
  12891. media.ssrcs[linessrc].lines.push(line);
  12892. });
  12893. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12894. tmp.forEach(function(line){
  12895. var semantics = line.substr(0, idx).substr(13);
  12896. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12897. if (ssrcs.length != 0) {
  12898. media.ssrcGroups.push({
  12899. semantics: semantics,
  12900. ssrcs: ssrcs
  12901. });
  12902. }
  12903. });
  12904. }
  12905. return media_ssrcs;
  12906. };
  12907. /**
  12908. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12909. * @param ssrc the ssrc to check.
  12910. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12911. */
  12912. SDP.prototype.containsSSRC = function(ssrc) {
  12913. var medias = this.getMediaSsrcMap();
  12914. var contains = false;
  12915. Object.keys(medias).forEach(function(mediaindex){
  12916. var media = medias[mediaindex];
  12917. //console.log("Check", channel, ssrc);
  12918. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12919. contains = true;
  12920. }
  12921. });
  12922. return contains;
  12923. };
  12924. // remove iSAC and CN from SDP
  12925. SDP.prototype.mangle = function () {
  12926. var i, j, mline, lines, rtpmap, newdesc;
  12927. for (i = 0; i < this.media.length; i++) {
  12928. lines = this.media[i].split('\r\n');
  12929. lines.pop(); // remove empty last element
  12930. mline = SDPUtil.parse_mline(lines.shift());
  12931. if (mline.media != 'audio')
  12932. continue;
  12933. newdesc = '';
  12934. mline.fmt.length = 0;
  12935. for (j = 0; j < lines.length; j++) {
  12936. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12937. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12938. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12939. continue;
  12940. mline.fmt.push(rtpmap.id);
  12941. newdesc += lines[j] + '\r\n';
  12942. } else {
  12943. newdesc += lines[j] + '\r\n';
  12944. }
  12945. }
  12946. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12947. this.media[i] += newdesc;
  12948. }
  12949. this.raw = this.session + this.media.join('');
  12950. };
  12951. // remove lines matching prefix from session section
  12952. SDP.prototype.removeSessionLines = function(prefix) {
  12953. var self = this;
  12954. var lines = SDPUtil.find_lines(this.session, prefix);
  12955. lines.forEach(function(line) {
  12956. self.session = self.session.replace(line + '\r\n', '');
  12957. });
  12958. this.raw = this.session + this.media.join('');
  12959. return lines;
  12960. }
  12961. // remove lines matching prefix from a media section specified by mediaindex
  12962. // TODO: non-numeric mediaindex could match mid
  12963. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12964. var self = this;
  12965. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12966. lines.forEach(function(line) {
  12967. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12968. });
  12969. this.raw = this.session + this.media.join('');
  12970. return lines;
  12971. }
  12972. // add content's to a jingle element
  12973. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  12974. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12975. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12976. var self = this;
  12977. // new bundle plan
  12978. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12979. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12980. for (i = 0; i < lines.length; i++) {
  12981. tmp = lines[i].split(' ');
  12982. var semantics = tmp.shift().substr(8);
  12983. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12984. for (j = 0; j < tmp.length; j++) {
  12985. elem.c('content', {name: tmp[j]}).up();
  12986. }
  12987. elem.up();
  12988. }
  12989. }
  12990. for (i = 0; i < this.media.length; i++) {
  12991. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12992. if (!(mline.media === 'audio' ||
  12993. mline.media === 'video' ||
  12994. mline.media === 'application'))
  12995. {
  12996. continue;
  12997. }
  12998. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12999. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13000. } else {
  13001. if(ssrcs && ssrcs[mline.media])
  13002. {
  13003. ssrc = ssrcs[mline.media];
  13004. }
  13005. else
  13006. ssrc = false;
  13007. }
  13008. elem.c('content', {creator: thecreator, name: mline.media});
  13009. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13010. // prefer identifier from a=mid if present
  13011. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13012. elem.attrs({ name: mid });
  13013. }
  13014. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13015. {
  13016. elem.c('description',
  13017. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13018. media: mline.media });
  13019. if (ssrc) {
  13020. elem.attrs({ssrc: ssrc});
  13021. }
  13022. for (j = 0; j < mline.fmt.length; j++) {
  13023. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13024. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13025. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13026. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13027. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13028. for (k = 0; k < tmp.length; k++) {
  13029. elem.c('parameter', tmp[k]).up();
  13030. }
  13031. }
  13032. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13033. elem.up();
  13034. }
  13035. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13036. elem.c('encryption', {required: 1});
  13037. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13038. crypto.forEach(function(line) {
  13039. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13040. });
  13041. elem.up(); // end of encryption
  13042. }
  13043. if (ssrc) {
  13044. // new style mapping
  13045. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13046. // FIXME: group by ssrc and support multiple different ssrcs
  13047. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13048. if(ssrclines.length > 0) {
  13049. ssrclines.forEach(function (line) {
  13050. idx = line.indexOf(' ');
  13051. var linessrc = line.substr(0, idx).substr(7);
  13052. if (linessrc != ssrc) {
  13053. elem.up();
  13054. ssrc = linessrc;
  13055. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13056. }
  13057. var kv = line.substr(idx + 1);
  13058. elem.c('parameter');
  13059. if (kv.indexOf(':') == -1) {
  13060. elem.attrs({ name: kv });
  13061. } else {
  13062. var k = kv.split(':', 2)[0];
  13063. elem.attrs({ name: k });
  13064. var v = kv.split(':', 2)[1];
  13065. v = SDPUtil.filter_special_chars(v);
  13066. elem.attrs({ value: v });
  13067. }
  13068. elem.up();
  13069. });
  13070. }
  13071. else
  13072. {
  13073. elem.up();
  13074. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13075. elem.c('parameter');
  13076. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13077. elem.up();
  13078. var msid = null;
  13079. if(mline.media == "audio")
  13080. {
  13081. msid = APP.RTC.localAudio.getId();
  13082. }
  13083. else
  13084. {
  13085. msid = APP.RTC.localVideo.getId();
  13086. }
  13087. if(msid != null)
  13088. {
  13089. msid = SDPUtil.filter_special_chars(msid);
  13090. elem.c('parameter');
  13091. elem.attrs({name: "msid", value:msid});
  13092. elem.up();
  13093. elem.c('parameter');
  13094. elem.attrs({name: "mslabel", value:msid});
  13095. elem.up();
  13096. elem.c('parameter');
  13097. elem.attrs({name: "label", value:msid});
  13098. elem.up();
  13099. }
  13100. }
  13101. elem.up();
  13102. // XEP-0339 handle ssrc-group attributes
  13103. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13104. ssrc_group_lines.forEach(function(line) {
  13105. idx = line.indexOf(' ');
  13106. var semantics = line.substr(0, idx).substr(13);
  13107. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13108. if (ssrcs.length != 0) {
  13109. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13110. ssrcs.forEach(function(ssrc) {
  13111. elem.c('source', { ssrc: ssrc })
  13112. .up();
  13113. });
  13114. elem.up();
  13115. }
  13116. });
  13117. }
  13118. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13119. elem.c('rtcp-mux').up();
  13120. }
  13121. // XEP-0293 -- map a=rtcp-fb:*
  13122. this.RtcpFbToJingle(i, elem, '*');
  13123. // XEP-0294
  13124. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13125. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13126. for (j = 0; j < lines.length; j++) {
  13127. tmp = SDPUtil.parse_extmap(lines[j]);
  13128. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13129. uri: tmp.uri,
  13130. id: tmp.value });
  13131. if (tmp.hasOwnProperty('direction')) {
  13132. switch (tmp.direction) {
  13133. case 'sendonly':
  13134. elem.attrs({senders: 'responder'});
  13135. break;
  13136. case 'recvonly':
  13137. elem.attrs({senders: 'initiator'});
  13138. break;
  13139. case 'sendrecv':
  13140. elem.attrs({senders: 'both'});
  13141. break;
  13142. case 'inactive':
  13143. elem.attrs({senders: 'none'});
  13144. break;
  13145. }
  13146. }
  13147. // TODO: handle params
  13148. elem.up();
  13149. }
  13150. }
  13151. elem.up(); // end of description
  13152. }
  13153. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13154. this.TransportToJingle(i, elem);
  13155. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13156. elem.attrs({senders: 'both'});
  13157. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13158. elem.attrs({senders: 'initiator'});
  13159. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13160. elem.attrs({senders: 'responder'});
  13161. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13162. elem.attrs({senders: 'none'});
  13163. }
  13164. if (mline.port == '0') {
  13165. // estos hack to reject an m-line
  13166. elem.attrs({senders: 'rejected'});
  13167. }
  13168. elem.up(); // end of content
  13169. }
  13170. elem.up();
  13171. return elem;
  13172. };
  13173. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13174. var i = mediaindex;
  13175. var tmp;
  13176. var self = this;
  13177. elem.c('transport');
  13178. // XEP-0343 DTLS/SCTP
  13179. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13180. {
  13181. var sctpmap = SDPUtil.find_line(
  13182. this.media[i], 'a=sctpmap:', self.session);
  13183. if (sctpmap)
  13184. {
  13185. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13186. elem.c('sctpmap',
  13187. {
  13188. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13189. number: sctpAttrs[0], /* SCTP port */
  13190. protocol: sctpAttrs[1], /* protocol */
  13191. });
  13192. // Optional stream count attribute
  13193. if (sctpAttrs.length > 2)
  13194. elem.attrs({ streams: sctpAttrs[2]});
  13195. elem.up();
  13196. }
  13197. }
  13198. // XEP-0320
  13199. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13200. fingerprints.forEach(function(line) {
  13201. tmp = SDPUtil.parse_fingerprint(line);
  13202. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13203. elem.c('fingerprint').t(tmp.fingerprint);
  13204. delete tmp.fingerprint;
  13205. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13206. if (line) {
  13207. tmp.setup = line.substr(8);
  13208. }
  13209. elem.attrs(tmp);
  13210. elem.up(); // end of fingerprint
  13211. });
  13212. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13213. if (tmp) {
  13214. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13215. elem.attrs(tmp);
  13216. // XEP-0176
  13217. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13218. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13219. lines.forEach(function (line) {
  13220. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13221. });
  13222. }
  13223. }
  13224. elem.up(); // end of transport
  13225. }
  13226. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13227. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13228. lines.forEach(function (line) {
  13229. var tmp = SDPUtil.parse_rtcpfb(line);
  13230. if (tmp.type == 'trr-int') {
  13231. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13232. elem.up();
  13233. } else {
  13234. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13235. if (tmp.params.length > 0) {
  13236. elem.attrs({'subtype': tmp.params[0]});
  13237. }
  13238. elem.up();
  13239. }
  13240. });
  13241. };
  13242. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13243. var media = '';
  13244. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13245. if (tmp.length) {
  13246. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13247. if (tmp.attr('value')) {
  13248. media += tmp.attr('value');
  13249. } else {
  13250. media += '0';
  13251. }
  13252. media += '\r\n';
  13253. }
  13254. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13255. tmp.each(function () {
  13256. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13257. if ($(this).attr('subtype')) {
  13258. media += ' ' + $(this).attr('subtype');
  13259. }
  13260. media += '\r\n';
  13261. });
  13262. return media;
  13263. };
  13264. // construct an SDP from a jingle stanza
  13265. SDP.prototype.fromJingle = function (jingle) {
  13266. var self = this;
  13267. this.raw = 'v=0\r\n' +
  13268. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13269. 's=-\r\n' +
  13270. 't=0 0\r\n';
  13271. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13272. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13273. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13274. var contents = $(group).find('>content').map(function (idx, content) {
  13275. return content.getAttribute('name');
  13276. }).get();
  13277. if (contents.length > 0) {
  13278. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13279. }
  13280. });
  13281. }
  13282. this.session = this.raw;
  13283. jingle.find('>content').each(function () {
  13284. var m = self.jingle2media($(this));
  13285. self.media.push(m);
  13286. });
  13287. // reconstruct msid-semantic -- apparently not necessary
  13288. /*
  13289. var msid = SDPUtil.parse_ssrc(this.raw);
  13290. if (msid.hasOwnProperty('mslabel')) {
  13291. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13292. }
  13293. */
  13294. this.raw = this.session + this.media.join('');
  13295. };
  13296. // translate a jingle content element into an an SDP media part
  13297. SDP.prototype.jingle2media = function (content) {
  13298. var media = '',
  13299. desc = content.find('description'),
  13300. ssrc = desc.attr('ssrc'),
  13301. self = this,
  13302. tmp;
  13303. var sctp = content.find(
  13304. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13305. tmp = { media: desc.attr('media') };
  13306. tmp.port = '1';
  13307. if (content.attr('senders') == 'rejected') {
  13308. // estos hack to reject an m-line.
  13309. tmp.port = '0';
  13310. }
  13311. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13312. if (sctp.length)
  13313. tmp.proto = 'DTLS/SCTP';
  13314. else
  13315. tmp.proto = 'RTP/SAVPF';
  13316. } else {
  13317. tmp.proto = 'RTP/AVPF';
  13318. }
  13319. if (!sctp.length)
  13320. {
  13321. tmp.fmt = desc.find('payload-type').map(
  13322. function () { return this.getAttribute('id'); }).get();
  13323. media += SDPUtil.build_mline(tmp) + '\r\n';
  13324. }
  13325. else
  13326. {
  13327. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13328. media += 'a=sctpmap:' + sctp.attr('number') +
  13329. ' ' + sctp.attr('protocol');
  13330. var streamCount = sctp.attr('streams');
  13331. if (streamCount)
  13332. media += ' ' + streamCount + '\r\n';
  13333. else
  13334. media += '\r\n';
  13335. }
  13336. media += 'c=IN IP4 0.0.0.0\r\n';
  13337. if (!sctp.length)
  13338. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13339. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13340. if (tmp.length) {
  13341. if (tmp.attr('ufrag')) {
  13342. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13343. }
  13344. if (tmp.attr('pwd')) {
  13345. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13346. }
  13347. tmp.find('>fingerprint').each(function () {
  13348. // FIXME: check namespace at some point
  13349. media += 'a=fingerprint:' + this.getAttribute('hash');
  13350. media += ' ' + $(this).text();
  13351. media += '\r\n';
  13352. if (this.getAttribute('setup')) {
  13353. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13354. }
  13355. });
  13356. }
  13357. switch (content.attr('senders')) {
  13358. case 'initiator':
  13359. media += 'a=sendonly\r\n';
  13360. break;
  13361. case 'responder':
  13362. media += 'a=recvonly\r\n';
  13363. break;
  13364. case 'none':
  13365. media += 'a=inactive\r\n';
  13366. break;
  13367. case 'both':
  13368. media += 'a=sendrecv\r\n';
  13369. break;
  13370. }
  13371. media += 'a=mid:' + content.attr('name') + '\r\n';
  13372. // <description><rtcp-mux/></description>
  13373. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13374. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13375. if (desc.find('rtcp-mux').length) {
  13376. media += 'a=rtcp-mux\r\n';
  13377. }
  13378. if (desc.find('encryption').length) {
  13379. desc.find('encryption>crypto').each(function () {
  13380. media += 'a=crypto:' + this.getAttribute('tag');
  13381. media += ' ' + this.getAttribute('crypto-suite');
  13382. media += ' ' + this.getAttribute('key-params');
  13383. if (this.getAttribute('session-params')) {
  13384. media += ' ' + this.getAttribute('session-params');
  13385. }
  13386. media += '\r\n';
  13387. });
  13388. }
  13389. desc.find('payload-type').each(function () {
  13390. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13391. if ($(this).find('>parameter').length) {
  13392. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13393. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13394. media += '\r\n';
  13395. }
  13396. // xep-0293
  13397. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13398. });
  13399. // xep-0293
  13400. media += self.RtcpFbFromJingle(desc, '*');
  13401. // xep-0294
  13402. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13403. tmp.each(function () {
  13404. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13405. });
  13406. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13407. media += SDPUtil.candidateFromJingle(this);
  13408. });
  13409. // XEP-0339 handle ssrc-group attributes
  13410. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13411. var semantics = this.getAttribute('semantics');
  13412. var ssrcs = $(this).find('>source').map(function() {
  13413. return this.getAttribute('ssrc');
  13414. }).get();
  13415. if (ssrcs.length != 0) {
  13416. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13417. }
  13418. });
  13419. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13420. tmp.each(function () {
  13421. var ssrc = this.getAttribute('ssrc');
  13422. $(this).find('>parameter').each(function () {
  13423. var name = this.getAttribute('name');
  13424. var value = this.getAttribute('value');
  13425. value = SDPUtil.filter_special_chars(value);
  13426. media += 'a=ssrc:' + ssrc + ' ' + name;
  13427. if (value && value.length)
  13428. media += ':' + value;
  13429. media += '\r\n';
  13430. });
  13431. });
  13432. return media;
  13433. };
  13434. module.exports = SDP;
  13435. },{"./SDPUtil":56}],55:[function(require,module,exports){
  13436. var SDPUtil = require("./SDPUtil");
  13437. function SDPDiffer(mySDP, otherSDP) {
  13438. this.mySDP = mySDP;
  13439. this.otherSDP = otherSDP;
  13440. }
  13441. /**
  13442. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13443. * @param otherSdp the other SDP to check ssrc with.
  13444. */
  13445. SDPDiffer.prototype.getNewMedia = function() {
  13446. // this could be useful in Array.prototype.
  13447. function arrayEquals(array) {
  13448. // if the other array is a falsy value, return
  13449. if (!array)
  13450. return false;
  13451. // compare lengths - can save a lot of time
  13452. if (this.length != array.length)
  13453. return false;
  13454. for (var i = 0, l=this.length; i < l; i++) {
  13455. // Check if we have nested arrays
  13456. if (this[i] instanceof Array && array[i] instanceof Array) {
  13457. // recurse into the nested arrays
  13458. if (!this[i].equals(array[i]))
  13459. return false;
  13460. }
  13461. else if (this[i] != array[i]) {
  13462. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13463. return false;
  13464. }
  13465. }
  13466. return true;
  13467. }
  13468. var myMedias = this.mySDP.getMediaSsrcMap();
  13469. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13470. var newMedia = {};
  13471. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13472. var myMedia = myMedias[othersMediaIdx];
  13473. var othersMedia = othersMedias[othersMediaIdx];
  13474. if(!myMedia && othersMedia) {
  13475. // Add whole channel
  13476. newMedia[othersMediaIdx] = othersMedia;
  13477. return;
  13478. }
  13479. // Look for new ssrcs accross the channel
  13480. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13481. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13482. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13483. if(!newMedia[othersMediaIdx]){
  13484. newMedia[othersMediaIdx] = {
  13485. mediaindex: othersMedia.mediaindex,
  13486. mid: othersMedia.mid,
  13487. ssrcs: {},
  13488. ssrcGroups: []
  13489. };
  13490. }
  13491. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13492. }
  13493. });
  13494. // Look for new ssrc groups across the channels
  13495. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13496. // try to match the other ssrc-group with an ssrc-group of ours
  13497. var matched = false;
  13498. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13499. var mySsrcGroup = myMedia.ssrcGroups[i];
  13500. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13501. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13502. matched = true;
  13503. break;
  13504. }
  13505. }
  13506. if (!matched) {
  13507. // Allocate channel if we've found an ssrc-group that doesn't
  13508. // exist in our channel
  13509. if(!newMedia[othersMediaIdx]){
  13510. newMedia[othersMediaIdx] = {
  13511. mediaindex: othersMedia.mediaindex,
  13512. mid: othersMedia.mid,
  13513. ssrcs: {},
  13514. ssrcGroups: []
  13515. };
  13516. }
  13517. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13518. }
  13519. });
  13520. });
  13521. return newMedia;
  13522. };
  13523. /**
  13524. * Sends SSRC update IQ.
  13525. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13526. * @param sid session identifier that will be put into the IQ.
  13527. * @param initiator initiator identifier.
  13528. * @param toJid destination Jid
  13529. * @param isAdd indicates if this is remove or add operation.
  13530. */
  13531. SDPDiffer.prototype.toJingle = function(modify) {
  13532. var sdpMediaSsrcs = this.getNewMedia();
  13533. var self = this;
  13534. // FIXME: only announce video ssrcs since we mix audio and dont need
  13535. // the audio ssrcs therefore
  13536. var modified = false;
  13537. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13538. modified = true;
  13539. var media = sdpMediaSsrcs[mediaindex];
  13540. modify.c('content', {name: media.mid});
  13541. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13542. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13543. // generate sources from lines
  13544. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13545. var mediaSsrc = media.ssrcs[ssrcNum];
  13546. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13547. modify.attrs({ssrc: mediaSsrc.ssrc});
  13548. // iterate over ssrc lines
  13549. mediaSsrc.lines.forEach(function (line) {
  13550. var idx = line.indexOf(' ');
  13551. var kv = line.substr(idx + 1);
  13552. modify.c('parameter');
  13553. if (kv.indexOf(':') == -1) {
  13554. modify.attrs({ name: kv });
  13555. } else {
  13556. var nv = kv.split(':', 2);
  13557. var name = nv[0];
  13558. var value = SDPUtil.filter_special_chars(nv[1]);
  13559. modify.attrs({ name: name });
  13560. modify.attrs({ value: value });
  13561. }
  13562. modify.up(); // end of parameter
  13563. });
  13564. modify.up(); // end of source
  13565. });
  13566. // generate source groups from lines
  13567. media.ssrcGroups.forEach(function(ssrcGroup) {
  13568. if (ssrcGroup.ssrcs.length != 0) {
  13569. modify.c('ssrc-group', {
  13570. semantics: ssrcGroup.semantics,
  13571. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13572. });
  13573. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13574. modify.c('source', { ssrc: ssrc })
  13575. .up(); // end of source
  13576. });
  13577. modify.up(); // end of ssrc-group
  13578. }
  13579. });
  13580. modify.up(); // end of description
  13581. modify.up(); // end of content
  13582. });
  13583. return modified;
  13584. };
  13585. module.exports = SDPDiffer;
  13586. },{"./SDPUtil":56}],56:[function(require,module,exports){
  13587. SDPUtil = {
  13588. filter_special_chars: function (text) {
  13589. return text.replace(/[\\\/\{,\}\+]/g, "");
  13590. },
  13591. iceparams: function (mediadesc, sessiondesc) {
  13592. var data = null;
  13593. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13594. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13595. data = {
  13596. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13597. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13598. };
  13599. }
  13600. return data;
  13601. },
  13602. parse_iceufrag: function (line) {
  13603. return line.substring(12);
  13604. },
  13605. build_iceufrag: function (frag) {
  13606. return 'a=ice-ufrag:' + frag;
  13607. },
  13608. parse_icepwd: function (line) {
  13609. return line.substring(10);
  13610. },
  13611. build_icepwd: function (pwd) {
  13612. return 'a=ice-pwd:' + pwd;
  13613. },
  13614. parse_mid: function (line) {
  13615. return line.substring(6);
  13616. },
  13617. parse_mline: function (line) {
  13618. var parts = line.substring(2).split(' '),
  13619. data = {};
  13620. data.media = parts.shift();
  13621. data.port = parts.shift();
  13622. data.proto = parts.shift();
  13623. if (parts[parts.length - 1] === '') { // trailing whitespace
  13624. parts.pop();
  13625. }
  13626. data.fmt = parts;
  13627. return data;
  13628. },
  13629. build_mline: function (mline) {
  13630. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13631. },
  13632. parse_rtpmap: function (line) {
  13633. var parts = line.substring(9).split(' '),
  13634. data = {};
  13635. data.id = parts.shift();
  13636. parts = parts[0].split('/');
  13637. data.name = parts.shift();
  13638. data.clockrate = parts.shift();
  13639. data.channels = parts.length ? parts.shift() : '1';
  13640. return data;
  13641. },
  13642. /**
  13643. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13644. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13645. * @returns [SCTP port number, protocol, streams]
  13646. */
  13647. parse_sctpmap: function (line)
  13648. {
  13649. var parts = line.substring(10).split(' ');
  13650. var sctpPort = parts[0];
  13651. var protocol = parts[1];
  13652. // Stream count is optional
  13653. var streamCount = parts.length > 2 ? parts[2] : null;
  13654. return [sctpPort, protocol, streamCount];// SCTP port
  13655. },
  13656. build_rtpmap: function (el) {
  13657. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13658. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13659. line += '/' + el.getAttribute('channels');
  13660. }
  13661. return line;
  13662. },
  13663. parse_crypto: function (line) {
  13664. var parts = line.substring(9).split(' '),
  13665. data = {};
  13666. data.tag = parts.shift();
  13667. data['crypto-suite'] = parts.shift();
  13668. data['key-params'] = parts.shift();
  13669. if (parts.length) {
  13670. data['session-params'] = parts.join(' ');
  13671. }
  13672. return data;
  13673. },
  13674. parse_fingerprint: function (line) { // RFC 4572
  13675. var parts = line.substring(14).split(' '),
  13676. data = {};
  13677. data.hash = parts.shift();
  13678. data.fingerprint = parts.shift();
  13679. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13680. return data;
  13681. },
  13682. parse_fmtp: function (line) {
  13683. var parts = line.split(' '),
  13684. i, key, value,
  13685. data = [];
  13686. parts.shift();
  13687. parts = parts.join(' ').split(';');
  13688. for (i = 0; i < parts.length; i++) {
  13689. key = parts[i].split('=')[0];
  13690. while (key.length && key[0] == ' ') {
  13691. key = key.substring(1);
  13692. }
  13693. value = parts[i].split('=')[1];
  13694. if (key && value) {
  13695. data.push({name: key, value: value});
  13696. } else if (key) {
  13697. // rfc 4733 (DTMF) style stuff
  13698. data.push({name: '', value: key});
  13699. }
  13700. }
  13701. return data;
  13702. },
  13703. parse_icecandidate: function (line) {
  13704. var candidate = {},
  13705. elems = line.split(' ');
  13706. candidate.foundation = elems[0].substring(12);
  13707. candidate.component = elems[1];
  13708. candidate.protocol = elems[2].toLowerCase();
  13709. candidate.priority = elems[3];
  13710. candidate.ip = elems[4];
  13711. candidate.port = elems[5];
  13712. // elems[6] => "typ"
  13713. candidate.type = elems[7];
  13714. candidate.generation = 0; // default value, may be overwritten below
  13715. for (var i = 8; i < elems.length; i += 2) {
  13716. switch (elems[i]) {
  13717. case 'raddr':
  13718. candidate['rel-addr'] = elems[i + 1];
  13719. break;
  13720. case 'rport':
  13721. candidate['rel-port'] = elems[i + 1];
  13722. break;
  13723. case 'generation':
  13724. candidate.generation = elems[i + 1];
  13725. break;
  13726. case 'tcptype':
  13727. candidate.tcptype = elems[i + 1];
  13728. break;
  13729. default: // TODO
  13730. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13731. }
  13732. }
  13733. candidate.network = '1';
  13734. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13735. return candidate;
  13736. },
  13737. build_icecandidate: function (cand) {
  13738. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13739. line += ' ';
  13740. switch (cand.type) {
  13741. case 'srflx':
  13742. case 'prflx':
  13743. case 'relay':
  13744. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13745. line += 'raddr';
  13746. line += ' ';
  13747. line += cand['rel-addr'];
  13748. line += ' ';
  13749. line += 'rport';
  13750. line += ' ';
  13751. line += cand['rel-port'];
  13752. line += ' ';
  13753. }
  13754. break;
  13755. }
  13756. if (cand.hasOwnAttribute('tcptype')) {
  13757. line += 'tcptype';
  13758. line += ' ';
  13759. line += cand.tcptype;
  13760. line += ' ';
  13761. }
  13762. line += 'generation';
  13763. line += ' ';
  13764. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13765. return line;
  13766. },
  13767. parse_ssrc: function (desc) {
  13768. // proprietary mapping of a=ssrc lines
  13769. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13770. // and parse according to that
  13771. var lines = desc.split('\r\n'),
  13772. data = {};
  13773. for (var i = 0; i < lines.length; i++) {
  13774. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13775. var idx = lines[i].indexOf(' ');
  13776. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13777. }
  13778. }
  13779. return data;
  13780. },
  13781. parse_rtcpfb: function (line) {
  13782. var parts = line.substr(10).split(' ');
  13783. var data = {};
  13784. data.pt = parts.shift();
  13785. data.type = parts.shift();
  13786. data.params = parts;
  13787. return data;
  13788. },
  13789. parse_extmap: function (line) {
  13790. var parts = line.substr(9).split(' ');
  13791. var data = {};
  13792. data.value = parts.shift();
  13793. if (data.value.indexOf('/') != -1) {
  13794. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13795. data.value = data.value.substr(0, data.value.indexOf('/'));
  13796. } else {
  13797. data.direction = 'both';
  13798. }
  13799. data.uri = parts.shift();
  13800. data.params = parts;
  13801. return data;
  13802. },
  13803. find_line: function (haystack, needle, sessionpart) {
  13804. var lines = haystack.split('\r\n');
  13805. for (var i = 0; i < lines.length; i++) {
  13806. if (lines[i].substring(0, needle.length) == needle) {
  13807. return lines[i];
  13808. }
  13809. }
  13810. if (!sessionpart) {
  13811. return false;
  13812. }
  13813. // search session part
  13814. lines = sessionpart.split('\r\n');
  13815. for (var j = 0; j < lines.length; j++) {
  13816. if (lines[j].substring(0, needle.length) == needle) {
  13817. return lines[j];
  13818. }
  13819. }
  13820. return false;
  13821. },
  13822. find_lines: function (haystack, needle, sessionpart) {
  13823. var lines = haystack.split('\r\n'),
  13824. needles = [];
  13825. for (var i = 0; i < lines.length; i++) {
  13826. if (lines[i].substring(0, needle.length) == needle)
  13827. needles.push(lines[i]);
  13828. }
  13829. if (needles.length || !sessionpart) {
  13830. return needles;
  13831. }
  13832. // search session part
  13833. lines = sessionpart.split('\r\n');
  13834. for (var j = 0; j < lines.length; j++) {
  13835. if (lines[j].substring(0, needle.length) == needle) {
  13836. needles.push(lines[j]);
  13837. }
  13838. }
  13839. return needles;
  13840. },
  13841. candidateToJingle: function (line) {
  13842. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13843. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13844. if (line.indexOf('candidate:') === 0) {
  13845. line = 'a=' + line;
  13846. } else if (line.substring(0, 12) != 'a=candidate:') {
  13847. console.log('parseCandidate called with a line that is not a candidate line');
  13848. console.log(line);
  13849. return null;
  13850. }
  13851. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13852. line = line.substring(0, line.length - 2);
  13853. var candidate = {},
  13854. elems = line.split(' '),
  13855. i;
  13856. if (elems[6] != 'typ') {
  13857. console.log('did not find typ in the right place');
  13858. console.log(line);
  13859. return null;
  13860. }
  13861. candidate.foundation = elems[0].substring(12);
  13862. candidate.component = elems[1];
  13863. candidate.protocol = elems[2].toLowerCase();
  13864. candidate.priority = elems[3];
  13865. candidate.ip = elems[4];
  13866. candidate.port = elems[5];
  13867. // elems[6] => "typ"
  13868. candidate.type = elems[7];
  13869. candidate.generation = '0'; // default, may be overwritten below
  13870. for (i = 8; i < elems.length; i += 2) {
  13871. switch (elems[i]) {
  13872. case 'raddr':
  13873. candidate['rel-addr'] = elems[i + 1];
  13874. break;
  13875. case 'rport':
  13876. candidate['rel-port'] = elems[i + 1];
  13877. break;
  13878. case 'generation':
  13879. candidate.generation = elems[i + 1];
  13880. break;
  13881. case 'tcptype':
  13882. candidate.tcptype = elems[i + 1];
  13883. break;
  13884. default: // TODO
  13885. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13886. }
  13887. }
  13888. candidate.network = '1';
  13889. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13890. return candidate;
  13891. },
  13892. candidateFromJingle: function (cand) {
  13893. var line = 'a=candidate:';
  13894. line += cand.getAttribute('foundation');
  13895. line += ' ';
  13896. line += cand.getAttribute('component');
  13897. line += ' ';
  13898. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13899. line += ' ';
  13900. line += cand.getAttribute('priority');
  13901. line += ' ';
  13902. line += cand.getAttribute('ip');
  13903. line += ' ';
  13904. line += cand.getAttribute('port');
  13905. line += ' ';
  13906. line += 'typ';
  13907. line += ' ' + cand.getAttribute('type');
  13908. line += ' ';
  13909. switch (cand.getAttribute('type')) {
  13910. case 'srflx':
  13911. case 'prflx':
  13912. case 'relay':
  13913. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13914. line += 'raddr';
  13915. line += ' ';
  13916. line += cand.getAttribute('rel-addr');
  13917. line += ' ';
  13918. line += 'rport';
  13919. line += ' ';
  13920. line += cand.getAttribute('rel-port');
  13921. line += ' ';
  13922. }
  13923. break;
  13924. }
  13925. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13926. line += 'tcptype';
  13927. line += ' ';
  13928. line += cand.getAttribute('tcptype');
  13929. line += ' ';
  13930. }
  13931. line += 'generation';
  13932. line += ' ';
  13933. line += cand.getAttribute('generation') || '0';
  13934. return line + '\r\n';
  13935. }
  13936. };
  13937. module.exports = SDPUtil;
  13938. },{}],57:[function(require,module,exports){
  13939. var RTC = require('../RTC/RTC');
  13940. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  13941. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13942. var VideoSSRCHack = require("./VideoSSRCHack");
  13943. function TraceablePeerConnection(ice_config, constraints, session) {
  13944. var self = this;
  13945. var RTCPeerConnectionType = null;
  13946. if (RTCBrowserType.isFirefox()) {
  13947. RTCPeerConnectionType = mozRTCPeerConnection;
  13948. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  13949. RTCPeerConnectionType = RTCPeerConnection;
  13950. } else {
  13951. RTCPeerConnectionType = webkitRTCPeerConnection;
  13952. }
  13953. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  13954. this.updateLog = [];
  13955. this.stats = {};
  13956. this.statsinterval = null;
  13957. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13958. var Interop = require('sdp-interop').Interop;
  13959. this.interop = new Interop();
  13960. var Simulcast = require('sdp-simulcast');
  13961. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  13962. // override as desired
  13963. this.trace = function (what, info) {
  13964. /*console.warn('WTRACE', what, info);
  13965. if (info && RTCBrowserType.isIExplorer()) {
  13966. if (info.length > 1024) {
  13967. console.warn('WTRACE', what, info.substr(1024));
  13968. }
  13969. if (info.length > 2048) {
  13970. console.warn('WTRACE', what, info.substr(2048));
  13971. }
  13972. }*/
  13973. self.updateLog.push({
  13974. time: new Date(),
  13975. type: what,
  13976. value: info || ""
  13977. });
  13978. };
  13979. this.onicecandidate = null;
  13980. this.peerconnection.onicecandidate = function (event) {
  13981. // FIXME: this causes stack overflow with Temasys Plugin
  13982. if (!RTCBrowserType.isTemasysPluginUsed())
  13983. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13984. if (self.onicecandidate !== null) {
  13985. self.onicecandidate(event);
  13986. }
  13987. };
  13988. this.onaddstream = null;
  13989. this.peerconnection.onaddstream = function (event) {
  13990. self.trace('onaddstream', event.stream.id);
  13991. if (self.onaddstream !== null) {
  13992. self.onaddstream(event);
  13993. }
  13994. };
  13995. this.onremovestream = null;
  13996. this.peerconnection.onremovestream = function (event) {
  13997. self.trace('onremovestream', event.stream.id);
  13998. if (self.onremovestream !== null) {
  13999. self.onremovestream(event);
  14000. }
  14001. };
  14002. this.onsignalingstatechange = null;
  14003. this.peerconnection.onsignalingstatechange = function (event) {
  14004. self.trace('onsignalingstatechange', self.signalingState);
  14005. if (self.onsignalingstatechange !== null) {
  14006. self.onsignalingstatechange(event);
  14007. }
  14008. };
  14009. this.oniceconnectionstatechange = null;
  14010. this.peerconnection.oniceconnectionstatechange = function (event) {
  14011. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14012. if (self.oniceconnectionstatechange !== null) {
  14013. self.oniceconnectionstatechange(event);
  14014. }
  14015. };
  14016. this.onnegotiationneeded = null;
  14017. this.peerconnection.onnegotiationneeded = function (event) {
  14018. self.trace('onnegotiationneeded');
  14019. if (self.onnegotiationneeded !== null) {
  14020. self.onnegotiationneeded(event);
  14021. }
  14022. };
  14023. self.ondatachannel = null;
  14024. this.peerconnection.ondatachannel = function (event) {
  14025. self.trace('ondatachannel', event);
  14026. if (self.ondatachannel !== null) {
  14027. self.ondatachannel(event);
  14028. }
  14029. };
  14030. // XXX: do all non-firefox browsers which we support also support this?
  14031. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14032. this.statsinterval = window.setInterval(function() {
  14033. self.peerconnection.getStats(function(stats) {
  14034. var results = stats.result();
  14035. var now = new Date();
  14036. for (var i = 0; i < results.length; ++i) {
  14037. results[i].names().forEach(function (name) {
  14038. var id = results[i].id + '-' + name;
  14039. if (!self.stats[id]) {
  14040. self.stats[id] = {
  14041. startTime: now,
  14042. endTime: now,
  14043. values: [],
  14044. times: []
  14045. };
  14046. }
  14047. self.stats[id].values.push(results[i].stat(name));
  14048. self.stats[id].times.push(now.getTime());
  14049. if (self.stats[id].values.length > self.maxstats) {
  14050. self.stats[id].values.shift();
  14051. self.stats[id].times.shift();
  14052. }
  14053. self.stats[id].endTime = now;
  14054. });
  14055. }
  14056. });
  14057. }, 1000);
  14058. }
  14059. }
  14060. /**
  14061. * Returns a string representation of a SessionDescription object.
  14062. */
  14063. var dumpSDP = function(description) {
  14064. if (typeof description === 'undefined' || description == null) {
  14065. return '';
  14066. }
  14067. return 'type: ' + description.type + '\r\n' + description.sdp;
  14068. };
  14069. /**
  14070. * Takes a SessionDescription object and returns a "normalized" version.
  14071. * Currently it only takes care of ordering the a=ssrc lines.
  14072. */
  14073. var normalizePlanB = function(desc) {
  14074. if (typeof desc !== 'object' || desc === null ||
  14075. typeof desc.sdp !== 'string') {
  14076. console.warn('An empty description was passed as an argument.');
  14077. return desc;
  14078. }
  14079. var transform = require('sdp-transform');
  14080. var session = transform.parse(desc.sdp);
  14081. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14082. Array.isArray(session.media)) {
  14083. session.media.forEach(function (mLine) {
  14084. // Chrome appears to be picky about the order in which a=ssrc lines
  14085. // are listed in an m-line when rtx is enabled (and thus there are
  14086. // a=ssrc-group lines with FID semantics). Specifically if we have
  14087. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14088. // the "a=ssrc:S1" lines, SRD fails.
  14089. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14090. // first.
  14091. var firstSsrcs = [];
  14092. var newSsrcLines = [];
  14093. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14094. mLine.ssrcGroups.forEach(function (group) {
  14095. if (typeof group.semantics !== 'undefined' &&
  14096. group.semantics === 'FID') {
  14097. if (typeof group.ssrcs !== 'undefined') {
  14098. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14099. }
  14100. }
  14101. });
  14102. }
  14103. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14104. for (var i = 0; i<mLine.ssrcs.length; i++){
  14105. if (typeof mLine.ssrcs[i] === 'object'
  14106. && typeof mLine.ssrcs[i].id !== 'undefined'
  14107. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14108. newSsrcLines.push(mLine.ssrcs[i]);
  14109. delete mLine.ssrcs[i];
  14110. }
  14111. }
  14112. for (var i = 0; i<mLine.ssrcs.length; i++){
  14113. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14114. newSsrcLines.push(mLine.ssrcs[i]);
  14115. }
  14116. }
  14117. mLine.ssrcs = newSsrcLines;
  14118. }
  14119. });
  14120. }
  14121. var resStr = transform.write(session);
  14122. return new RTCSessionDescription({
  14123. type: desc.type,
  14124. sdp: resStr
  14125. });
  14126. };
  14127. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14128. TraceablePeerConnection.prototype.__defineGetter__(
  14129. 'signalingState',
  14130. function() { return this.peerconnection.signalingState; });
  14131. TraceablePeerConnection.prototype.__defineGetter__(
  14132. 'iceConnectionState',
  14133. function() { return this.peerconnection.iceConnectionState; });
  14134. TraceablePeerConnection.prototype.__defineGetter__(
  14135. 'localDescription',
  14136. function() {
  14137. var desc = this.peerconnection.localDescription;
  14138. desc = VideoSSRCHack.mungeLocalVideoSSRC(desc);
  14139. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14140. // if we're running on FF, transform to Plan B first.
  14141. if (RTCBrowserType.usesUnifiedPlan()) {
  14142. desc = this.interop.toPlanB(desc);
  14143. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14144. }
  14145. return desc;
  14146. });
  14147. TraceablePeerConnection.prototype.__defineGetter__(
  14148. 'remoteDescription',
  14149. function() {
  14150. var desc = this.peerconnection.remoteDescription;
  14151. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14152. // if we're running on FF, transform to Plan B first.
  14153. if (RTCBrowserType.usesUnifiedPlan()) {
  14154. desc = this.interop.toPlanB(desc);
  14155. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14156. }
  14157. return desc;
  14158. });
  14159. }
  14160. TraceablePeerConnection.prototype.addStream = function (stream) {
  14161. this.trace('addStream', stream.id);
  14162. try
  14163. {
  14164. this.peerconnection.addStream(stream);
  14165. }
  14166. catch (e)
  14167. {
  14168. console.error(e);
  14169. }
  14170. };
  14171. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14172. this.trace('removeStream', stream.id);
  14173. if(stopStreams) {
  14174. stream.getAudioTracks().forEach(function (track) {
  14175. // stop() not supported with IE
  14176. if (track.stop) {
  14177. track.stop();
  14178. }
  14179. });
  14180. stream.getVideoTracks().forEach(function (track) {
  14181. // stop() not supported with IE
  14182. if (track.stop) {
  14183. track.stop();
  14184. }
  14185. });
  14186. if (stream.stop) {
  14187. stream.stop();
  14188. }
  14189. }
  14190. try {
  14191. // FF doesn't support this yet.
  14192. if (this.peerconnection.removeStream)
  14193. this.peerconnection.removeStream(stream);
  14194. } catch (e) {
  14195. console.error(e);
  14196. }
  14197. };
  14198. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14199. this.trace('createDataChannel', label, opts);
  14200. return this.peerconnection.createDataChannel(label, opts);
  14201. };
  14202. TraceablePeerConnection.prototype.setLocalDescription
  14203. = function (description, successCallback, failureCallback) {
  14204. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14205. // if we're running on FF, transform to Plan A first.
  14206. if (RTCBrowserType.usesUnifiedPlan()) {
  14207. description = this.interop.toUnifiedPlan(description);
  14208. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14209. }
  14210. var self = this;
  14211. this.peerconnection.setLocalDescription(description,
  14212. function () {
  14213. self.trace('setLocalDescriptionOnSuccess');
  14214. successCallback();
  14215. },
  14216. function (err) {
  14217. self.trace('setLocalDescriptionOnFailure', err);
  14218. failureCallback(err);
  14219. }
  14220. );
  14221. /*
  14222. if (this.statsinterval === null && this.maxstats > 0) {
  14223. // start gathering stats
  14224. }
  14225. */
  14226. };
  14227. TraceablePeerConnection.prototype.setRemoteDescription
  14228. = function (description, successCallback, failureCallback) {
  14229. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14230. // TODO the focus should squeze or explode the remote simulcast
  14231. description = this.simulcast.mungeRemoteDescription(description);
  14232. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14233. // if we're running on FF, transform to Plan A first.
  14234. if (RTCBrowserType.usesUnifiedPlan()) {
  14235. description = this.interop.toUnifiedPlan(description);
  14236. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14237. }
  14238. if (RTCBrowserType.usesPlanB()) {
  14239. description = normalizePlanB(description);
  14240. }
  14241. var self = this;
  14242. this.peerconnection.setRemoteDescription(description,
  14243. function () {
  14244. self.trace('setRemoteDescriptionOnSuccess');
  14245. successCallback();
  14246. },
  14247. function (err) {
  14248. self.trace('setRemoteDescriptionOnFailure', err);
  14249. failureCallback(err);
  14250. }
  14251. );
  14252. /*
  14253. if (this.statsinterval === null && this.maxstats > 0) {
  14254. // start gathering stats
  14255. }
  14256. */
  14257. };
  14258. TraceablePeerConnection.prototype.close = function () {
  14259. this.trace('stop');
  14260. if (this.statsinterval !== null) {
  14261. window.clearInterval(this.statsinterval);
  14262. this.statsinterval = null;
  14263. }
  14264. this.peerconnection.close();
  14265. };
  14266. TraceablePeerConnection.prototype.createOffer
  14267. = function (successCallback, failureCallback, constraints) {
  14268. var self = this;
  14269. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14270. this.peerconnection.createOffer(
  14271. function (offer) {
  14272. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14273. // NOTE this is not tested because in meet the focus generates the
  14274. // offer.
  14275. // if we're running on FF, transform to Plan B first.
  14276. if (RTCBrowserType.usesUnifiedPlan()) {
  14277. offer = self.interop.toPlanB(offer);
  14278. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14279. }
  14280. offer = VideoSSRCHack.mungeLocalVideoSSRC(offer);
  14281. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14282. offer = self.simulcast.mungeLocalDescription(offer);
  14283. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14284. }
  14285. successCallback(offer);
  14286. },
  14287. function(err) {
  14288. self.trace('createOfferOnFailure', err);
  14289. failureCallback(err);
  14290. },
  14291. constraints
  14292. );
  14293. };
  14294. TraceablePeerConnection.prototype.createAnswer
  14295. = function (successCallback, failureCallback, constraints) {
  14296. var self = this;
  14297. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14298. this.peerconnection.createAnswer(
  14299. function (answer) {
  14300. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14301. // if we're running on FF, transform to Plan A first.
  14302. if (RTCBrowserType.usesUnifiedPlan()) {
  14303. answer = self.interop.toPlanB(answer);
  14304. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14305. }
  14306. // munge local video SSRC
  14307. answer = VideoSSRCHack.mungeLocalVideoSSRC(answer);
  14308. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14309. answer = self.simulcast.mungeLocalDescription(answer);
  14310. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14311. }
  14312. successCallback(answer);
  14313. },
  14314. function(err) {
  14315. self.trace('createAnswerOnFailure', err);
  14316. failureCallback(err);
  14317. },
  14318. constraints
  14319. );
  14320. };
  14321. TraceablePeerConnection.prototype.addIceCandidate
  14322. = function (candidate, successCallback, failureCallback) {
  14323. //var self = this;
  14324. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14325. this.peerconnection.addIceCandidate(candidate);
  14326. /* maybe later
  14327. this.peerconnection.addIceCandidate(candidate,
  14328. function () {
  14329. self.trace('addIceCandidateOnSuccess');
  14330. successCallback();
  14331. },
  14332. function (err) {
  14333. self.trace('addIceCandidateOnFailure', err);
  14334. failureCallback(err);
  14335. }
  14336. );
  14337. */
  14338. };
  14339. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14340. // TODO: Is this the correct way to handle Opera, Temasys?
  14341. if (RTCBrowserType.isFirefox()) {
  14342. // ignore for now...
  14343. if(!errback)
  14344. errback = function () {};
  14345. this.peerconnection.getStats(null, callback, errback);
  14346. } else {
  14347. this.peerconnection.getStats(callback);
  14348. }
  14349. };
  14350. module.exports = TraceablePeerConnection;
  14351. },{"../../service/xmpp/XMPPEvents":113,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"./VideoSSRCHack":58,"sdp-interop":90,"sdp-simulcast":97,"sdp-transform":100}],58:[function(require,module,exports){
  14352. /* global $ */
  14353. /*
  14354. The purpose of this hack is to re-use SSRC of first video stream ever created
  14355. for any video streams created later on. In order to do that this hack:
  14356. 1. Stores the SSRC of the first video stream created by
  14357. a) scanning Jingle session-accept/session-invite for existing video SSRC
  14358. b) watching for 'source-add' for new video stream if it has not been
  14359. created in step a)
  14360. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  14361. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  14362. returned to the other parts of the application.
  14363. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  14364. blocks those notifications. This makes Jicofo and all participants think
  14365. that it exists all the time even if the video stream has been removed or
  14366. replaced locally. Thanks to that there is no additional signaling activity
  14367. on video mute or when switching to the desktop stream.
  14368. */
  14369. var SDP = require('./SDP');
  14370. /**
  14371. * Stored SSRC of local video stream.
  14372. */
  14373. var localVideoSSRC;
  14374. /**
  14375. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  14376. * from given Jingle IQ.
  14377. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  14378. * @param actionName display name of the action which will be printed in log
  14379. * messages.
  14380. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  14381. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  14382. * other SSRCs left to be signaled after removing it.
  14383. */
  14384. var filterOutSource = function (modifyIq, actionName) {
  14385. if (!localVideoSSRC)
  14386. return modifyIq;
  14387. var modifyIqTree = $(modifyIq.tree());
  14388. var videoSSRC = modifyIqTree.find(
  14389. '>jingle>content[name="video"]' +
  14390. '>description>source[ssrc="' + localVideoSSRC + '"]');
  14391. if (!videoSSRC.length) {
  14392. return modifyIqTree;
  14393. }
  14394. console.info(
  14395. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  14396. videoSSRC.remove();
  14397. // Check if any sources still left to be added/removed
  14398. if (modifyIqTree.find('>jingle>content>description>source').length) {
  14399. return modifyIqTree;
  14400. } else {
  14401. return null;
  14402. }
  14403. };
  14404. /**
  14405. * Scans given Jingle IQ for video SSRC and stores it.
  14406. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  14407. */
  14408. var storeLocalVideoSSRC = function (jingleIq) {
  14409. var videoSSRCs =
  14410. $(jingleIq.tree())
  14411. .find('>jingle>content[name="video"]>description>source');
  14412. console.info('Video desc: ', videoSSRCs);
  14413. if (!videoSSRCs.length)
  14414. return;
  14415. var ssrc = videoSSRCs.attr('ssrc');
  14416. if (ssrc) {
  14417. localVideoSSRC = ssrc;
  14418. console.info(
  14419. 'Stored local video SSRC for future re-use: ' + localVideoSSRC);
  14420. } else {
  14421. console.error('No "ssrc" attribute present in <source> element');
  14422. }
  14423. };
  14424. var LocalVideoSSRCHack = {
  14425. /**
  14426. * Method must be called before 'session-initiate' or 'session-invite' is
  14427. * sent. Scans the IQ for local video SSRC and stores it if detected.
  14428. *
  14429. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  14430. * which will be scanned for local video SSRC.
  14431. */
  14432. processSessionInit: function (sessionInit) {
  14433. if (localVideoSSRC) {
  14434. console.error("Local SSRC stored already: " + localVideoSSRC);
  14435. return;
  14436. }
  14437. storeLocalVideoSSRC(sessionInit);
  14438. },
  14439. /**
  14440. * If we have local video SSRC stored searched given
  14441. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  14442. * with the stored one.
  14443. * @param localDescription local description object that will have local
  14444. * video SSRC replaced with the stored one
  14445. * @returns modified <tt>localDescription</tt> object.
  14446. */
  14447. mungeLocalVideoSSRC: function (localDescription) {
  14448. // IF we have local video SSRC stored make sure it is replaced
  14449. // with old SSRC
  14450. if (localVideoSSRC) {
  14451. var newSdp = new SDP(localDescription.sdp);
  14452. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  14453. !newSdp.containsSSRC(localVideoSSRC)) {
  14454. // Get new video SSRC
  14455. var map = newSdp.getMediaSsrcMap();
  14456. var videoPart = map[1];
  14457. var videoSSRCs = videoPart.ssrcs;
  14458. var newSSRC = Object.keys(videoSSRCs)[0];
  14459. console.info(
  14460. "Replacing new video SSRC: " + newSSRC +
  14461. " with " + localVideoSSRC);
  14462. localDescription.sdp =
  14463. newSdp.raw.replace(
  14464. new RegExp('a=ssrc:' + newSSRC, 'g'),
  14465. 'a=ssrc:' + localVideoSSRC);
  14466. }
  14467. }
  14468. return localDescription;
  14469. },
  14470. /**
  14471. * Method must be called before 'source-add' notification is sent. In case
  14472. * we have local video SSRC advertised already it will be removed from the
  14473. * notification. If no other SSRCs are described by given IQ null will be
  14474. * returned which means that there is no point in sending the notification.
  14475. * @param sourceAdd 'source-add' Jingle IQ to be processed
  14476. * @returns modified 'source-add' IQ which can be sent to the focus or
  14477. * <tt>null</tt> if no notification shall be sent. It is no longer
  14478. * a Strophe IQ Builder instance, but DOM element tree.
  14479. */
  14480. processSourceAdd: function (sourceAdd) {
  14481. if (!localVideoSSRC) {
  14482. // Store local SSRC if available
  14483. storeLocalVideoSSRC(sourceAdd);
  14484. return sourceAdd;
  14485. } else {
  14486. return filterOutSource(sourceAdd, 'source-add');
  14487. }
  14488. },
  14489. /**
  14490. * Method must be called before 'source-remove' notification is sent.
  14491. * Removes local video SSRC from the notification. If there are no other
  14492. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  14493. * means that there is no point in sending the notification.
  14494. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  14495. * @returns modified 'source-remove' IQ which can be sent to the focus or
  14496. * <tt>null</tt> if no notification shall be sent. It is no longer
  14497. * a Strophe IQ Builder instance, but DOM element tree.
  14498. */
  14499. processSourceRemove: function (sourceRemove) {
  14500. return filterOutSource(sourceRemove, 'source-remove');
  14501. }
  14502. };
  14503. module.exports = LocalVideoSSRCHack;
  14504. },{"./SDP":54}],59:[function(require,module,exports){
  14505. /* global $, $iq, APP, config, messageHandler,
  14506. roomName, sessionTerminated, Strophe, Util */
  14507. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14508. var Settings = require("../settings/Settings");
  14509. var AuthenticationEvents
  14510. = require("../../service/authentication/AuthenticationEvents");
  14511. /**
  14512. * Contains logic responsible for enabling/disabling functionality available
  14513. * only to moderator users.
  14514. */
  14515. var connection = null;
  14516. var focusUserJid;
  14517. function createExpBackoffTimer(step) {
  14518. var count = 1;
  14519. return function (reset) {
  14520. // Reset call
  14521. if (reset) {
  14522. count = 1;
  14523. return;
  14524. }
  14525. // Calculate next timeout
  14526. var timeout = Math.pow(2, count - 1);
  14527. count += 1;
  14528. return timeout * step;
  14529. };
  14530. }
  14531. var getNextTimeout = createExpBackoffTimer(1000);
  14532. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14533. // External authentication stuff
  14534. var externalAuthEnabled = false;
  14535. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14536. // it will be enabled automatically if focus detects the component through
  14537. // service discovery.
  14538. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14539. var eventEmitter = null;
  14540. var Moderator = {
  14541. isModerator: function () {
  14542. return connection && connection.emuc.isModerator();
  14543. },
  14544. isPeerModerator: function (peerJid) {
  14545. return connection &&
  14546. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14547. },
  14548. isExternalAuthEnabled: function () {
  14549. return externalAuthEnabled;
  14550. },
  14551. isSipGatewayEnabled: function () {
  14552. return sipGatewayEnabled;
  14553. },
  14554. setConnection: function (con) {
  14555. connection = con;
  14556. },
  14557. init: function (xmpp, emitter) {
  14558. this.xmppService = xmpp;
  14559. eventEmitter = emitter;
  14560. // Message listener that talks to POPUP window
  14561. function listener(event) {
  14562. if (event.data && event.data.sessionId) {
  14563. if (event.origin !== window.location.origin) {
  14564. console.warn("Ignoring sessionId from different origin: " +
  14565. event.origin);
  14566. return;
  14567. }
  14568. localStorage.setItem('sessionId', event.data.sessionId);
  14569. // After popup is closed we will authenticate
  14570. }
  14571. }
  14572. // Register
  14573. if (window.addEventListener) {
  14574. window.addEventListener("message", listener, false);
  14575. } else {
  14576. window.attachEvent("onmessage", listener);
  14577. }
  14578. },
  14579. onMucMemberLeft: function (jid) {
  14580. console.info("Someone left is it focus ? " + jid);
  14581. var resource = Strophe.getResourceFromJid(jid);
  14582. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14583. console.info(
  14584. "Focus has left the room - leaving conference");
  14585. //hangUp();
  14586. // We'd rather reload to have everything re-initialized
  14587. // FIXME: show some message before reload
  14588. location.reload();
  14589. }
  14590. },
  14591. setFocusUserJid: function (focusJid) {
  14592. if (!focusUserJid) {
  14593. focusUserJid = focusJid;
  14594. console.info("Focus jid set to: " + focusUserJid);
  14595. }
  14596. },
  14597. getFocusUserJid: function () {
  14598. return focusUserJid;
  14599. },
  14600. getFocusComponent: function () {
  14601. // Get focus component address
  14602. var focusComponent = config.hosts.focus;
  14603. // If not specified use default: 'focus.domain'
  14604. if (!focusComponent) {
  14605. focusComponent = 'focus.' + config.hosts.domain;
  14606. }
  14607. return focusComponent;
  14608. },
  14609. createConferenceIq: function (roomName) {
  14610. // Generate create conference IQ
  14611. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14612. // Session Id used for authentication
  14613. var sessionId = localStorage.getItem('sessionId');
  14614. var machineUID = Settings.getSettings().uid;
  14615. console.info(
  14616. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14617. elem.c('conference', {
  14618. xmlns: 'http://jitsi.org/protocol/focus',
  14619. room: roomName,
  14620. 'machine-uid': machineUID
  14621. });
  14622. if (sessionId) {
  14623. elem.attrs({ 'session-id': sessionId});
  14624. }
  14625. if (config.hosts.bridge !== undefined) {
  14626. elem.c(
  14627. 'property',
  14628. { name: 'bridge', value: config.hosts.bridge})
  14629. .up();
  14630. }
  14631. // Tell the focus we have Jigasi configured
  14632. if (config.hosts.call_control !== undefined) {
  14633. elem.c(
  14634. 'property',
  14635. { name: 'call_control', value: config.hosts.call_control})
  14636. .up();
  14637. }
  14638. if (config.channelLastN !== undefined) {
  14639. elem.c(
  14640. 'property',
  14641. { name: 'channelLastN', value: config.channelLastN})
  14642. .up();
  14643. }
  14644. if (config.adaptiveLastN !== undefined) {
  14645. elem.c(
  14646. 'property',
  14647. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14648. .up();
  14649. }
  14650. if (config.adaptiveSimulcast !== undefined) {
  14651. elem.c(
  14652. 'property',
  14653. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14654. .up();
  14655. }
  14656. if (config.openSctp !== undefined) {
  14657. elem.c(
  14658. 'property',
  14659. { name: 'openSctp', value: config.openSctp})
  14660. .up();
  14661. }
  14662. if(config.startAudioMuted !== undefined)
  14663. {
  14664. elem.c(
  14665. 'property',
  14666. { name: 'startAudioMuted', value: config.startAudioMuted})
  14667. .up();
  14668. }
  14669. if(config.startVideoMuted !== undefined)
  14670. {
  14671. elem.c(
  14672. 'property',
  14673. { name: 'startVideoMuted', value: config.startVideoMuted})
  14674. .up();
  14675. }
  14676. elem.c(
  14677. 'property',
  14678. { name: 'simulcastMode', value: 'rewriting'})
  14679. .up();
  14680. elem.up();
  14681. return elem;
  14682. },
  14683. parseSessionId: function (resultIq) {
  14684. var sessionId = $(resultIq).find('conference').attr('session-id');
  14685. if (sessionId) {
  14686. console.info('Received sessionId: ' + sessionId);
  14687. localStorage.setItem('sessionId', sessionId);
  14688. }
  14689. },
  14690. parseConfigOptions: function (resultIq) {
  14691. Moderator.setFocusUserJid(
  14692. $(resultIq).find('conference').attr('focusjid'));
  14693. var authenticationEnabled
  14694. = $(resultIq).find(
  14695. '>conference>property' +
  14696. '[name=\'authentication\'][value=\'true\']').length > 0;
  14697. console.info("Authentication enabled: " + authenticationEnabled);
  14698. externalAuthEnabled = $(resultIq).find(
  14699. '>conference>property' +
  14700. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14701. console.info('External authentication enabled: ' + externalAuthEnabled);
  14702. if (!externalAuthEnabled) {
  14703. // We expect to receive sessionId in 'internal' authentication mode
  14704. Moderator.parseSessionId(resultIq);
  14705. }
  14706. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14707. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14708. authenticationEnabled, authIdentity);
  14709. // Check if focus has auto-detected Jigasi component(this will be also
  14710. // included if we have passed our host from the config)
  14711. if ($(resultIq).find(
  14712. '>conference>property' +
  14713. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14714. sipGatewayEnabled = true;
  14715. }
  14716. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14717. },
  14718. // FIXME: we need to show the fact that we're waiting for the focus
  14719. // to the user(or that focus is not available)
  14720. allocateConferenceFocus: function (roomName, callback) {
  14721. // Try to use focus user JID from the config
  14722. Moderator.setFocusUserJid(config.focusUserJid);
  14723. // Send create conference IQ
  14724. var iq = Moderator.createConferenceIq(roomName);
  14725. var self = this;
  14726. connection.sendIQ(
  14727. iq,
  14728. function (result) {
  14729. // Setup config options
  14730. Moderator.parseConfigOptions(result);
  14731. if ('true' === $(result).find('conference').attr('ready')) {
  14732. // Reset both timers
  14733. getNextTimeout(true);
  14734. getNextErrorTimeout(true);
  14735. // Exec callback
  14736. callback();
  14737. } else {
  14738. var waitMs = getNextTimeout();
  14739. console.info("Waiting for the focus... " + waitMs);
  14740. // Reset error timeout
  14741. getNextErrorTimeout(true);
  14742. window.setTimeout(
  14743. function () {
  14744. Moderator.allocateConferenceFocus(
  14745. roomName, callback);
  14746. }, waitMs);
  14747. }
  14748. },
  14749. function (error) {
  14750. // Invalid session ? remove and try again
  14751. // without session ID to get a new one
  14752. var invalidSession
  14753. = $(error).find('>error>session-invalid').length;
  14754. if (invalidSession) {
  14755. console.info("Session expired! - removing");
  14756. localStorage.removeItem("sessionId");
  14757. }
  14758. if ($(error).find('>error>graceful-shutdown').length) {
  14759. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14760. return;
  14761. }
  14762. // Check for error returned by the reservation system
  14763. var reservationErr = $(error).find('>error>reservation-error');
  14764. if (reservationErr.length) {
  14765. // Trigger error event
  14766. var errorCode = reservationErr.attr('error-code');
  14767. var errorMsg;
  14768. if ($(error).find('>error>text')) {
  14769. errorMsg = $(error).find('>error>text').text();
  14770. }
  14771. eventEmitter.emit(
  14772. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14773. return;
  14774. }
  14775. // Not authorized to create new room
  14776. if ($(error).find('>error>not-authorized').length) {
  14777. console.warn("Unauthorized to start the conference", error);
  14778. var toDomain
  14779. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14780. if (toDomain !== config.hosts.anonymousdomain) {
  14781. // FIXME: "is external" should come either from
  14782. // the focus or config.js
  14783. externalAuthEnabled = true;
  14784. }
  14785. eventEmitter.emit(
  14786. XMPPEvents.AUTHENTICATION_REQUIRED,
  14787. function () {
  14788. Moderator.allocateConferenceFocus(
  14789. roomName, callback);
  14790. });
  14791. return;
  14792. }
  14793. var waitMs = getNextErrorTimeout();
  14794. console.error("Focus error, retry after " + waitMs, error);
  14795. // Show message
  14796. var focusComponent = Moderator.getFocusComponent();
  14797. var retrySec = waitMs / 1000;
  14798. // FIXME: message is duplicated ?
  14799. // Do not show in case of session invalid
  14800. // which means just a retry
  14801. if (!invalidSession) {
  14802. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  14803. focusComponent, retrySec);
  14804. }
  14805. // Reset response timeout
  14806. getNextTimeout(true);
  14807. window.setTimeout(
  14808. function () {
  14809. Moderator.allocateConferenceFocus(roomName, callback);
  14810. }, waitMs);
  14811. }
  14812. );
  14813. },
  14814. getLoginUrl: function (roomName, urlCallback) {
  14815. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14816. iq.c('login-url', {
  14817. xmlns: 'http://jitsi.org/protocol/focus',
  14818. room: roomName,
  14819. 'machine-uid': Settings.getSettings().uid
  14820. });
  14821. connection.sendIQ(
  14822. iq,
  14823. function (result) {
  14824. var url = $(result).find('login-url').attr('url');
  14825. url = url = decodeURIComponent(url);
  14826. if (url) {
  14827. console.info("Got auth url: " + url);
  14828. urlCallback(url);
  14829. } else {
  14830. console.error(
  14831. "Failed to get auth url from the focus", result);
  14832. }
  14833. },
  14834. function (error) {
  14835. console.error("Get auth url error", error);
  14836. }
  14837. );
  14838. },
  14839. getPopupLoginUrl: function (roomName, urlCallback) {
  14840. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14841. iq.c('login-url', {
  14842. xmlns: 'http://jitsi.org/protocol/focus',
  14843. room: roomName,
  14844. 'machine-uid': Settings.getSettings().uid,
  14845. popup: true
  14846. });
  14847. connection.sendIQ(
  14848. iq,
  14849. function (result) {
  14850. var url = $(result).find('login-url').attr('url');
  14851. url = url = decodeURIComponent(url);
  14852. if (url) {
  14853. console.info("Got POPUP auth url: " + url);
  14854. urlCallback(url);
  14855. } else {
  14856. console.error(
  14857. "Failed to get POPUP auth url from the focus", result);
  14858. }
  14859. },
  14860. function (error) {
  14861. console.error('Get POPUP auth url error', error);
  14862. }
  14863. );
  14864. },
  14865. logout: function (callback) {
  14866. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14867. var sessionId = localStorage.getItem('sessionId');
  14868. if (!sessionId) {
  14869. callback();
  14870. return;
  14871. }
  14872. iq.c('logout', {
  14873. xmlns: 'http://jitsi.org/protocol/focus',
  14874. 'session-id': sessionId
  14875. });
  14876. connection.sendIQ(
  14877. iq,
  14878. function (result) {
  14879. var logoutUrl = $(result).find('logout').attr('logout-url');
  14880. if (logoutUrl) {
  14881. logoutUrl = decodeURIComponent(logoutUrl);
  14882. }
  14883. console.info("Log out OK, url: " + logoutUrl, result);
  14884. localStorage.removeItem('sessionId');
  14885. callback(logoutUrl);
  14886. },
  14887. function (error) {
  14888. console.error("Logout error", error);
  14889. }
  14890. );
  14891. }
  14892. };
  14893. module.exports = Moderator;
  14894. },{"../../service/authentication/AuthenticationEvents":108,"../../service/xmpp/XMPPEvents":113,"../settings/Settings":47}],60:[function(require,module,exports){
  14895. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  14896. Toolbar, Util */
  14897. var Moderator = require("./moderator");
  14898. var recordingToken = null;
  14899. var recordingEnabled;
  14900. /**
  14901. * Whether to use a jirecon component for recording, or use the videobridge
  14902. * through COLIBRI.
  14903. */
  14904. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14905. /**
  14906. * The ID of the jirecon recording session. Jirecon generates it when we
  14907. * initially start recording, and it needs to be used in subsequent requests
  14908. * to jirecon.
  14909. */
  14910. var jireconRid = null;
  14911. /**
  14912. * The callback to update the recording button. Currently used from colibri
  14913. * after receiving a pending status.
  14914. */
  14915. var recordingStateChangeCallback = null;
  14916. function setRecordingToken(token) {
  14917. recordingToken = token;
  14918. }
  14919. function setRecordingJirecon(state, token, callback, connection) {
  14920. if (state == recordingEnabled){
  14921. return;
  14922. }
  14923. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14924. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14925. action: (state === 'on') ? 'start' : 'stop',
  14926. mucjid: connection.emuc.roomjid});
  14927. if (state === 'off'){
  14928. iq.attrs({rid: jireconRid});
  14929. }
  14930. console.log('Start recording');
  14931. connection.sendIQ(
  14932. iq,
  14933. function (result) {
  14934. // TODO wait for an IQ with the real status, since this is
  14935. // provisional?
  14936. jireconRid = $(result).find('recording').attr('rid');
  14937. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  14938. '(jirecon)' + result);
  14939. recordingEnabled = state;
  14940. if (state === 'off'){
  14941. jireconRid = null;
  14942. }
  14943. callback(state);
  14944. },
  14945. function (error) {
  14946. console.log('Failed to start recording, error: ', error);
  14947. callback(recordingEnabled);
  14948. });
  14949. }
  14950. // Sends a COLIBRI message which enables or disables (according to 'state')
  14951. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14952. // with the new recording state, according to the IQ.
  14953. function setRecordingColibri(state, token, callback, connection) {
  14954. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14955. elem.c('conference', {
  14956. xmlns: 'http://jitsi.org/protocol/colibri'
  14957. });
  14958. elem.c('recording', {state: state, token: token});
  14959. connection.sendIQ(elem,
  14960. function (result) {
  14961. console.log('Set recording "', state, '". Result:', result);
  14962. var recordingElem = $(result).find('>conference>recording');
  14963. var newState = recordingElem.attr('state');
  14964. recordingEnabled = newState;
  14965. callback(newState);
  14966. if (newState === 'pending' && recordingStateChangeCallback == null) {
  14967. recordingStateChangeCallback = callback;
  14968. connection.addHandler(function(iq){
  14969. var state = $(iq).find('recording').attr('state');
  14970. if (state)
  14971. recordingStateChangeCallback(state);
  14972. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  14973. }
  14974. },
  14975. function (error) {
  14976. console.warn(error);
  14977. callback(recordingEnabled);
  14978. }
  14979. );
  14980. }
  14981. function setRecording(state, token, callback, connection) {
  14982. if (useJirecon){
  14983. setRecordingJirecon(state, token, callback, connection);
  14984. } else {
  14985. setRecordingColibri(state, token, callback, connection);
  14986. }
  14987. }
  14988. var Recording = {
  14989. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  14990. if (!Moderator.isModerator()) {
  14991. console.log(
  14992. 'non-focus, or conference not yet organized:' +
  14993. ' not enabling recording');
  14994. return;
  14995. }
  14996. var self = this;
  14997. // Jirecon does not (currently) support a token.
  14998. if (!recordingToken && !useJirecon) {
  14999. tokenEmptyCallback(function (value) {
  15000. setRecordingToken(value);
  15001. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  15002. });
  15003. return;
  15004. }
  15005. var oldState = recordingEnabled;
  15006. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  15007. setRecording(newState,
  15008. recordingToken,
  15009. function (state) {
  15010. console.log("New recording state: ", state);
  15011. if (state === oldState) {
  15012. // FIXME: new focus:
  15013. // this will not work when moderator changes
  15014. // during active session. Then it will assume that
  15015. // recording status has changed to true, but it might have
  15016. // been already true(and we only received actual status from
  15017. // the focus).
  15018. //
  15019. // SO we start with status null, so that it is initialized
  15020. // here and will fail only after second click, so if invalid
  15021. // token was used we have to press the button twice before
  15022. // current status will be fetched and token will be reset.
  15023. //
  15024. // Reliable way would be to return authentication error.
  15025. // Or status update when moderator connects.
  15026. // Or we have to stop recording session when current
  15027. // moderator leaves the room.
  15028. // Failed to change, reset the token because it might
  15029. // have been wrong
  15030. setRecordingToken(null);
  15031. }
  15032. recordingStateChangeCallback(state);
  15033. },
  15034. connection
  15035. );
  15036. }
  15037. };
  15038. module.exports = Recording;
  15039. },{"./moderator":59}],61:[function(require,module,exports){
  15040. /* jshint -W117 */
  15041. /* a simple MUC connection plugin
  15042. * can only handle a single MUC room
  15043. */
  15044. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15045. var Moderator = require("./moderator");
  15046. module.exports = function(XMPP, eventEmitter) {
  15047. Strophe.addConnectionPlugin('emuc', {
  15048. connection: null,
  15049. roomjid: null,
  15050. myroomjid: null,
  15051. members: {},
  15052. list_members: [], // so we can elect a new focus
  15053. presMap: {},
  15054. preziMap: {},
  15055. joined: false,
  15056. isOwner: false,
  15057. role: null,
  15058. focusMucJid: null,
  15059. bridgeIsDown: false,
  15060. init: function (conn) {
  15061. this.connection = conn;
  15062. },
  15063. initPresenceMap: function (myroomjid) {
  15064. this.presMap['to'] = myroomjid;
  15065. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15066. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15067. this.addAudioInfoToPresence(true);
  15068. }
  15069. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15070. this.addVideoInfoToPresence(true);
  15071. }
  15072. },
  15073. doJoin: function (jid, password) {
  15074. this.myroomjid = jid;
  15075. console.info("Joined MUC as " + this.myroomjid);
  15076. this.initPresenceMap(this.myroomjid);
  15077. if (!this.roomjid) {
  15078. this.roomjid = Strophe.getBareJidFromJid(jid);
  15079. // add handlers (just once)
  15080. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15081. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15082. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15083. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15084. }
  15085. if (password !== undefined) {
  15086. this.presMap['password'] = password;
  15087. }
  15088. this.sendPresence();
  15089. },
  15090. doLeave: function () {
  15091. console.log("do leave", this.myroomjid);
  15092. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15093. this.presMap.length = 0;
  15094. this.connection.send(pres);
  15095. },
  15096. createNonAnonymousRoom: function () {
  15097. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15098. var getForm = $iq({type: 'get', to: this.roomjid})
  15099. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15100. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15101. var self = this;
  15102. this.connection.sendIQ(getForm, function (form) {
  15103. if (!$(form).find(
  15104. '>query>x[xmlns="jabber:x:data"]' +
  15105. '>field[var="muc#roomconfig_whois"]').length) {
  15106. console.error('non-anonymous rooms not supported');
  15107. return;
  15108. }
  15109. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15110. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15111. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15112. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15113. .c('value')
  15114. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15115. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15116. .c('value').t('anyone').up().up();
  15117. self.connection.sendIQ(formSubmit);
  15118. }, function (error) {
  15119. console.error("Error getting room configuration form");
  15120. });
  15121. },
  15122. onPresence: function (pres) {
  15123. var from = pres.getAttribute('from');
  15124. // What is this for? A workaround for something?
  15125. if (pres.getAttribute('type')) {
  15126. return true;
  15127. }
  15128. // Parse etherpad tag.
  15129. var etherpad = $(pres).find('>etherpad');
  15130. if (etherpad.length) {
  15131. if (config.etherpad_base) {
  15132. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15133. }
  15134. }
  15135. // Parse prezi tag.
  15136. var presentation = $(pres).find('>prezi');
  15137. if (presentation.length) {
  15138. var url = presentation.attr('url');
  15139. var current = presentation.find('>current').text();
  15140. console.log('presentation info received from', from, url);
  15141. if (this.preziMap[from] == null) {
  15142. this.preziMap[from] = url;
  15143. $(document).trigger('presentationadded.muc', [from, url, current]);
  15144. }
  15145. else {
  15146. $(document).trigger('gotoslide.muc', [from, url, current]);
  15147. }
  15148. }
  15149. else if (this.preziMap[from] != null) {
  15150. var url = this.preziMap[from];
  15151. delete this.preziMap[from];
  15152. $(document).trigger('presentationremoved.muc', [from, url]);
  15153. }
  15154. // Parse audio info tag.
  15155. var audioMuted = $(pres).find('>audiomuted');
  15156. if (audioMuted.length) {
  15157. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  15158. from, (audioMuted.text() === "true"));
  15159. }
  15160. // Parse video info tag.
  15161. var videoMuted = $(pres).find('>videomuted');
  15162. if (videoMuted.length) {
  15163. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  15164. from, (videoMuted.text() === "true"));
  15165. }
  15166. var startMuted = $(pres).find('>startmuted');
  15167. if (startMuted.length)
  15168. {
  15169. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15170. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  15171. }
  15172. var devices = $(pres).find('>devices');
  15173. if(devices.length)
  15174. {
  15175. var audio = devices.find('>audio');
  15176. var video = devices.find('>video');
  15177. var devicesValues = {audio: false, video: false};
  15178. if(audio.length && audio.text() === "true")
  15179. {
  15180. devicesValues.audio = true;
  15181. }
  15182. if(video.length && video.text() === "true")
  15183. {
  15184. devicesValues.video = true;
  15185. }
  15186. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15187. Strophe.getResourceFromJid(from), devicesValues);
  15188. }
  15189. var videoType = $(pres).find('>videoType');
  15190. if (videoType.length)
  15191. {
  15192. if (videoType.text().length)
  15193. {
  15194. eventEmitter.emit(XMPPEvents.VIDEO_TYPE,
  15195. Strophe.getResourceFromJid(from), videoType.text());
  15196. }
  15197. }
  15198. var stats = $(pres).find('>stats');
  15199. if (stats.length) {
  15200. var statsObj = {};
  15201. Strophe.forEachChild(stats[0], "stat", function (el) {
  15202. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15203. });
  15204. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15205. }
  15206. // Parse status.
  15207. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15208. this.isOwner = true;
  15209. this.createNonAnonymousRoom();
  15210. }
  15211. // Parse roles.
  15212. var member = {};
  15213. member.show = $(pres).find('>show').text();
  15214. member.status = $(pres).find('>status').text();
  15215. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15216. member.affiliation = tmp.attr('affiliation');
  15217. member.role = tmp.attr('role');
  15218. // Focus recognition
  15219. member.jid = tmp.attr('jid');
  15220. member.isFocus = false;
  15221. if (member.jid
  15222. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15223. member.isFocus = true;
  15224. }
  15225. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15226. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  15227. if (from == this.myroomjid) {
  15228. if (member.affiliation == 'owner') this.isOwner = true;
  15229. if (this.role !== member.role) {
  15230. this.role = member.role;
  15231. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15232. from, member, pres, Moderator.isModerator());
  15233. }
  15234. if (!this.joined) {
  15235. this.joined = true;
  15236. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15237. this.list_members.push(from);
  15238. }
  15239. } else if (this.members[from] === undefined) {
  15240. // new participant
  15241. this.members[from] = member;
  15242. this.list_members.push(from);
  15243. console.log('entered', from, member);
  15244. if (member.isFocus) {
  15245. this.focusMucJid = from;
  15246. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15247. }
  15248. else {
  15249. var id = $(pres).find('>userId').text();
  15250. var email = $(pres).find('>email');
  15251. if (email.length > 0) {
  15252. id = email.text();
  15253. }
  15254. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15255. }
  15256. } else {
  15257. // Presence update for existing participant
  15258. // Watch role change:
  15259. if (this.members[from].role != member.role) {
  15260. this.members[from].role = member.role;
  15261. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15262. member.role, member.displayName);
  15263. }
  15264. }
  15265. // Always trigger presence to update bindings
  15266. this.parsePresence(from, member, pres);
  15267. // Trigger status message update
  15268. if (member.status) {
  15269. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15270. }
  15271. return true;
  15272. },
  15273. onPresenceUnavailable: function (pres) {
  15274. var from = pres.getAttribute('from');
  15275. // room destroyed ?
  15276. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15277. '>destroy').length) {
  15278. var reason;
  15279. var reasonSelect = $(pres).find(
  15280. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15281. '>destroy>reason');
  15282. if (reasonSelect.length) {
  15283. reason = reasonSelect.text();
  15284. }
  15285. XMPP.disposeConference(false);
  15286. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15287. return true;
  15288. }
  15289. // Status code 110 indicates that this notification is "self-presence".
  15290. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15291. delete this.members[from];
  15292. this.list_members.splice(this.list_members.indexOf(from), 1);
  15293. this.onParticipantLeft(from);
  15294. }
  15295. // If the status code is 110 this means we're leaving and we would like
  15296. // to remove everyone else from our view, so we trigger the event.
  15297. else if (this.list_members.length > 1) {
  15298. for (var i = 0; i < this.list_members.length; i++) {
  15299. var member = this.list_members[i];
  15300. delete this.members[i];
  15301. this.list_members.splice(i, 1);
  15302. this.onParticipantLeft(member);
  15303. }
  15304. }
  15305. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15306. $(document).trigger('kicked.muc', [from]);
  15307. if (this.myroomjid === from) {
  15308. XMPP.disposeConference(false);
  15309. eventEmitter.emit(XMPPEvents.KICKED);
  15310. }
  15311. }
  15312. return true;
  15313. },
  15314. onPresenceError: function (pres) {
  15315. var from = pres.getAttribute('from');
  15316. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15317. console.log('on password required', from);
  15318. var self = this;
  15319. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15320. self.doJoin(from, value);
  15321. });
  15322. } else if ($(pres).find(
  15323. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15324. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15325. if (toDomain === config.hosts.anonymousdomain) {
  15326. // enter the room by replying with 'not-authorized'. This would
  15327. // result in reconnection from authorized domain.
  15328. // We're either missing Jicofo/Prosody config for anonymous
  15329. // domains or something is wrong.
  15330. // XMPP.promptLogin();
  15331. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15332. } else {
  15333. console.warn('onPresError ', pres);
  15334. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15335. }
  15336. } else {
  15337. console.warn('onPresError ', pres);
  15338. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15339. }
  15340. return true;
  15341. },
  15342. sendMessage: function (body, nickname) {
  15343. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15344. msg.c('body', body).up();
  15345. if (nickname) {
  15346. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15347. }
  15348. this.connection.send(msg);
  15349. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15350. },
  15351. setSubject: function (subject) {
  15352. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15353. msg.c('subject', subject);
  15354. this.connection.send(msg);
  15355. console.log("topic changed to " + subject);
  15356. },
  15357. onMessage: function (msg) {
  15358. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15359. var from = msg.getAttribute('from');
  15360. var nick =
  15361. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15362. .text() ||
  15363. Strophe.getResourceFromJid(from);
  15364. var txt = $(msg).find('>body').text();
  15365. var type = msg.getAttribute("type");
  15366. if (type == "error") {
  15367. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15368. $(msg).find('>text').text(), txt);
  15369. return true;
  15370. }
  15371. var subject = $(msg).find('>subject');
  15372. if (subject.length) {
  15373. var subjectText = subject.text();
  15374. if (subjectText || subjectText == "") {
  15375. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15376. console.log("Subject is changed to " + subjectText);
  15377. }
  15378. }
  15379. // xep-0203 delay
  15380. var stamp = $(msg).find('>delay').attr('stamp');
  15381. if (!stamp) {
  15382. // or xep-0091 delay, UTC timestamp
  15383. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15384. if (stamp) {
  15385. // the format is CCYYMMDDThh:mm:ss
  15386. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15387. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15388. }
  15389. }
  15390. if (txt) {
  15391. console.log('chat', nick, txt);
  15392. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15393. from, nick, txt, this.myroomjid, stamp);
  15394. }
  15395. return true;
  15396. },
  15397. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15398. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15399. var ob = this;
  15400. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15401. function (res) {
  15402. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15403. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15404. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15405. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15406. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15407. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15408. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15409. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15410. ob.connection.sendIQ(formsubmit,
  15411. onSuccess,
  15412. onError);
  15413. } else {
  15414. onNotSupported();
  15415. }
  15416. }, onError);
  15417. },
  15418. kick: function (jid) {
  15419. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15420. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15421. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15422. .c('reason').t('You have been kicked.').up().up().up();
  15423. this.connection.sendIQ(
  15424. kickIQ,
  15425. function (result) {
  15426. console.log('Kick participant with jid: ', jid, result);
  15427. },
  15428. function (error) {
  15429. console.log('Kick participant error: ', error);
  15430. });
  15431. },
  15432. sendPresence: function () {
  15433. if (!this.presMap['to']) {
  15434. // Too early to send presence - not initialized
  15435. return;
  15436. }
  15437. var pres = $pres({to: this.presMap['to'] });
  15438. pres.c('x', {xmlns: this.presMap['xns']});
  15439. if (this.presMap['password']) {
  15440. pres.c('password').t(this.presMap['password']).up();
  15441. }
  15442. pres.up();
  15443. // Send XEP-0115 'c' stanza that contains our capabilities info
  15444. if (this.connection.caps) {
  15445. this.connection.caps.node = config.clientNode;
  15446. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15447. }
  15448. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15449. .t(navigator.userAgent).up();
  15450. if (this.presMap['bridgeIsDown']) {
  15451. pres.c('bridgeIsDown').up();
  15452. }
  15453. if (this.presMap['email']) {
  15454. pres.c('email').t(this.presMap['email']).up();
  15455. }
  15456. if (this.presMap['userId']) {
  15457. pres.c('userId').t(this.presMap['userId']).up();
  15458. }
  15459. if (this.presMap['displayName']) {
  15460. // XEP-0172
  15461. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15462. .t(this.presMap['displayName']).up();
  15463. }
  15464. if(this.presMap["devices"])
  15465. {
  15466. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15467. .c('video').t(this.presMap['devices'].video).up().up();
  15468. }
  15469. if (this.presMap['audions']) {
  15470. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15471. .t(this.presMap['audiomuted']).up();
  15472. }
  15473. if (this.presMap['videons']) {
  15474. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15475. .t(this.presMap['videomuted']).up();
  15476. }
  15477. if (this.presMap['videoTypeNs']) {
  15478. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  15479. .t(this.presMap['videoType']).up();
  15480. }
  15481. if (this.presMap['statsns']) {
  15482. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15483. for (var stat in this.presMap["stats"])
  15484. if (this.presMap["stats"][stat] != null)
  15485. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15486. pres.up();
  15487. }
  15488. if (this.presMap['prezins']) {
  15489. pres.c('prezi',
  15490. {xmlns: this.presMap['prezins'],
  15491. 'url': this.presMap['preziurl']})
  15492. .c('current').t(this.presMap['prezicurrent']).up().up();
  15493. }
  15494. if(this.presMap["startMuted"] !== undefined)
  15495. {
  15496. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15497. video: this.presMap["startMuted"].video,
  15498. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15499. delete this.presMap["startMuted"];
  15500. }
  15501. pres.up();
  15502. this.connection.send(pres);
  15503. },
  15504. addDisplayNameToPresence: function (displayName) {
  15505. this.presMap['displayName'] = displayName;
  15506. },
  15507. addDevicesToPresence: function (devices) {
  15508. this.presMap['devices'] = devices;
  15509. },
  15510. /**
  15511. * Adds the info about the type of our video stream.
  15512. * @param videoType 'camera' or 'screen'
  15513. */
  15514. addVideoTypeToPresence: function (videoType) {
  15515. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  15516. this.presMap['videoType'] = videoType;
  15517. },
  15518. addPreziToPresence: function (url, currentSlide) {
  15519. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15520. this.presMap['preziurl'] = url;
  15521. this.presMap['prezicurrent'] = currentSlide;
  15522. },
  15523. removePreziFromPresence: function () {
  15524. delete this.presMap['prezins'];
  15525. delete this.presMap['preziurl'];
  15526. delete this.presMap['prezicurrent'];
  15527. },
  15528. addCurrentSlideToPresence: function (currentSlide) {
  15529. this.presMap['prezicurrent'] = currentSlide;
  15530. },
  15531. getPrezi: function (roomjid) {
  15532. return this.preziMap[roomjid];
  15533. },
  15534. addAudioInfoToPresence: function (isMuted) {
  15535. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15536. this.presMap['audiomuted'] = isMuted.toString();
  15537. },
  15538. addVideoInfoToPresence: function (isMuted) {
  15539. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15540. this.presMap['videomuted'] = isMuted.toString();
  15541. },
  15542. addConnectionInfoToPresence: function (stats) {
  15543. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15544. this.presMap['stats'] = stats;
  15545. },
  15546. findJidFromResource: function (resourceJid) {
  15547. if (resourceJid &&
  15548. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15549. return this.myroomjid;
  15550. }
  15551. var peerJid = null;
  15552. Object.keys(this.members).some(function (jid) {
  15553. peerJid = jid;
  15554. return Strophe.getResourceFromJid(jid) === resourceJid;
  15555. });
  15556. return peerJid;
  15557. },
  15558. addBridgeIsDownToPresence: function () {
  15559. this.presMap['bridgeIsDown'] = true;
  15560. },
  15561. addEmailToPresence: function (email) {
  15562. this.presMap['email'] = email;
  15563. },
  15564. addUserIdToPresence: function (userId) {
  15565. this.presMap['userId'] = userId;
  15566. },
  15567. addStartMutedToPresence: function (audio, video) {
  15568. this.presMap["startMuted"] = {audio: audio, video: video};
  15569. },
  15570. isModerator: function () {
  15571. return this.role === 'moderator';
  15572. },
  15573. getMemberRole: function (peerJid) {
  15574. if (this.members[peerJid]) {
  15575. return this.members[peerJid].role;
  15576. }
  15577. return null;
  15578. },
  15579. onParticipantLeft: function (jid) {
  15580. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15581. this.connection.jingle.terminateByJid(jid);
  15582. if (this.getPrezi(jid)) {
  15583. $(document).trigger('presentationremoved.muc',
  15584. [jid, this.getPrezi(jid)]);
  15585. }
  15586. Moderator.onMucMemberLeft(jid);
  15587. },
  15588. parsePresence: function (from, member, pres) {
  15589. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  15590. this.bridgeIsDown = true;
  15591. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15592. }
  15593. if(member.isFocus)
  15594. return;
  15595. var displayName = !config.displayJids
  15596. ? member.displayName : Strophe.getResourceFromJid(from);
  15597. if (displayName && displayName.length > 0) {
  15598. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15599. }
  15600. var id = $(pres).find('>userID').text();
  15601. var email = $(pres).find('>email');
  15602. if (email.length > 0) {
  15603. id = email.text();
  15604. }
  15605. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15606. }
  15607. });
  15608. };
  15609. },{"../../service/xmpp/XMPPEvents":113,"./moderator":59}],62:[function(require,module,exports){
  15610. /* jshint -W117 */
  15611. var JingleSession = require("./JingleSession");
  15612. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15613. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15614. module.exports = function(XMPP, eventEmitter) {
  15615. function CallIncomingJingle(sid, connection) {
  15616. var sess = connection.jingle.sessions[sid];
  15617. // TODO: do we check activecall == null?
  15618. connection.jingle.activecall = sess;
  15619. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15620. // TODO: check affiliation and/or role
  15621. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15622. sess.usedrip = true; // not-so-naive trickle ice
  15623. sess.sendAnswer();
  15624. sess.accept();
  15625. }
  15626. Strophe.addConnectionPlugin('jingle', {
  15627. connection: null,
  15628. sessions: {},
  15629. jid2session: {},
  15630. ice_config: {iceServers: []},
  15631. pc_constraints: {},
  15632. activecall: null,
  15633. media_constraints: {
  15634. mandatory: {
  15635. 'OfferToReceiveAudio': true,
  15636. 'OfferToReceiveVideo': true
  15637. }
  15638. // MozDontOfferDataChannel: true when this is firefox
  15639. },
  15640. init: function (conn) {
  15641. this.connection = conn;
  15642. if (this.connection.disco) {
  15643. // http://xmpp.org/extensions/xep-0167.html#support
  15644. // http://xmpp.org/extensions/xep-0176.html#support
  15645. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15646. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15647. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15648. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15649. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15650. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15651. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15652. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15653. || RTCBrowserType.isTemasysPluginUsed()) {
  15654. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15655. }
  15656. // this is dealt with by SDP O/A so we don't need to announce this
  15657. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15658. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15659. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15660. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15661. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15662. }
  15663. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15664. },
  15665. onJingle: function (iq) {
  15666. var sid = $(iq).find('jingle').attr('sid');
  15667. var action = $(iq).find('jingle').attr('action');
  15668. var fromJid = iq.getAttribute('from');
  15669. // send ack first
  15670. var ack = $iq({type: 'result',
  15671. to: fromJid,
  15672. id: iq.getAttribute('id')
  15673. });
  15674. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15675. var sess = this.sessions[sid];
  15676. if ('session-initiate' != action) {
  15677. if (sess === null) {
  15678. ack.type = 'error';
  15679. ack.c('error', {type: 'cancel'})
  15680. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15681. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15682. this.connection.send(ack);
  15683. return true;
  15684. }
  15685. // local jid is not checked
  15686. if (fromJid != sess.peerjid) {
  15687. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15688. ack.type = 'error';
  15689. ack.c('error', {type: 'cancel'})
  15690. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15691. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15692. this.connection.send(ack);
  15693. return true;
  15694. }
  15695. } else if (sess !== undefined) {
  15696. // existing session with same session id
  15697. // this might be out-of-order if the sess.peerjid is the same as from
  15698. ack.type = 'error';
  15699. ack.c('error', {type: 'cancel'})
  15700. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15701. console.warn('duplicate session id', sid);
  15702. this.connection.send(ack);
  15703. return true;
  15704. }
  15705. // FIXME: check for a defined action
  15706. this.connection.send(ack);
  15707. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15708. switch (action) {
  15709. case 'session-initiate':
  15710. var startMuted = $(iq).find('jingle>startmuted');
  15711. if (startMuted && startMuted.length > 0) {
  15712. var audioMuted = startMuted.attr("audio");
  15713. var videoMuted = startMuted.attr("video");
  15714. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15715. audioMuted === "true", videoMuted === "true");
  15716. }
  15717. sess = new JingleSession(
  15718. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15719. this.connection, XMPP, eventEmitter);
  15720. // configure session
  15721. sess.media_constraints = this.media_constraints;
  15722. sess.pc_constraints = this.pc_constraints;
  15723. sess.ice_config = this.ice_config;
  15724. sess.initiate(fromJid, false);
  15725. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15726. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15727. this.sessions[sess.sid] = sess;
  15728. this.jid2session[sess.peerjid] = sess;
  15729. // the callback should either
  15730. // .sendAnswer and .accept
  15731. // or .sendTerminate -- not necessarily synchronus
  15732. CallIncomingJingle(sess.sid, this.connection);
  15733. break;
  15734. case 'session-accept':
  15735. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15736. sess.accept();
  15737. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15738. break;
  15739. case 'session-terminate':
  15740. // If this is not the focus sending the terminate, we have
  15741. // nothing more to do here.
  15742. if (Object.keys(this.sessions).length < 1
  15743. || !(this.sessions[Object.keys(this.sessions)[0]]
  15744. instanceof JingleSession))
  15745. {
  15746. break;
  15747. }
  15748. console.log('terminating...', sess.sid);
  15749. sess.terminate();
  15750. this.terminate(sess.sid);
  15751. if ($(iq).find('>jingle>reason').length) {
  15752. $(document).trigger('callterminated.jingle', [
  15753. sess.sid,
  15754. sess.peerjid,
  15755. $(iq).find('>jingle>reason>:first')[0].tagName,
  15756. $(iq).find('>jingle>reason>text').text()
  15757. ]);
  15758. } else {
  15759. $(document).trigger('callterminated.jingle',
  15760. [sess.sid, sess.peerjid]);
  15761. }
  15762. break;
  15763. case 'transport-info':
  15764. sess.addIceCandidate($(iq).find('>jingle>content'));
  15765. break;
  15766. case 'session-info':
  15767. var affected;
  15768. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15769. $(document).trigger('ringing.jingle', [sess.sid]);
  15770. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15771. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15772. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15773. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15774. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15775. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15776. }
  15777. break;
  15778. case 'addsource': // FIXME: proprietary, un-jingleish
  15779. case 'source-add': // FIXME: proprietary
  15780. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15781. break;
  15782. case 'removesource': // FIXME: proprietary, un-jingleish
  15783. case 'source-remove': // FIXME: proprietary
  15784. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15785. break;
  15786. default:
  15787. console.warn('jingle action not implemented', action);
  15788. break;
  15789. }
  15790. return true;
  15791. },
  15792. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15793. var sess = new JingleSession(myjid || this.connection.jid,
  15794. Math.random().toString(36).substr(2, 12), // random string
  15795. this.connection, XMPP, eventEmitter);
  15796. // configure session
  15797. sess.media_constraints = this.media_constraints;
  15798. sess.pc_constraints = this.pc_constraints;
  15799. sess.ice_config = this.ice_config;
  15800. sess.initiate(peerjid, true);
  15801. this.sessions[sess.sid] = sess;
  15802. this.jid2session[sess.peerjid] = sess;
  15803. sess.sendOffer();
  15804. return sess;
  15805. },
  15806. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15807. if (sid === null || sid === undefined) {
  15808. for (sid in this.sessions) {
  15809. if (this.sessions[sid].state != 'ended') {
  15810. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15811. this.sessions[sid].terminate();
  15812. }
  15813. delete this.jid2session[this.sessions[sid].peerjid];
  15814. delete this.sessions[sid];
  15815. }
  15816. } else if (this.sessions.hasOwnProperty(sid)) {
  15817. if (this.sessions[sid].state != 'ended') {
  15818. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15819. this.sessions[sid].terminate();
  15820. }
  15821. delete this.jid2session[this.sessions[sid].peerjid];
  15822. delete this.sessions[sid];
  15823. }
  15824. },
  15825. // Used to terminate a session when an unavailable presence is received.
  15826. terminateByJid: function (jid) {
  15827. if (this.jid2session.hasOwnProperty(jid)) {
  15828. var sess = this.jid2session[jid];
  15829. if (sess) {
  15830. sess.terminate();
  15831. console.log('peer went away silently', jid);
  15832. delete this.sessions[sess.sid];
  15833. delete this.jid2session[jid];
  15834. $(document).trigger('callterminated.jingle',
  15835. [sess.sid, jid], 'gone');
  15836. }
  15837. }
  15838. },
  15839. terminateRemoteByJid: function (jid, reason) {
  15840. if (this.jid2session.hasOwnProperty(jid)) {
  15841. var sess = this.jid2session[jid];
  15842. if (sess) {
  15843. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15844. sess.terminate();
  15845. console.log('terminate peer with jid', sess.sid, jid);
  15846. delete this.sessions[sess.sid];
  15847. delete this.jid2session[jid];
  15848. $(document).trigger('callterminated.jingle',
  15849. [sess.sid, jid, 'kicked']);
  15850. }
  15851. }
  15852. },
  15853. getStunAndTurnCredentials: function () {
  15854. // get stun and turn configuration from server via xep-0215
  15855. // uses time-limited credentials as described in
  15856. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15857. //
  15858. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15859. // for a prosody module which implements this
  15860. //
  15861. // currently, this doesn't work with updateIce and therefore credentials with a long
  15862. // validity have to be fetched before creating the peerconnection
  15863. // TODO: implement refresh via updateIce as described in
  15864. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15865. var self = this;
  15866. this.connection.sendIQ(
  15867. $iq({type: 'get', to: this.connection.domain})
  15868. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15869. function (res) {
  15870. var iceservers = [];
  15871. $(res).find('>services>service').each(function (idx, el) {
  15872. el = $(el);
  15873. var dict = {};
  15874. var type = el.attr('type');
  15875. switch (type) {
  15876. case 'stun':
  15877. dict.url = 'stun:' + el.attr('host');
  15878. if (el.attr('port')) {
  15879. dict.url += ':' + el.attr('port');
  15880. }
  15881. iceservers.push(dict);
  15882. break;
  15883. case 'turn':
  15884. case 'turns':
  15885. dict.url = type + ':';
  15886. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15887. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15888. dict.url += el.attr('username') + '@';
  15889. } else {
  15890. dict.username = el.attr('username'); // only works in M28
  15891. }
  15892. }
  15893. dict.url += el.attr('host');
  15894. if (el.attr('port') && el.attr('port') != '3478') {
  15895. dict.url += ':' + el.attr('port');
  15896. }
  15897. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15898. dict.url += '?transport=' + el.attr('transport');
  15899. }
  15900. if (el.attr('password')) {
  15901. dict.credential = el.attr('password');
  15902. }
  15903. iceservers.push(dict);
  15904. break;
  15905. }
  15906. });
  15907. self.ice_config.iceServers = iceservers;
  15908. },
  15909. function (err) {
  15910. console.warn('getting turn credentials failed', err);
  15911. console.warn('is mod_turncredentials or similar installed?');
  15912. }
  15913. );
  15914. // implement push?
  15915. },
  15916. /**
  15917. * Returns the data saved in 'updateLog' in a format to be logged.
  15918. */
  15919. getLog: function () {
  15920. var data = {};
  15921. var self = this;
  15922. Object.keys(this.sessions).forEach(function (sid) {
  15923. var session = self.sessions[sid];
  15924. if (session.peerconnection && session.peerconnection.updateLog) {
  15925. // FIXME: should probably be a .dump call
  15926. data["jingle_" + session.sid] = {
  15927. updateLog: session.peerconnection.updateLog,
  15928. stats: session.peerconnection.stats,
  15929. url: window.location.href
  15930. };
  15931. }
  15932. });
  15933. return data;
  15934. }
  15935. });
  15936. };
  15937. },{"../../service/xmpp/XMPPEvents":113,"../RTC/RTCBrowserType":8,"./JingleSession":53}],63:[function(require,module,exports){
  15938. /* global Strophe */
  15939. module.exports = function () {
  15940. Strophe.addConnectionPlugin('logger', {
  15941. // logs raw stanzas and makes them available for download as JSON
  15942. connection: null,
  15943. log: [],
  15944. init: function (conn) {
  15945. this.connection = conn;
  15946. this.connection.rawInput = this.log_incoming.bind(this);
  15947. this.connection.rawOutput = this.log_outgoing.bind(this);
  15948. },
  15949. log_incoming: function (stanza) {
  15950. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15951. },
  15952. log_outgoing: function (stanza) {
  15953. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15954. }
  15955. });
  15956. };
  15957. },{}],64:[function(require,module,exports){
  15958. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15959. setAudioMuted, Strophe */
  15960. /**
  15961. * Moderate connection plugin.
  15962. */
  15963. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15964. module.exports = function (XMPP, eventEmitter) {
  15965. Strophe.addConnectionPlugin('moderate', {
  15966. connection: null,
  15967. init: function (conn) {
  15968. this.connection = conn;
  15969. this.connection.addHandler(this.onMute.bind(this),
  15970. 'http://jitsi.org/jitmeet/audio',
  15971. 'iq',
  15972. 'set',
  15973. null,
  15974. null);
  15975. },
  15976. setMute: function (jid, mute) {
  15977. console.info("set mute", mute);
  15978. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15979. .c('mute', {
  15980. xmlns: 'http://jitsi.org/jitmeet/audio',
  15981. jid: jid
  15982. })
  15983. .t(mute.toString())
  15984. .up();
  15985. this.connection.sendIQ(
  15986. iqToFocus,
  15987. function (result) {
  15988. console.log('set mute', result);
  15989. },
  15990. function (error) {
  15991. console.log('set mute error', error);
  15992. });
  15993. },
  15994. onMute: function (iq) {
  15995. var from = iq.getAttribute('from');
  15996. if (from !== this.connection.emuc.focusMucJid) {
  15997. console.warn("Ignored mute from non focus peer");
  15998. return false;
  15999. }
  16000. var mute = $(iq).find('mute');
  16001. if (mute.length) {
  16002. var doMuteAudio = mute.text() === "true";
  16003. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16004. XMPP.forceMuted = doMuteAudio;
  16005. }
  16006. return true;
  16007. },
  16008. eject: function (jid) {
  16009. // We're not the focus, so can't terminate
  16010. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16011. this.connection.emuc.kick(jid);
  16012. }
  16013. });
  16014. }
  16015. },{"../../service/xmpp/XMPPEvents":113}],65:[function(require,module,exports){
  16016. /* jshint -W117 */
  16017. module.exports = function() {
  16018. Strophe.addConnectionPlugin('rayo',
  16019. {
  16020. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16021. connection: null,
  16022. init: function (conn) {
  16023. this.connection = conn;
  16024. if (this.connection.disco) {
  16025. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16026. }
  16027. this.connection.addHandler(
  16028. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16029. },
  16030. onRayo: function (iq) {
  16031. console.info("Rayo IQ", iq);
  16032. },
  16033. dial: function (to, from, roomName, roomPass) {
  16034. var self = this;
  16035. var req = $iq(
  16036. {
  16037. type: 'set',
  16038. to: this.connection.emuc.focusMucJid
  16039. }
  16040. );
  16041. req.c('dial',
  16042. {
  16043. xmlns: this.RAYO_XMLNS,
  16044. to: to,
  16045. from: from
  16046. });
  16047. req.c('header',
  16048. {
  16049. name: 'JvbRoomName',
  16050. value: roomName
  16051. }).up();
  16052. if (roomPass !== null && roomPass.length) {
  16053. req.c('header',
  16054. {
  16055. name: 'JvbRoomPassword',
  16056. value: roomPass
  16057. }).up();
  16058. }
  16059. this.connection.sendIQ(
  16060. req,
  16061. function (result) {
  16062. console.info('Dial result ', result);
  16063. var resource = $(result).find('ref').attr('uri');
  16064. this.call_resource = resource.substr('xmpp:'.length);
  16065. console.info(
  16066. "Received call resource: " + this.call_resource);
  16067. },
  16068. function (error) {
  16069. console.info('Dial error ', error);
  16070. }
  16071. );
  16072. },
  16073. hang_up: function () {
  16074. if (!this.call_resource) {
  16075. console.warn("No call in progress");
  16076. return;
  16077. }
  16078. var self = this;
  16079. var req = $iq(
  16080. {
  16081. type: 'set',
  16082. to: this.call_resource
  16083. }
  16084. );
  16085. req.c('hangup',
  16086. {
  16087. xmlns: this.RAYO_XMLNS
  16088. });
  16089. this.connection.sendIQ(
  16090. req,
  16091. function (result) {
  16092. console.info('Hangup result ', result);
  16093. self.call_resource = null;
  16094. },
  16095. function (error) {
  16096. console.info('Hangup error ', error);
  16097. self.call_resource = null;
  16098. }
  16099. );
  16100. }
  16101. }
  16102. );
  16103. };
  16104. },{}],66:[function(require,module,exports){
  16105. /**
  16106. * Strophe logger implementation. Logs from level WARN and above.
  16107. */
  16108. module.exports = function () {
  16109. Strophe.log = function (level, msg) {
  16110. switch (level) {
  16111. case Strophe.LogLevel.WARN:
  16112. console.warn("Strophe: " + msg);
  16113. break;
  16114. case Strophe.LogLevel.ERROR:
  16115. case Strophe.LogLevel.FATAL:
  16116. console.error("Strophe: " + msg);
  16117. break;
  16118. }
  16119. };
  16120. Strophe.getStatusString = function (status) {
  16121. switch (status) {
  16122. case Strophe.Status.ERROR:
  16123. return "ERROR";
  16124. case Strophe.Status.CONNECTING:
  16125. return "CONNECTING";
  16126. case Strophe.Status.CONNFAIL:
  16127. return "CONNFAIL";
  16128. case Strophe.Status.AUTHENTICATING:
  16129. return "AUTHENTICATING";
  16130. case Strophe.Status.AUTHFAIL:
  16131. return "AUTHFAIL";
  16132. case Strophe.Status.CONNECTED:
  16133. return "CONNECTED";
  16134. case Strophe.Status.DISCONNECTED:
  16135. return "DISCONNECTED";
  16136. case Strophe.Status.DISCONNECTING:
  16137. return "DISCONNECTING";
  16138. case Strophe.Status.ATTACHED:
  16139. return "ATTACHED";
  16140. default:
  16141. return "unknown";
  16142. }
  16143. };
  16144. };
  16145. },{}],67:[function(require,module,exports){
  16146. /* global $, APP, config, Strophe*/
  16147. var Moderator = require("./moderator");
  16148. var EventEmitter = require("events");
  16149. var Recording = require("./recording");
  16150. var SDP = require("./SDP");
  16151. var Settings = require("../settings/Settings");
  16152. var Pako = require("pako");
  16153. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16154. var RTCEvents = require("../../service/RTC/RTCEvents");
  16155. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16156. var retry = require('retry');
  16157. var eventEmitter = new EventEmitter();
  16158. var connection = null;
  16159. var authenticatedUser = false;
  16160. function connect(jid, password) {
  16161. var faultTolerantConnect = retry.operation({
  16162. retries: 3
  16163. });
  16164. // fault tolerant connect
  16165. faultTolerantConnect.attempt(function () {
  16166. connection = XMPP.createConnection();
  16167. Moderator.setConnection(connection);
  16168. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16169. if (config.useIPv6) {
  16170. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16171. if (!connection.jingle.pc_constraints.optional)
  16172. connection.jingle.pc_constraints.optional = [];
  16173. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16174. }
  16175. // Include user info in MUC presence
  16176. var settings = Settings.getSettings();
  16177. if (settings.email) {
  16178. connection.emuc.addEmailToPresence(settings.email);
  16179. }
  16180. if (settings.uid) {
  16181. connection.emuc.addUserIdToPresence(settings.uid);
  16182. }
  16183. if (settings.displayName) {
  16184. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16185. }
  16186. // connection.connect() starts the connection process.
  16187. //
  16188. // As the connection process proceeds, the user supplied callback will
  16189. // be triggered multiple times with status updates. The callback should
  16190. // take two arguments - the status code and the error condition.
  16191. //
  16192. // The status code will be one of the values in the Strophe.Status
  16193. // constants. The error condition will be one of the conditions defined
  16194. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16195. //
  16196. // The Parameters wait, hold and route are optional and only relevant
  16197. // for BOSH connections. Please see XEP 124 for a more detailed
  16198. // explanation of the optional parameters.
  16199. //
  16200. // Connection status constants for use by the connection handler
  16201. // callback.
  16202. //
  16203. // Status.ERROR - An error has occurred (websockets specific)
  16204. // Status.CONNECTING - The connection is currently being made
  16205. // Status.CONNFAIL - The connection attempt failed
  16206. // Status.AUTHENTICATING - The connection is authenticating
  16207. // Status.AUTHFAIL - The authentication attempt failed
  16208. // Status.CONNECTED - The connection has succeeded
  16209. // Status.DISCONNECTED - The connection has been terminated
  16210. // Status.DISCONNECTING - The connection is currently being terminated
  16211. // Status.ATTACHED - The connection has been attached
  16212. var anonymousConnectionFailed = false;
  16213. var connectionFailed = false;
  16214. var lastErrorMsg;
  16215. connection.connect(jid, password, function (status, msg) {
  16216. console.log('Strophe status changed to',
  16217. Strophe.getStatusString(status), msg);
  16218. if (status === Strophe.Status.CONNECTED) {
  16219. if (config.useStunTurn) {
  16220. connection.jingle.getStunAndTurnCredentials();
  16221. }
  16222. console.info("My Jabber ID: " + connection.jid);
  16223. if (password)
  16224. authenticatedUser = true;
  16225. maybeDoJoin();
  16226. } else if (status === Strophe.Status.CONNFAIL) {
  16227. if (msg === 'x-strophe-bad-non-anon-jid') {
  16228. anonymousConnectionFailed = true;
  16229. } else {
  16230. connectionFailed = true;
  16231. }
  16232. lastErrorMsg = msg;
  16233. } else if (status === Strophe.Status.DISCONNECTED) {
  16234. if (anonymousConnectionFailed) {
  16235. // prompt user for username and password
  16236. XMPP.promptLogin();
  16237. } else {
  16238. // Strophe already has built-in HTTP/BOSH error handling and
  16239. // request retry logic. Requests are resent automatically
  16240. // until their error count reaches 5. Strophe.js disconnects
  16241. // if the error count is > 5. We are not replicating this
  16242. // here.
  16243. //
  16244. // The "problem" is that failed HTTP/BOSH requests don't
  16245. // trigger a callback with a status update, so when a
  16246. // callback with status Strophe.Status.DISCONNECTED arrives,
  16247. // we can't be sure if it's a graceful disconnect or if it's
  16248. // triggered by some HTTP/BOSH error.
  16249. //
  16250. // But that's a minor issue in Jitsi Meet as we never
  16251. // disconnect anyway, not even when the user closes the
  16252. // browser window (which is kind of wrong, but the point is
  16253. // that we should never ever get disconnected).
  16254. //
  16255. // On the other hand, failed connections due to XMPP layer
  16256. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16257. //
  16258. // Here we implement retry logic for failed connections due
  16259. // to XMPP layer errors and we display an error to the user
  16260. // if we get disconnected from the XMPP server permanently.
  16261. // If the connection failed, retry.
  16262. if (connectionFailed &&
  16263. faultTolerantConnect.retry("connection-failed")) {
  16264. return;
  16265. }
  16266. // If we failed to connect to the XMPP server, fire an event
  16267. // to let all the interested module now about it.
  16268. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16269. msg ? msg : lastErrorMsg);
  16270. }
  16271. } else if (status === Strophe.Status.AUTHFAIL) {
  16272. // wrong password or username, prompt user
  16273. XMPP.promptLogin();
  16274. }
  16275. });
  16276. });
  16277. }
  16278. function maybeDoJoin() {
  16279. if (connection && connection.connected &&
  16280. Strophe.getResourceFromJid(connection.jid) &&
  16281. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16282. // .connected is true while connecting?
  16283. doJoin();
  16284. }
  16285. }
  16286. function doJoin() {
  16287. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16288. }
  16289. function initStrophePlugins()
  16290. {
  16291. require("./strophe.emuc")(XMPP, eventEmitter);
  16292. require("./strophe.jingle")(XMPP, eventEmitter);
  16293. require("./strophe.moderate")(XMPP, eventEmitter);
  16294. require("./strophe.util")();
  16295. require("./strophe.rayo")();
  16296. require("./strophe.logger")();
  16297. }
  16298. /**
  16299. * If given <tt>localStream</tt> is video one this method will advertise it's
  16300. * video type in MUC presence.
  16301. * @param localStream new or modified <tt>LocalStream</tt>.
  16302. */
  16303. function broadcastLocalVideoType(localStream) {
  16304. if (localStream.videoType)
  16305. XMPP.addToPresence('videoType', localStream.videoType);
  16306. }
  16307. function registerListeners() {
  16308. APP.RTC.addStreamListener(
  16309. function (localStream) {
  16310. maybeDoJoin();
  16311. broadcastLocalVideoType(localStream);
  16312. },
  16313. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16314. );
  16315. APP.RTC.addStreamListener(
  16316. broadcastLocalVideoType,
  16317. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16318. );
  16319. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16320. XMPP.addToPresence("devices", devices);
  16321. });
  16322. }
  16323. var unload = (function () {
  16324. var unloaded = false;
  16325. return function () {
  16326. if (unloaded) { return; }
  16327. unloaded = true;
  16328. if (connection && connection.connected) {
  16329. // ensure signout
  16330. $.ajax({
  16331. type: 'POST',
  16332. url: config.bosh,
  16333. async: false,
  16334. cache: false,
  16335. contentType: 'application/xml',
  16336. data: "<body rid='" +
  16337. (connection.rid || connection._proto.rid) +
  16338. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16339. (connection.sid || connection._proto.sid) +
  16340. "' type='terminate'>" +
  16341. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16342. "</body>",
  16343. success: function (data) {
  16344. console.log('signed out');
  16345. console.log(data);
  16346. },
  16347. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16348. console.log('signout error',
  16349. textStatus + ' (' + errorThrown + ')');
  16350. }
  16351. });
  16352. }
  16353. XMPP.disposeConference(true);
  16354. };
  16355. })();
  16356. function setupEvents() {
  16357. // In recent versions of FF the 'beforeunload' event is not fired when the
  16358. // window or the tab is closed. It is only fired when we leave the page
  16359. // (change URL). If this participant doesn't unload properly, then it
  16360. // becomes a ghost for the rest of the participants that stay in the
  16361. // conference. Thankfully handling the 'unload' event in addition to the
  16362. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16363. // method at least once.
  16364. //
  16365. // The 'unload' method can safely be run multiple times, it will actually do
  16366. // something only the first time that it's run, so we're don't have to worry
  16367. // about browsers that fire both events.
  16368. $(window).bind('beforeunload', unload);
  16369. $(window).bind('unload', unload);
  16370. }
  16371. var XMPP = {
  16372. getConnection: function(){ return connection; },
  16373. sessionTerminated: false,
  16374. /**
  16375. * XMPP connection status
  16376. */
  16377. Status: Strophe.Status,
  16378. /**
  16379. * Remembers if we were muted by the focus.
  16380. * @type {boolean}
  16381. */
  16382. forceMuted: false,
  16383. start: function () {
  16384. setupEvents();
  16385. initStrophePlugins();
  16386. registerListeners();
  16387. Moderator.init(this, eventEmitter);
  16388. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16389. // Force authenticated domain if room is appended with '?login=true'
  16390. if (config.hosts.anonymousdomain &&
  16391. window.location.search.indexOf("login=true") !== -1) {
  16392. configDomain = config.hosts.domain;
  16393. }
  16394. var jid = configDomain || window.location.hostname;
  16395. connect(jid, null);
  16396. },
  16397. createConnection: function () {
  16398. var bosh = config.bosh || '/http-bind';
  16399. return new Strophe.Connection(bosh);
  16400. },
  16401. getStatusString: function (status) {
  16402. return Strophe.getStatusString(status);
  16403. },
  16404. promptLogin: function () {
  16405. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16406. },
  16407. joinRoom: function(roomName, useNicks, nick) {
  16408. var roomjid = roomName;
  16409. if (useNicks) {
  16410. if (nick) {
  16411. roomjid += '/' + nick;
  16412. } else {
  16413. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16414. }
  16415. } else {
  16416. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16417. if(!authenticatedUser)
  16418. tmpJid = tmpJid.substr(0, 8);
  16419. roomjid += '/' + tmpJid;
  16420. }
  16421. connection.emuc.doJoin(roomjid);
  16422. },
  16423. myJid: function () {
  16424. if(!connection)
  16425. return null;
  16426. return connection.emuc.myroomjid;
  16427. },
  16428. myResource: function () {
  16429. if(!connection || ! connection.emuc.myroomjid)
  16430. return null;
  16431. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16432. },
  16433. disposeConference: function (onUnload) {
  16434. var handler = connection.jingle.activecall;
  16435. if (handler && handler.peerconnection) {
  16436. // FIXME: probably removing streams is not required and close() should
  16437. // be enough
  16438. if (APP.RTC.localAudio) {
  16439. handler.peerconnection.removeStream(
  16440. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16441. }
  16442. if (APP.RTC.localVideo) {
  16443. handler.peerconnection.removeStream(
  16444. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16445. }
  16446. handler.peerconnection.close();
  16447. }
  16448. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16449. connection.jingle.activecall = null;
  16450. if (!onUnload) {
  16451. this.sessionTerminated = true;
  16452. connection.emuc.doLeave();
  16453. }
  16454. },
  16455. addListener: function(type, listener) {
  16456. eventEmitter.on(type, listener);
  16457. },
  16458. removeListener: function (type, listener) {
  16459. eventEmitter.removeListener(type, listener);
  16460. },
  16461. allocateConferenceFocus: function(roomName, callback) {
  16462. Moderator.allocateConferenceFocus(roomName, callback);
  16463. },
  16464. getLoginUrl: function (roomName, callback) {
  16465. Moderator.getLoginUrl(roomName, callback);
  16466. },
  16467. getPopupLoginUrl: function (roomName, callback) {
  16468. Moderator.getPopupLoginUrl(roomName, callback);
  16469. },
  16470. isModerator: function () {
  16471. return Moderator.isModerator();
  16472. },
  16473. isSipGatewayEnabled: function () {
  16474. return Moderator.isSipGatewayEnabled();
  16475. },
  16476. isExternalAuthEnabled: function () {
  16477. return Moderator.isExternalAuthEnabled();
  16478. },
  16479. isConferenceInProgress: function () {
  16480. return connection && connection.jingle.activecall &&
  16481. connection.jingle.activecall.peerconnection;
  16482. },
  16483. switchStreams: function (stream, oldStream, callback, isAudio) {
  16484. if (this.isConferenceInProgress()) {
  16485. // FIXME: will block switchInProgress on true value in case of exception
  16486. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16487. } else {
  16488. // We are done immediately
  16489. console.warn("No conference handler or conference not started yet");
  16490. callback();
  16491. }
  16492. },
  16493. sendVideoInfoPresence: function (mute) {
  16494. if(!connection)
  16495. return;
  16496. connection.emuc.addVideoInfoToPresence(mute);
  16497. connection.emuc.sendPresence();
  16498. },
  16499. setVideoMute: function (mute, callback, options) {
  16500. if(!connection)
  16501. return;
  16502. var self = this;
  16503. var localCallback = function (mute) {
  16504. self.sendVideoInfoPresence(mute);
  16505. return callback(mute);
  16506. };
  16507. if(connection.jingle.activecall)
  16508. {
  16509. connection.jingle.activecall.setVideoMute(
  16510. mute, localCallback, options);
  16511. }
  16512. else {
  16513. localCallback(mute);
  16514. }
  16515. },
  16516. setAudioMute: function (mute, callback) {
  16517. if (!(connection && APP.RTC.localAudio)) {
  16518. return false;
  16519. }
  16520. if (this.forceMuted && !mute) {
  16521. console.info("Asking focus for unmute");
  16522. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16523. // FIXME: wait for result before resetting muted status
  16524. this.forceMuted = false;
  16525. }
  16526. if (mute == APP.RTC.localAudio.isMuted()) {
  16527. // Nothing to do
  16528. return true;
  16529. }
  16530. APP.RTC.localAudio.setMute(mute);
  16531. this.sendAudioInfoPresence(mute, callback);
  16532. return true;
  16533. },
  16534. sendAudioInfoPresence: function(mute, callback) {
  16535. if(connection) {
  16536. connection.emuc.addAudioInfoToPresence(mute);
  16537. connection.emuc.sendPresence();
  16538. }
  16539. callback();
  16540. return true;
  16541. },
  16542. toggleRecording: function (tokenEmptyCallback,
  16543. recordingStateChangeCallback) {
  16544. Recording.toggleRecording(tokenEmptyCallback,
  16545. recordingStateChangeCallback, connection);
  16546. },
  16547. addToPresence: function (name, value, dontSend) {
  16548. switch (name) {
  16549. case "displayName":
  16550. connection.emuc.addDisplayNameToPresence(value);
  16551. break;
  16552. case "prezi":
  16553. connection.emuc.addPreziToPresence(value, 0);
  16554. break;
  16555. case "preziSlide":
  16556. connection.emuc.addCurrentSlideToPresence(value);
  16557. break;
  16558. case "connectionQuality":
  16559. connection.emuc.addConnectionInfoToPresence(value);
  16560. break;
  16561. case "email":
  16562. connection.emuc.addEmailToPresence(value);
  16563. break;
  16564. case "devices":
  16565. connection.emuc.addDevicesToPresence(value);
  16566. break;
  16567. case "videoType":
  16568. connection.emuc.addVideoTypeToPresence(value);
  16569. break;
  16570. case "startMuted":
  16571. if(!Moderator.isModerator())
  16572. return;
  16573. connection.emuc.addStartMutedToPresence(value[0],
  16574. value[1]);
  16575. break;
  16576. default :
  16577. console.log("Unknown tag for presence: " + name);
  16578. return;
  16579. }
  16580. if (!dontSend)
  16581. connection.emuc.sendPresence();
  16582. },
  16583. /**
  16584. * Sends 'data' as a log message to the focus. Returns true iff a message
  16585. * was sent.
  16586. * @param data
  16587. * @returns {boolean} true iff a message was sent.
  16588. */
  16589. sendLogs: function (data) {
  16590. if(!connection.emuc.focusMucJid)
  16591. return false;
  16592. var deflate = true;
  16593. var content = JSON.stringify(data);
  16594. if (deflate) {
  16595. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16596. }
  16597. content = Base64.encode(content);
  16598. // XEP-0337-ish
  16599. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16600. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16601. id: 'PeerConnectionStats'});
  16602. message.c('message').t(content).up();
  16603. if (deflate) {
  16604. message.c('tag', {name: "deflated", value: "true"}).up();
  16605. }
  16606. message.up();
  16607. connection.send(message);
  16608. return true;
  16609. },
  16610. // Gets the logs from strophe.jingle.
  16611. getJingleLog: function () {
  16612. return connection.jingle ? connection.jingle.getLog() : {};
  16613. },
  16614. // Gets the logs from strophe.
  16615. getXmppLog: function () {
  16616. return connection.logger ? connection.logger.log : null;
  16617. },
  16618. getPrezi: function () {
  16619. return connection.emuc.getPrezi(this.myJid());
  16620. },
  16621. removePreziFromPresence: function () {
  16622. connection.emuc.removePreziFromPresence();
  16623. connection.emuc.sendPresence();
  16624. },
  16625. sendChatMessage: function (message, nickname) {
  16626. connection.emuc.sendMessage(message, nickname);
  16627. },
  16628. setSubject: function (topic) {
  16629. connection.emuc.setSubject(topic);
  16630. },
  16631. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16632. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16633. },
  16634. dial: function (to, from, roomName,roomPass) {
  16635. connection.rayo.dial(to, from, roomName,roomPass);
  16636. },
  16637. setMute: function (jid, mute) {
  16638. connection.moderate.setMute(jid, mute);
  16639. },
  16640. eject: function (jid) {
  16641. connection.moderate.eject(jid);
  16642. },
  16643. logout: function (callback) {
  16644. Moderator.logout(callback);
  16645. },
  16646. findJidFromResource: function (resource) {
  16647. return connection.emuc.findJidFromResource(resource);
  16648. },
  16649. getMembers: function () {
  16650. return connection.emuc.members;
  16651. },
  16652. getJidFromSSRC: function (ssrc) {
  16653. if (!this.isConferenceInProgress())
  16654. return null;
  16655. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16656. },
  16657. // Returns true iff we have joined the MUC.
  16658. isMUCJoined: function () {
  16659. return connection.emuc.joined;
  16660. },
  16661. getSessions: function () {
  16662. return connection.jingle.sessions;
  16663. },
  16664. removeStream: function (stream) {
  16665. if (!this.isConferenceInProgress())
  16666. return;
  16667. connection.jingle.activecall.peerconnection.removeStream(stream);
  16668. }
  16669. };
  16670. module.exports = XMPP;
  16671. },{"../../service/RTC/RTCEvents":104,"../../service/RTC/StreamEventTypes":106,"../../service/xmpp/XMPPEvents":113,"../settings/Settings":47,"./SDP":54,"./moderator":59,"./recording":60,"./strophe.emuc":61,"./strophe.jingle":62,"./strophe.logger":63,"./strophe.moderate":64,"./strophe.rayo":65,"./strophe.util":66,"events":114,"pako":70,"retry":86}],68:[function(require,module,exports){
  16672. (function (process){
  16673. /*!
  16674. * async
  16675. * https://github.com/caolan/async
  16676. *
  16677. * Copyright 2010-2014 Caolan McMahon
  16678. * Released under the MIT license
  16679. */
  16680. /*jshint onevar: false, indent:4 */
  16681. /*global setImmediate: false, setTimeout: false, console: false */
  16682. (function () {
  16683. var async = {};
  16684. // global on the server, window in the browser
  16685. var root, previous_async;
  16686. root = this;
  16687. if (root != null) {
  16688. previous_async = root.async;
  16689. }
  16690. async.noConflict = function () {
  16691. root.async = previous_async;
  16692. return async;
  16693. };
  16694. function only_once(fn) {
  16695. var called = false;
  16696. return function() {
  16697. if (called) throw new Error("Callback was already called.");
  16698. called = true;
  16699. fn.apply(root, arguments);
  16700. }
  16701. }
  16702. //// cross-browser compatiblity functions ////
  16703. var _toString = Object.prototype.toString;
  16704. var _isArray = Array.isArray || function (obj) {
  16705. return _toString.call(obj) === '[object Array]';
  16706. };
  16707. var _each = function (arr, iterator) {
  16708. if (arr.forEach) {
  16709. return arr.forEach(iterator);
  16710. }
  16711. for (var i = 0; i < arr.length; i += 1) {
  16712. iterator(arr[i], i, arr);
  16713. }
  16714. };
  16715. var _map = function (arr, iterator) {
  16716. if (arr.map) {
  16717. return arr.map(iterator);
  16718. }
  16719. var results = [];
  16720. _each(arr, function (x, i, a) {
  16721. results.push(iterator(x, i, a));
  16722. });
  16723. return results;
  16724. };
  16725. var _reduce = function (arr, iterator, memo) {
  16726. if (arr.reduce) {
  16727. return arr.reduce(iterator, memo);
  16728. }
  16729. _each(arr, function (x, i, a) {
  16730. memo = iterator(memo, x, i, a);
  16731. });
  16732. return memo;
  16733. };
  16734. var _keys = function (obj) {
  16735. if (Object.keys) {
  16736. return Object.keys(obj);
  16737. }
  16738. var keys = [];
  16739. for (var k in obj) {
  16740. if (obj.hasOwnProperty(k)) {
  16741. keys.push(k);
  16742. }
  16743. }
  16744. return keys;
  16745. };
  16746. //// exported async module functions ////
  16747. //// nextTick implementation with browser-compatible fallback ////
  16748. if (typeof process === 'undefined' || !(process.nextTick)) {
  16749. if (typeof setImmediate === 'function') {
  16750. async.nextTick = function (fn) {
  16751. // not a direct alias for IE10 compatibility
  16752. setImmediate(fn);
  16753. };
  16754. async.setImmediate = async.nextTick;
  16755. }
  16756. else {
  16757. async.nextTick = function (fn) {
  16758. setTimeout(fn, 0);
  16759. };
  16760. async.setImmediate = async.nextTick;
  16761. }
  16762. }
  16763. else {
  16764. async.nextTick = process.nextTick;
  16765. if (typeof setImmediate !== 'undefined') {
  16766. async.setImmediate = function (fn) {
  16767. // not a direct alias for IE10 compatibility
  16768. setImmediate(fn);
  16769. };
  16770. }
  16771. else {
  16772. async.setImmediate = async.nextTick;
  16773. }
  16774. }
  16775. async.each = function (arr, iterator, callback) {
  16776. callback = callback || function () {};
  16777. if (!arr.length) {
  16778. return callback();
  16779. }
  16780. var completed = 0;
  16781. _each(arr, function (x) {
  16782. iterator(x, only_once(done) );
  16783. });
  16784. function done(err) {
  16785. if (err) {
  16786. callback(err);
  16787. callback = function () {};
  16788. }
  16789. else {
  16790. completed += 1;
  16791. if (completed >= arr.length) {
  16792. callback();
  16793. }
  16794. }
  16795. }
  16796. };
  16797. async.forEach = async.each;
  16798. async.eachSeries = function (arr, iterator, callback) {
  16799. callback = callback || function () {};
  16800. if (!arr.length) {
  16801. return callback();
  16802. }
  16803. var completed = 0;
  16804. var iterate = function () {
  16805. iterator(arr[completed], function (err) {
  16806. if (err) {
  16807. callback(err);
  16808. callback = function () {};
  16809. }
  16810. else {
  16811. completed += 1;
  16812. if (completed >= arr.length) {
  16813. callback();
  16814. }
  16815. else {
  16816. iterate();
  16817. }
  16818. }
  16819. });
  16820. };
  16821. iterate();
  16822. };
  16823. async.forEachSeries = async.eachSeries;
  16824. async.eachLimit = function (arr, limit, iterator, callback) {
  16825. var fn = _eachLimit(limit);
  16826. fn.apply(null, [arr, iterator, callback]);
  16827. };
  16828. async.forEachLimit = async.eachLimit;
  16829. var _eachLimit = function (limit) {
  16830. return function (arr, iterator, callback) {
  16831. callback = callback || function () {};
  16832. if (!arr.length || limit <= 0) {
  16833. return callback();
  16834. }
  16835. var completed = 0;
  16836. var started = 0;
  16837. var running = 0;
  16838. (function replenish () {
  16839. if (completed >= arr.length) {
  16840. return callback();
  16841. }
  16842. while (running < limit && started < arr.length) {
  16843. started += 1;
  16844. running += 1;
  16845. iterator(arr[started - 1], function (err) {
  16846. if (err) {
  16847. callback(err);
  16848. callback = function () {};
  16849. }
  16850. else {
  16851. completed += 1;
  16852. running -= 1;
  16853. if (completed >= arr.length) {
  16854. callback();
  16855. }
  16856. else {
  16857. replenish();
  16858. }
  16859. }
  16860. });
  16861. }
  16862. })();
  16863. };
  16864. };
  16865. var doParallel = function (fn) {
  16866. return function () {
  16867. var args = Array.prototype.slice.call(arguments);
  16868. return fn.apply(null, [async.each].concat(args));
  16869. };
  16870. };
  16871. var doParallelLimit = function(limit, fn) {
  16872. return function () {
  16873. var args = Array.prototype.slice.call(arguments);
  16874. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16875. };
  16876. };
  16877. var doSeries = function (fn) {
  16878. return function () {
  16879. var args = Array.prototype.slice.call(arguments);
  16880. return fn.apply(null, [async.eachSeries].concat(args));
  16881. };
  16882. };
  16883. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16884. arr = _map(arr, function (x, i) {
  16885. return {index: i, value: x};
  16886. });
  16887. if (!callback) {
  16888. eachfn(arr, function (x, callback) {
  16889. iterator(x.value, function (err) {
  16890. callback(err);
  16891. });
  16892. });
  16893. } else {
  16894. var results = [];
  16895. eachfn(arr, function (x, callback) {
  16896. iterator(x.value, function (err, v) {
  16897. results[x.index] = v;
  16898. callback(err);
  16899. });
  16900. }, function (err) {
  16901. callback(err, results);
  16902. });
  16903. }
  16904. };
  16905. async.map = doParallel(_asyncMap);
  16906. async.mapSeries = doSeries(_asyncMap);
  16907. async.mapLimit = function (arr, limit, iterator, callback) {
  16908. return _mapLimit(limit)(arr, iterator, callback);
  16909. };
  16910. var _mapLimit = function(limit) {
  16911. return doParallelLimit(limit, _asyncMap);
  16912. };
  16913. // reduce only has a series version, as doing reduce in parallel won't
  16914. // work in many situations.
  16915. async.reduce = function (arr, memo, iterator, callback) {
  16916. async.eachSeries(arr, function (x, callback) {
  16917. iterator(memo, x, function (err, v) {
  16918. memo = v;
  16919. callback(err);
  16920. });
  16921. }, function (err) {
  16922. callback(err, memo);
  16923. });
  16924. };
  16925. // inject alias
  16926. async.inject = async.reduce;
  16927. // foldl alias
  16928. async.foldl = async.reduce;
  16929. async.reduceRight = function (arr, memo, iterator, callback) {
  16930. var reversed = _map(arr, function (x) {
  16931. return x;
  16932. }).reverse();
  16933. async.reduce(reversed, memo, iterator, callback);
  16934. };
  16935. // foldr alias
  16936. async.foldr = async.reduceRight;
  16937. var _filter = function (eachfn, arr, iterator, callback) {
  16938. var results = [];
  16939. arr = _map(arr, function (x, i) {
  16940. return {index: i, value: x};
  16941. });
  16942. eachfn(arr, function (x, callback) {
  16943. iterator(x.value, function (v) {
  16944. if (v) {
  16945. results.push(x);
  16946. }
  16947. callback();
  16948. });
  16949. }, function (err) {
  16950. callback(_map(results.sort(function (a, b) {
  16951. return a.index - b.index;
  16952. }), function (x) {
  16953. return x.value;
  16954. }));
  16955. });
  16956. };
  16957. async.filter = doParallel(_filter);
  16958. async.filterSeries = doSeries(_filter);
  16959. // select alias
  16960. async.select = async.filter;
  16961. async.selectSeries = async.filterSeries;
  16962. var _reject = function (eachfn, arr, iterator, callback) {
  16963. var results = [];
  16964. arr = _map(arr, function (x, i) {
  16965. return {index: i, value: x};
  16966. });
  16967. eachfn(arr, function (x, callback) {
  16968. iterator(x.value, function (v) {
  16969. if (!v) {
  16970. results.push(x);
  16971. }
  16972. callback();
  16973. });
  16974. }, function (err) {
  16975. callback(_map(results.sort(function (a, b) {
  16976. return a.index - b.index;
  16977. }), function (x) {
  16978. return x.value;
  16979. }));
  16980. });
  16981. };
  16982. async.reject = doParallel(_reject);
  16983. async.rejectSeries = doSeries(_reject);
  16984. var _detect = function (eachfn, arr, iterator, main_callback) {
  16985. eachfn(arr, function (x, callback) {
  16986. iterator(x, function (result) {
  16987. if (result) {
  16988. main_callback(x);
  16989. main_callback = function () {};
  16990. }
  16991. else {
  16992. callback();
  16993. }
  16994. });
  16995. }, function (err) {
  16996. main_callback();
  16997. });
  16998. };
  16999. async.detect = doParallel(_detect);
  17000. async.detectSeries = doSeries(_detect);
  17001. async.some = function (arr, iterator, main_callback) {
  17002. async.each(arr, function (x, callback) {
  17003. iterator(x, function (v) {
  17004. if (v) {
  17005. main_callback(true);
  17006. main_callback = function () {};
  17007. }
  17008. callback();
  17009. });
  17010. }, function (err) {
  17011. main_callback(false);
  17012. });
  17013. };
  17014. // any alias
  17015. async.any = async.some;
  17016. async.every = function (arr, iterator, main_callback) {
  17017. async.each(arr, function (x, callback) {
  17018. iterator(x, function (v) {
  17019. if (!v) {
  17020. main_callback(false);
  17021. main_callback = function () {};
  17022. }
  17023. callback();
  17024. });
  17025. }, function (err) {
  17026. main_callback(true);
  17027. });
  17028. };
  17029. // all alias
  17030. async.all = async.every;
  17031. async.sortBy = function (arr, iterator, callback) {
  17032. async.map(arr, function (x, callback) {
  17033. iterator(x, function (err, criteria) {
  17034. if (err) {
  17035. callback(err);
  17036. }
  17037. else {
  17038. callback(null, {value: x, criteria: criteria});
  17039. }
  17040. });
  17041. }, function (err, results) {
  17042. if (err) {
  17043. return callback(err);
  17044. }
  17045. else {
  17046. var fn = function (left, right) {
  17047. var a = left.criteria, b = right.criteria;
  17048. return a < b ? -1 : a > b ? 1 : 0;
  17049. };
  17050. callback(null, _map(results.sort(fn), function (x) {
  17051. return x.value;
  17052. }));
  17053. }
  17054. });
  17055. };
  17056. async.auto = function (tasks, callback) {
  17057. callback = callback || function () {};
  17058. var keys = _keys(tasks);
  17059. var remainingTasks = keys.length
  17060. if (!remainingTasks) {
  17061. return callback();
  17062. }
  17063. var results = {};
  17064. var listeners = [];
  17065. var addListener = function (fn) {
  17066. listeners.unshift(fn);
  17067. };
  17068. var removeListener = function (fn) {
  17069. for (var i = 0; i < listeners.length; i += 1) {
  17070. if (listeners[i] === fn) {
  17071. listeners.splice(i, 1);
  17072. return;
  17073. }
  17074. }
  17075. };
  17076. var taskComplete = function () {
  17077. remainingTasks--
  17078. _each(listeners.slice(0), function (fn) {
  17079. fn();
  17080. });
  17081. };
  17082. addListener(function () {
  17083. if (!remainingTasks) {
  17084. var theCallback = callback;
  17085. // prevent final callback from calling itself if it errors
  17086. callback = function () {};
  17087. theCallback(null, results);
  17088. }
  17089. });
  17090. _each(keys, function (k) {
  17091. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17092. var taskCallback = function (err) {
  17093. var args = Array.prototype.slice.call(arguments, 1);
  17094. if (args.length <= 1) {
  17095. args = args[0];
  17096. }
  17097. if (err) {
  17098. var safeResults = {};
  17099. _each(_keys(results), function(rkey) {
  17100. safeResults[rkey] = results[rkey];
  17101. });
  17102. safeResults[k] = args;
  17103. callback(err, safeResults);
  17104. // stop subsequent errors hitting callback multiple times
  17105. callback = function () {};
  17106. }
  17107. else {
  17108. results[k] = args;
  17109. async.setImmediate(taskComplete);
  17110. }
  17111. };
  17112. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17113. var ready = function () {
  17114. return _reduce(requires, function (a, x) {
  17115. return (a && results.hasOwnProperty(x));
  17116. }, true) && !results.hasOwnProperty(k);
  17117. };
  17118. if (ready()) {
  17119. task[task.length - 1](taskCallback, results);
  17120. }
  17121. else {
  17122. var listener = function () {
  17123. if (ready()) {
  17124. removeListener(listener);
  17125. task[task.length - 1](taskCallback, results);
  17126. }
  17127. };
  17128. addListener(listener);
  17129. }
  17130. });
  17131. };
  17132. async.retry = function(times, task, callback) {
  17133. var DEFAULT_TIMES = 5;
  17134. var attempts = [];
  17135. // Use defaults if times not passed
  17136. if (typeof times === 'function') {
  17137. callback = task;
  17138. task = times;
  17139. times = DEFAULT_TIMES;
  17140. }
  17141. // Make sure times is a number
  17142. times = parseInt(times, 10) || DEFAULT_TIMES;
  17143. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17144. var retryAttempt = function(task, finalAttempt) {
  17145. return function(seriesCallback) {
  17146. task(function(err, result){
  17147. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17148. }, wrappedResults);
  17149. };
  17150. };
  17151. while (times) {
  17152. attempts.push(retryAttempt(task, !(times-=1)));
  17153. }
  17154. async.series(attempts, function(done, data){
  17155. data = data[data.length - 1];
  17156. (wrappedCallback || callback)(data.err, data.result);
  17157. });
  17158. }
  17159. // If a callback is passed, run this as a controll flow
  17160. return callback ? wrappedTask() : wrappedTask
  17161. };
  17162. async.waterfall = function (tasks, callback) {
  17163. callback = callback || function () {};
  17164. if (!_isArray(tasks)) {
  17165. var err = new Error('First argument to waterfall must be an array of functions');
  17166. return callback(err);
  17167. }
  17168. if (!tasks.length) {
  17169. return callback();
  17170. }
  17171. var wrapIterator = function (iterator) {
  17172. return function (err) {
  17173. if (err) {
  17174. callback.apply(null, arguments);
  17175. callback = function () {};
  17176. }
  17177. else {
  17178. var args = Array.prototype.slice.call(arguments, 1);
  17179. var next = iterator.next();
  17180. if (next) {
  17181. args.push(wrapIterator(next));
  17182. }
  17183. else {
  17184. args.push(callback);
  17185. }
  17186. async.setImmediate(function () {
  17187. iterator.apply(null, args);
  17188. });
  17189. }
  17190. };
  17191. };
  17192. wrapIterator(async.iterator(tasks))();
  17193. };
  17194. var _parallel = function(eachfn, tasks, callback) {
  17195. callback = callback || function () {};
  17196. if (_isArray(tasks)) {
  17197. eachfn.map(tasks, function (fn, callback) {
  17198. if (fn) {
  17199. fn(function (err) {
  17200. var args = Array.prototype.slice.call(arguments, 1);
  17201. if (args.length <= 1) {
  17202. args = args[0];
  17203. }
  17204. callback.call(null, err, args);
  17205. });
  17206. }
  17207. }, callback);
  17208. }
  17209. else {
  17210. var results = {};
  17211. eachfn.each(_keys(tasks), function (k, callback) {
  17212. tasks[k](function (err) {
  17213. var args = Array.prototype.slice.call(arguments, 1);
  17214. if (args.length <= 1) {
  17215. args = args[0];
  17216. }
  17217. results[k] = args;
  17218. callback(err);
  17219. });
  17220. }, function (err) {
  17221. callback(err, results);
  17222. });
  17223. }
  17224. };
  17225. async.parallel = function (tasks, callback) {
  17226. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17227. };
  17228. async.parallelLimit = function(tasks, limit, callback) {
  17229. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17230. };
  17231. async.series = function (tasks, callback) {
  17232. callback = callback || function () {};
  17233. if (_isArray(tasks)) {
  17234. async.mapSeries(tasks, function (fn, callback) {
  17235. if (fn) {
  17236. fn(function (err) {
  17237. var args = Array.prototype.slice.call(arguments, 1);
  17238. if (args.length <= 1) {
  17239. args = args[0];
  17240. }
  17241. callback.call(null, err, args);
  17242. });
  17243. }
  17244. }, callback);
  17245. }
  17246. else {
  17247. var results = {};
  17248. async.eachSeries(_keys(tasks), function (k, callback) {
  17249. tasks[k](function (err) {
  17250. var args = Array.prototype.slice.call(arguments, 1);
  17251. if (args.length <= 1) {
  17252. args = args[0];
  17253. }
  17254. results[k] = args;
  17255. callback(err);
  17256. });
  17257. }, function (err) {
  17258. callback(err, results);
  17259. });
  17260. }
  17261. };
  17262. async.iterator = function (tasks) {
  17263. var makeCallback = function (index) {
  17264. var fn = function () {
  17265. if (tasks.length) {
  17266. tasks[index].apply(null, arguments);
  17267. }
  17268. return fn.next();
  17269. };
  17270. fn.next = function () {
  17271. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17272. };
  17273. return fn;
  17274. };
  17275. return makeCallback(0);
  17276. };
  17277. async.apply = function (fn) {
  17278. var args = Array.prototype.slice.call(arguments, 1);
  17279. return function () {
  17280. return fn.apply(
  17281. null, args.concat(Array.prototype.slice.call(arguments))
  17282. );
  17283. };
  17284. };
  17285. var _concat = function (eachfn, arr, fn, callback) {
  17286. var r = [];
  17287. eachfn(arr, function (x, cb) {
  17288. fn(x, function (err, y) {
  17289. r = r.concat(y || []);
  17290. cb(err);
  17291. });
  17292. }, function (err) {
  17293. callback(err, r);
  17294. });
  17295. };
  17296. async.concat = doParallel(_concat);
  17297. async.concatSeries = doSeries(_concat);
  17298. async.whilst = function (test, iterator, callback) {
  17299. if (test()) {
  17300. iterator(function (err) {
  17301. if (err) {
  17302. return callback(err);
  17303. }
  17304. async.whilst(test, iterator, callback);
  17305. });
  17306. }
  17307. else {
  17308. callback();
  17309. }
  17310. };
  17311. async.doWhilst = function (iterator, test, callback) {
  17312. iterator(function (err) {
  17313. if (err) {
  17314. return callback(err);
  17315. }
  17316. var args = Array.prototype.slice.call(arguments, 1);
  17317. if (test.apply(null, args)) {
  17318. async.doWhilst(iterator, test, callback);
  17319. }
  17320. else {
  17321. callback();
  17322. }
  17323. });
  17324. };
  17325. async.until = function (test, iterator, callback) {
  17326. if (!test()) {
  17327. iterator(function (err) {
  17328. if (err) {
  17329. return callback(err);
  17330. }
  17331. async.until(test, iterator, callback);
  17332. });
  17333. }
  17334. else {
  17335. callback();
  17336. }
  17337. };
  17338. async.doUntil = function (iterator, test, callback) {
  17339. iterator(function (err) {
  17340. if (err) {
  17341. return callback(err);
  17342. }
  17343. var args = Array.prototype.slice.call(arguments, 1);
  17344. if (!test.apply(null, args)) {
  17345. async.doUntil(iterator, test, callback);
  17346. }
  17347. else {
  17348. callback();
  17349. }
  17350. });
  17351. };
  17352. async.queue = function (worker, concurrency) {
  17353. if (concurrency === undefined) {
  17354. concurrency = 1;
  17355. }
  17356. function _insert(q, data, pos, callback) {
  17357. if (!q.started){
  17358. q.started = true;
  17359. }
  17360. if (!_isArray(data)) {
  17361. data = [data];
  17362. }
  17363. if(data.length == 0) {
  17364. // call drain immediately if there are no tasks
  17365. return async.setImmediate(function() {
  17366. if (q.drain) {
  17367. q.drain();
  17368. }
  17369. });
  17370. }
  17371. _each(data, function(task) {
  17372. var item = {
  17373. data: task,
  17374. callback: typeof callback === 'function' ? callback : null
  17375. };
  17376. if (pos) {
  17377. q.tasks.unshift(item);
  17378. } else {
  17379. q.tasks.push(item);
  17380. }
  17381. if (q.saturated && q.tasks.length === q.concurrency) {
  17382. q.saturated();
  17383. }
  17384. async.setImmediate(q.process);
  17385. });
  17386. }
  17387. var workers = 0;
  17388. var q = {
  17389. tasks: [],
  17390. concurrency: concurrency,
  17391. saturated: null,
  17392. empty: null,
  17393. drain: null,
  17394. started: false,
  17395. paused: false,
  17396. push: function (data, callback) {
  17397. _insert(q, data, false, callback);
  17398. },
  17399. kill: function () {
  17400. q.drain = null;
  17401. q.tasks = [];
  17402. },
  17403. unshift: function (data, callback) {
  17404. _insert(q, data, true, callback);
  17405. },
  17406. process: function () {
  17407. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17408. var task = q.tasks.shift();
  17409. if (q.empty && q.tasks.length === 0) {
  17410. q.empty();
  17411. }
  17412. workers += 1;
  17413. var next = function () {
  17414. workers -= 1;
  17415. if (task.callback) {
  17416. task.callback.apply(task, arguments);
  17417. }
  17418. if (q.drain && q.tasks.length + workers === 0) {
  17419. q.drain();
  17420. }
  17421. q.process();
  17422. };
  17423. var cb = only_once(next);
  17424. worker(task.data, cb);
  17425. }
  17426. },
  17427. length: function () {
  17428. return q.tasks.length;
  17429. },
  17430. running: function () {
  17431. return workers;
  17432. },
  17433. idle: function() {
  17434. return q.tasks.length + workers === 0;
  17435. },
  17436. pause: function () {
  17437. if (q.paused === true) { return; }
  17438. q.paused = true;
  17439. q.process();
  17440. },
  17441. resume: function () {
  17442. if (q.paused === false) { return; }
  17443. q.paused = false;
  17444. q.process();
  17445. }
  17446. };
  17447. return q;
  17448. };
  17449. async.priorityQueue = function (worker, concurrency) {
  17450. function _compareTasks(a, b){
  17451. return a.priority - b.priority;
  17452. };
  17453. function _binarySearch(sequence, item, compare) {
  17454. var beg = -1,
  17455. end = sequence.length - 1;
  17456. while (beg < end) {
  17457. var mid = beg + ((end - beg + 1) >>> 1);
  17458. if (compare(item, sequence[mid]) >= 0) {
  17459. beg = mid;
  17460. } else {
  17461. end = mid - 1;
  17462. }
  17463. }
  17464. return beg;
  17465. }
  17466. function _insert(q, data, priority, callback) {
  17467. if (!q.started){
  17468. q.started = true;
  17469. }
  17470. if (!_isArray(data)) {
  17471. data = [data];
  17472. }
  17473. if(data.length == 0) {
  17474. // call drain immediately if there are no tasks
  17475. return async.setImmediate(function() {
  17476. if (q.drain) {
  17477. q.drain();
  17478. }
  17479. });
  17480. }
  17481. _each(data, function(task) {
  17482. var item = {
  17483. data: task,
  17484. priority: priority,
  17485. callback: typeof callback === 'function' ? callback : null
  17486. };
  17487. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17488. if (q.saturated && q.tasks.length === q.concurrency) {
  17489. q.saturated();
  17490. }
  17491. async.setImmediate(q.process);
  17492. });
  17493. }
  17494. // Start with a normal queue
  17495. var q = async.queue(worker, concurrency);
  17496. // Override push to accept second parameter representing priority
  17497. q.push = function (data, priority, callback) {
  17498. _insert(q, data, priority, callback);
  17499. };
  17500. // Remove unshift function
  17501. delete q.unshift;
  17502. return q;
  17503. };
  17504. async.cargo = function (worker, payload) {
  17505. var working = false,
  17506. tasks = [];
  17507. var cargo = {
  17508. tasks: tasks,
  17509. payload: payload,
  17510. saturated: null,
  17511. empty: null,
  17512. drain: null,
  17513. drained: true,
  17514. push: function (data, callback) {
  17515. if (!_isArray(data)) {
  17516. data = [data];
  17517. }
  17518. _each(data, function(task) {
  17519. tasks.push({
  17520. data: task,
  17521. callback: typeof callback === 'function' ? callback : null
  17522. });
  17523. cargo.drained = false;
  17524. if (cargo.saturated && tasks.length === payload) {
  17525. cargo.saturated();
  17526. }
  17527. });
  17528. async.setImmediate(cargo.process);
  17529. },
  17530. process: function process() {
  17531. if (working) return;
  17532. if (tasks.length === 0) {
  17533. if(cargo.drain && !cargo.drained) cargo.drain();
  17534. cargo.drained = true;
  17535. return;
  17536. }
  17537. var ts = typeof payload === 'number'
  17538. ? tasks.splice(0, payload)
  17539. : tasks.splice(0, tasks.length);
  17540. var ds = _map(ts, function (task) {
  17541. return task.data;
  17542. });
  17543. if(cargo.empty) cargo.empty();
  17544. working = true;
  17545. worker(ds, function () {
  17546. working = false;
  17547. var args = arguments;
  17548. _each(ts, function (data) {
  17549. if (data.callback) {
  17550. data.callback.apply(null, args);
  17551. }
  17552. });
  17553. process();
  17554. });
  17555. },
  17556. length: function () {
  17557. return tasks.length;
  17558. },
  17559. running: function () {
  17560. return working;
  17561. }
  17562. };
  17563. return cargo;
  17564. };
  17565. var _console_fn = function (name) {
  17566. return function (fn) {
  17567. var args = Array.prototype.slice.call(arguments, 1);
  17568. fn.apply(null, args.concat([function (err) {
  17569. var args = Array.prototype.slice.call(arguments, 1);
  17570. if (typeof console !== 'undefined') {
  17571. if (err) {
  17572. if (console.error) {
  17573. console.error(err);
  17574. }
  17575. }
  17576. else if (console[name]) {
  17577. _each(args, function (x) {
  17578. console[name](x);
  17579. });
  17580. }
  17581. }
  17582. }]));
  17583. };
  17584. };
  17585. async.log = _console_fn('log');
  17586. async.dir = _console_fn('dir');
  17587. /*async.info = _console_fn('info');
  17588. async.warn = _console_fn('warn');
  17589. async.error = _console_fn('error');*/
  17590. async.memoize = function (fn, hasher) {
  17591. var memo = {};
  17592. var queues = {};
  17593. hasher = hasher || function (x) {
  17594. return x;
  17595. };
  17596. var memoized = function () {
  17597. var args = Array.prototype.slice.call(arguments);
  17598. var callback = args.pop();
  17599. var key = hasher.apply(null, args);
  17600. if (key in memo) {
  17601. async.nextTick(function () {
  17602. callback.apply(null, memo[key]);
  17603. });
  17604. }
  17605. else if (key in queues) {
  17606. queues[key].push(callback);
  17607. }
  17608. else {
  17609. queues[key] = [callback];
  17610. fn.apply(null, args.concat([function () {
  17611. memo[key] = arguments;
  17612. var q = queues[key];
  17613. delete queues[key];
  17614. for (var i = 0, l = q.length; i < l; i++) {
  17615. q[i].apply(null, arguments);
  17616. }
  17617. }]));
  17618. }
  17619. };
  17620. memoized.memo = memo;
  17621. memoized.unmemoized = fn;
  17622. return memoized;
  17623. };
  17624. async.unmemoize = function (fn) {
  17625. return function () {
  17626. return (fn.unmemoized || fn).apply(null, arguments);
  17627. };
  17628. };
  17629. async.times = function (count, iterator, callback) {
  17630. var counter = [];
  17631. for (var i = 0; i < count; i++) {
  17632. counter.push(i);
  17633. }
  17634. return async.map(counter, iterator, callback);
  17635. };
  17636. async.timesSeries = function (count, iterator, callback) {
  17637. var counter = [];
  17638. for (var i = 0; i < count; i++) {
  17639. counter.push(i);
  17640. }
  17641. return async.mapSeries(counter, iterator, callback);
  17642. };
  17643. async.seq = function (/* functions... */) {
  17644. var fns = arguments;
  17645. return function () {
  17646. var that = this;
  17647. var args = Array.prototype.slice.call(arguments);
  17648. var callback = args.pop();
  17649. async.reduce(fns, args, function (newargs, fn, cb) {
  17650. fn.apply(that, newargs.concat([function () {
  17651. var err = arguments[0];
  17652. var nextargs = Array.prototype.slice.call(arguments, 1);
  17653. cb(err, nextargs);
  17654. }]))
  17655. },
  17656. function (err, results) {
  17657. callback.apply(that, [err].concat(results));
  17658. });
  17659. };
  17660. };
  17661. async.compose = function (/* functions... */) {
  17662. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17663. };
  17664. var _applyEach = function (eachfn, fns /*args...*/) {
  17665. var go = function () {
  17666. var that = this;
  17667. var args = Array.prototype.slice.call(arguments);
  17668. var callback = args.pop();
  17669. return eachfn(fns, function (fn, cb) {
  17670. fn.apply(that, args.concat([cb]));
  17671. },
  17672. callback);
  17673. };
  17674. if (arguments.length > 2) {
  17675. var args = Array.prototype.slice.call(arguments, 2);
  17676. return go.apply(this, args);
  17677. }
  17678. else {
  17679. return go;
  17680. }
  17681. };
  17682. async.applyEach = doParallel(_applyEach);
  17683. async.applyEachSeries = doSeries(_applyEach);
  17684. async.forever = function (fn, callback) {
  17685. function next(err) {
  17686. if (err) {
  17687. if (callback) {
  17688. return callback(err);
  17689. }
  17690. throw err;
  17691. }
  17692. fn(next);
  17693. }
  17694. next();
  17695. };
  17696. // Node.js
  17697. if (typeof module !== 'undefined' && module.exports) {
  17698. module.exports = async;
  17699. }
  17700. // AMD / RequireJS
  17701. else if (typeof define !== 'undefined' && define.amd) {
  17702. define([], function () {
  17703. return async;
  17704. });
  17705. }
  17706. // included directly via <script> tag
  17707. else {
  17708. root.async = async;
  17709. }
  17710. }());
  17711. }).call(this,require('_process'))
  17712. },{"_process":115}],69:[function(require,module,exports){
  17713. // i18next, v1.7.7
  17714. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17715. // Distributed under MIT license
  17716. // http://i18next.com
  17717. (function() {
  17718. // add indexOf to non ECMA-262 standard compliant browsers
  17719. if (!Array.prototype.indexOf) {
  17720. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17721. "use strict";
  17722. if (this == null) {
  17723. throw new TypeError();
  17724. }
  17725. var t = Object(this);
  17726. var len = t.length >>> 0;
  17727. if (len === 0) {
  17728. return -1;
  17729. }
  17730. var n = 0;
  17731. if (arguments.length > 0) {
  17732. n = Number(arguments[1]);
  17733. if (n != n) { // shortcut for verifying if it's NaN
  17734. n = 0;
  17735. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17736. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17737. }
  17738. }
  17739. if (n >= len) {
  17740. return -1;
  17741. }
  17742. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17743. for (; k < len; k++) {
  17744. if (k in t && t[k] === searchElement) {
  17745. return k;
  17746. }
  17747. }
  17748. return -1;
  17749. }
  17750. }
  17751. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17752. if (!Array.prototype.lastIndexOf) {
  17753. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17754. "use strict";
  17755. if (this == null) {
  17756. throw new TypeError();
  17757. }
  17758. var t = Object(this);
  17759. var len = t.length >>> 0;
  17760. if (len === 0) {
  17761. return -1;
  17762. }
  17763. var n = len;
  17764. if (arguments.length > 1) {
  17765. n = Number(arguments[1]);
  17766. if (n != n) {
  17767. n = 0;
  17768. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17769. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17770. }
  17771. }
  17772. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17773. for (; k >= 0; k--) {
  17774. if (k in t && t[k] === searchElement) {
  17775. return k;
  17776. }
  17777. }
  17778. return -1;
  17779. };
  17780. }
  17781. // Add string trim for IE8.
  17782. if (typeof String.prototype.trim !== 'function') {
  17783. String.prototype.trim = function() {
  17784. return this.replace(/^\s+|\s+$/g, '');
  17785. }
  17786. }
  17787. var root = this
  17788. , $ = root.jQuery || root.Zepto
  17789. , i18n = {}
  17790. , resStore = {}
  17791. , currentLng
  17792. , replacementCounter = 0
  17793. , languages = []
  17794. , initialized = false
  17795. , sync = {};
  17796. // Export the i18next object for **CommonJS**.
  17797. // If we're not in CommonJS, add `i18n` to the
  17798. // global object or to jquery.
  17799. if (typeof module !== 'undefined' && module.exports) {
  17800. if (!$) {
  17801. try {
  17802. $ = require('jquery');
  17803. } catch(e) {
  17804. // just ignore
  17805. }
  17806. }
  17807. if ($) {
  17808. $.i18n = $.i18n || i18n;
  17809. }
  17810. module.exports = i18n;
  17811. } else {
  17812. if ($) {
  17813. $.i18n = $.i18n || i18n;
  17814. }
  17815. root.i18n = root.i18n || i18n;
  17816. }
  17817. sync = {
  17818. load: function(lngs, options, cb) {
  17819. if (options.useLocalStorage) {
  17820. sync._loadLocal(lngs, options, function(err, store) {
  17821. var missingLngs = [];
  17822. for (var i = 0, len = lngs.length; i < len; i++) {
  17823. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17824. }
  17825. if (missingLngs.length > 0) {
  17826. sync._fetch(missingLngs, options, function(err, fetched) {
  17827. f.extend(store, fetched);
  17828. sync._storeLocal(fetched);
  17829. cb(null, store);
  17830. });
  17831. } else {
  17832. cb(null, store);
  17833. }
  17834. });
  17835. } else {
  17836. sync._fetch(lngs, options, function(err, store){
  17837. cb(null, store);
  17838. });
  17839. }
  17840. },
  17841. _loadLocal: function(lngs, options, cb) {
  17842. var store = {}
  17843. , nowMS = new Date().getTime();
  17844. if(window.localStorage) {
  17845. var todo = lngs.length;
  17846. f.each(lngs, function(key, lng) {
  17847. var local = window.localStorage.getItem('res_' + lng);
  17848. if (local) {
  17849. local = JSON.parse(local);
  17850. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17851. store[lng] = local;
  17852. }
  17853. }
  17854. todo--; // wait for all done befor callback
  17855. if (todo === 0) cb(null, store);
  17856. });
  17857. }
  17858. },
  17859. _storeLocal: function(store) {
  17860. if(window.localStorage) {
  17861. for (var m in store) {
  17862. store[m].i18nStamp = new Date().getTime();
  17863. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17864. }
  17865. }
  17866. return;
  17867. },
  17868. _fetch: function(lngs, options, cb) {
  17869. var ns = options.ns
  17870. , store = {};
  17871. if (!options.dynamicLoad) {
  17872. var todo = ns.namespaces.length * lngs.length
  17873. , errors;
  17874. // load each file individual
  17875. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17876. f.each(lngs, function(lngIndex, lngValue) {
  17877. // Call this once our translation has returned.
  17878. var loadComplete = function(err, data) {
  17879. if (err) {
  17880. errors = errors || [];
  17881. errors.push(err);
  17882. }
  17883. store[lngValue] = store[lngValue] || {};
  17884. store[lngValue][nsValue] = data;
  17885. todo--; // wait for all done befor callback
  17886. if (todo === 0) cb(errors, store);
  17887. };
  17888. if(typeof options.customLoad == 'function'){
  17889. // Use the specified custom callback.
  17890. options.customLoad(lngValue, nsValue, options, loadComplete);
  17891. } else {
  17892. //~ // Use our inbuilt sync.
  17893. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17894. }
  17895. });
  17896. });
  17897. } else {
  17898. // Call this once our translation has returned.
  17899. var loadComplete = function(err, data) {
  17900. cb(null, data);
  17901. };
  17902. if(typeof options.customLoad == 'function'){
  17903. // Use the specified custom callback.
  17904. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17905. } else {
  17906. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17907. // load all needed stuff once
  17908. f.ajax({
  17909. url: url,
  17910. success: function(data, status, xhr) {
  17911. f.log('loaded: ' + url);
  17912. loadComplete(null, data);
  17913. },
  17914. error : function(xhr, status, error) {
  17915. f.log('failed loading: ' + url);
  17916. loadComplete('failed loading resource.json error: ' + error);
  17917. },
  17918. dataType: "json",
  17919. async : options.getAsync
  17920. });
  17921. }
  17922. }
  17923. },
  17924. _fetchOne: function(lng, ns, options, done) {
  17925. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17926. f.ajax({
  17927. url: url,
  17928. success: function(data, status, xhr) {
  17929. f.log('loaded: ' + url);
  17930. done(null, data);
  17931. },
  17932. error : function(xhr, status, error) {
  17933. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17934. // file loaded but invalid json, stop waste time !
  17935. f.error('There is a typo in: ' + url);
  17936. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17937. f.log('Does not exist: ' + url);
  17938. } else {
  17939. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17940. f.log(theStatus + ' when loading ' + url);
  17941. }
  17942. done(error, {});
  17943. },
  17944. dataType: "json",
  17945. async : options.getAsync
  17946. });
  17947. },
  17948. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17949. var payload = {};
  17950. payload[key] = defaultValue;
  17951. var urls = [];
  17952. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17953. for (var i = 0; i < o.fallbackLng.length; i++) {
  17954. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17955. }
  17956. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17957. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17958. } else if (o.sendMissingTo === 'all') {
  17959. for (var i = 0, l = lngs.length; i < l; i++) {
  17960. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17961. }
  17962. }
  17963. for (var y = 0, len = urls.length; y < len; y++) {
  17964. var item = urls[y];
  17965. f.ajax({
  17966. url: item.url,
  17967. type: o.sendType,
  17968. data: payload,
  17969. success: function(data, status, xhr) {
  17970. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17971. // add key to resStore
  17972. var keys = key.split('.');
  17973. var x = 0;
  17974. var value = resStore[item.lng][ns];
  17975. while (keys[x]) {
  17976. if (x === keys.length - 1) {
  17977. value = value[keys[x]] = defaultValue;
  17978. } else {
  17979. value = value[keys[x]] = value[keys[x]] || {};
  17980. }
  17981. x++;
  17982. }
  17983. },
  17984. error : function(xhr, status, error) {
  17985. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17986. },
  17987. dataType: "json",
  17988. async : o.postAsync
  17989. });
  17990. }
  17991. },
  17992. reload: reload
  17993. };
  17994. // defaults
  17995. var o = {
  17996. lng: undefined,
  17997. load: 'all',
  17998. preload: [],
  17999. lowerCaseLng: false,
  18000. returnObjectTrees: false,
  18001. fallbackLng: ['dev'],
  18002. fallbackNS: [],
  18003. detectLngQS: 'setLng',
  18004. detectLngFromLocalStorage: false,
  18005. ns: 'translation',
  18006. fallbackOnNull: true,
  18007. fallbackOnEmpty: false,
  18008. fallbackToDefaultNS: false,
  18009. nsseparator: ':',
  18010. keyseparator: '.',
  18011. selectorAttr: 'data-i18n',
  18012. debug: false,
  18013. resGetPath: 'locales/__lng__/__ns__.json',
  18014. resPostPath: 'locales/add/__lng__/__ns__',
  18015. getAsync: true,
  18016. postAsync: true,
  18017. resStore: undefined,
  18018. useLocalStorage: false,
  18019. localStorageExpirationTime: 7*24*60*60*1000,
  18020. dynamicLoad: false,
  18021. sendMissing: false,
  18022. sendMissingTo: 'fallback', // current | all
  18023. sendType: 'POST',
  18024. interpolationPrefix: '__',
  18025. interpolationSuffix: '__',
  18026. defaultVariables: false,
  18027. reusePrefix: '$t(',
  18028. reuseSuffix: ')',
  18029. pluralSuffix: '_plural',
  18030. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18031. contextNotFound: ['context_not_found', Math.random()].join(''),
  18032. escapeInterpolation: false,
  18033. indefiniteSuffix: '_indefinite',
  18034. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18035. setJqueryExt: true,
  18036. defaultValueFromContent: true,
  18037. useDataAttrOptions: false,
  18038. cookieExpirationTime: undefined,
  18039. useCookie: true,
  18040. cookieName: 'i18next',
  18041. cookieDomain: undefined,
  18042. objectTreeKeyHandler: undefined,
  18043. postProcess: undefined,
  18044. parseMissingKey: undefined,
  18045. missingKeyHandler: sync.postMissing,
  18046. shortcutFunction: 'sprintf' // or: defaultValue
  18047. };
  18048. function _extend(target, source) {
  18049. if (!source || typeof source === 'function') {
  18050. return target;
  18051. }
  18052. for (var attr in source) { target[attr] = source[attr]; }
  18053. return target;
  18054. }
  18055. function _deepExtend(target, source) {
  18056. for (var prop in source)
  18057. if (prop in target)
  18058. _deepExtend(target[prop], source[prop]);
  18059. else
  18060. target[prop] = source[prop];
  18061. return target;
  18062. }
  18063. function _each(object, callback, args) {
  18064. var name, i = 0,
  18065. length = object.length,
  18066. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18067. if (args) {
  18068. if (isObj) {
  18069. for (name in object) {
  18070. if (callback.apply(object[name], args) === false) {
  18071. break;
  18072. }
  18073. }
  18074. } else {
  18075. for ( ; i < length; ) {
  18076. if (callback.apply(object[i++], args) === false) {
  18077. break;
  18078. }
  18079. }
  18080. }
  18081. // A special, fast, case for the most common use of each
  18082. } else {
  18083. if (isObj) {
  18084. for (name in object) {
  18085. if (callback.call(object[name], name, object[name]) === false) {
  18086. break;
  18087. }
  18088. }
  18089. } else {
  18090. for ( ; i < length; ) {
  18091. if (callback.call(object[i], i, object[i++]) === false) {
  18092. break;
  18093. }
  18094. }
  18095. }
  18096. }
  18097. return object;
  18098. }
  18099. var _entityMap = {
  18100. "&": "&amp;",
  18101. "<": "&lt;",
  18102. ">": "&gt;",
  18103. '"': '&quot;',
  18104. "'": '&#39;',
  18105. "/": '&#x2F;'
  18106. };
  18107. function _escape(data) {
  18108. if (typeof data === 'string') {
  18109. return data.replace(/[&<>"'\/]/g, function (s) {
  18110. return _entityMap[s];
  18111. });
  18112. }else{
  18113. return data;
  18114. }
  18115. }
  18116. function _ajax(options) {
  18117. // v0.5.0 of https://github.com/goloroden/http.js
  18118. var getXhr = function (callback) {
  18119. // Use the native XHR object if the browser supports it.
  18120. if (window.XMLHttpRequest) {
  18121. return callback(null, new XMLHttpRequest());
  18122. } else if (window.ActiveXObject) {
  18123. // In Internet Explorer check for ActiveX versions of the XHR object.
  18124. try {
  18125. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18126. } catch (e) {
  18127. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18128. }
  18129. }
  18130. // If no XHR support was found, throw an error.
  18131. return callback(new Error());
  18132. };
  18133. var encodeUsingUrlEncoding = function (data) {
  18134. if(typeof data === 'string') {
  18135. return data;
  18136. }
  18137. var result = [];
  18138. for(var dataItem in data) {
  18139. if(data.hasOwnProperty(dataItem)) {
  18140. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18141. }
  18142. }
  18143. return result.join('&');
  18144. };
  18145. var utf8 = function (text) {
  18146. text = text.replace(/\r\n/g, '\n');
  18147. var result = '';
  18148. for(var i = 0; i < text.length; i++) {
  18149. var c = text.charCodeAt(i);
  18150. if(c < 128) {
  18151. result += String.fromCharCode(c);
  18152. } else if((c > 127) && (c < 2048)) {
  18153. result += String.fromCharCode((c >> 6) | 192);
  18154. result += String.fromCharCode((c & 63) | 128);
  18155. } else {
  18156. result += String.fromCharCode((c >> 12) | 224);
  18157. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18158. result += String.fromCharCode((c & 63) | 128);
  18159. }
  18160. }
  18161. return result;
  18162. };
  18163. var base64 = function (text) {
  18164. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18165. text = utf8(text);
  18166. var result = '',
  18167. chr1, chr2, chr3,
  18168. enc1, enc2, enc3, enc4,
  18169. i = 0;
  18170. do {
  18171. chr1 = text.charCodeAt(i++);
  18172. chr2 = text.charCodeAt(i++);
  18173. chr3 = text.charCodeAt(i++);
  18174. enc1 = chr1 >> 2;
  18175. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18176. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18177. enc4 = chr3 & 63;
  18178. if(isNaN(chr2)) {
  18179. enc3 = enc4 = 64;
  18180. } else if(isNaN(chr3)) {
  18181. enc4 = 64;
  18182. }
  18183. result +=
  18184. keyStr.charAt(enc1) +
  18185. keyStr.charAt(enc2) +
  18186. keyStr.charAt(enc3) +
  18187. keyStr.charAt(enc4);
  18188. chr1 = chr2 = chr3 = '';
  18189. enc1 = enc2 = enc3 = enc4 = '';
  18190. } while(i < text.length);
  18191. return result;
  18192. };
  18193. var mergeHeaders = function () {
  18194. // Use the first header object as base.
  18195. var result = arguments[0];
  18196. // Iterate through the remaining header objects and add them.
  18197. for(var i = 1; i < arguments.length; i++) {
  18198. var currentHeaders = arguments[i];
  18199. for(var header in currentHeaders) {
  18200. if(currentHeaders.hasOwnProperty(header)) {
  18201. result[header] = currentHeaders[header];
  18202. }
  18203. }
  18204. }
  18205. // Return the merged headers.
  18206. return result;
  18207. };
  18208. var ajax = function (method, url, options, callback) {
  18209. // Adjust parameters.
  18210. if(typeof options === 'function') {
  18211. callback = options;
  18212. options = {};
  18213. }
  18214. // Set default parameter values.
  18215. options.cache = options.cache || false;
  18216. options.data = options.data || {};
  18217. options.headers = options.headers || {};
  18218. options.jsonp = options.jsonp || false;
  18219. options.async = options.async === undefined ? true : options.async;
  18220. // Merge the various header objects.
  18221. var headers = mergeHeaders({
  18222. 'accept': '*/*',
  18223. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18224. }, ajax.headers, options.headers);
  18225. // Encode the data according to the content-type.
  18226. var payload;
  18227. if (headers['content-type'] === 'application/json') {
  18228. payload = JSON.stringify(options.data);
  18229. } else {
  18230. payload = encodeUsingUrlEncoding(options.data);
  18231. }
  18232. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18233. // if neccessary.
  18234. if(method === 'GET') {
  18235. // Setup the query string.
  18236. var queryString = [];
  18237. if(payload) {
  18238. queryString.push(payload);
  18239. payload = null;
  18240. }
  18241. // Handle caching.
  18242. if(!options.cache) {
  18243. queryString.push('_=' + (new Date()).getTime());
  18244. }
  18245. // If neccessary prepare the query string for a JSONP call.
  18246. if(options.jsonp) {
  18247. queryString.push('callback=' + options.jsonp);
  18248. queryString.push('jsonp=' + options.jsonp);
  18249. }
  18250. // Merge the query string and attach it to the url.
  18251. queryString = queryString.join('&');
  18252. if (queryString.length > 1) {
  18253. if (url.indexOf('?') > -1) {
  18254. url += '&' + queryString;
  18255. } else {
  18256. url += '?' + queryString;
  18257. }
  18258. }
  18259. // Make a JSONP call if neccessary.
  18260. if(options.jsonp) {
  18261. var head = document.getElementsByTagName('head')[0];
  18262. var script = document.createElement('script');
  18263. script.type = 'text/javascript';
  18264. script.src = url;
  18265. head.appendChild(script);
  18266. return;
  18267. }
  18268. }
  18269. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18270. getXhr(function (err, xhr) {
  18271. if(err) return callback(err);
  18272. // Open the request.
  18273. xhr.open(method, url, options.async);
  18274. // Set the request headers.
  18275. for(var header in headers) {
  18276. if(headers.hasOwnProperty(header)) {
  18277. xhr.setRequestHeader(header, headers[header]);
  18278. }
  18279. }
  18280. // Handle the request events.
  18281. xhr.onreadystatechange = function () {
  18282. if(xhr.readyState === 4) {
  18283. var data = xhr.responseText || '';
  18284. // If no callback is given, return.
  18285. if(!callback) {
  18286. return;
  18287. }
  18288. // Return an object that provides access to the data as text and JSON.
  18289. callback(xhr.status, {
  18290. text: function () {
  18291. return data;
  18292. },
  18293. json: function () {
  18294. try {
  18295. return JSON.parse(data)
  18296. } catch (e) {
  18297. f.error('Can not parse JSON. URL: ' + url);
  18298. return {};
  18299. }
  18300. }
  18301. });
  18302. }
  18303. };
  18304. // Actually send the XHR request.
  18305. xhr.send(payload);
  18306. });
  18307. };
  18308. // Define the external interface.
  18309. var http = {
  18310. authBasic: function (username, password) {
  18311. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18312. },
  18313. connect: function (url, options, callback) {
  18314. return ajax('CONNECT', url, options, callback);
  18315. },
  18316. del: function (url, options, callback) {
  18317. return ajax('DELETE', url, options, callback);
  18318. },
  18319. get: function (url, options, callback) {
  18320. return ajax('GET', url, options, callback);
  18321. },
  18322. head: function (url, options, callback) {
  18323. return ajax('HEAD', url, options, callback);
  18324. },
  18325. headers: function (headers) {
  18326. ajax.headers = headers || {};
  18327. },
  18328. isAllowed: function (url, verb, callback) {
  18329. this.options(url, function (status, data) {
  18330. callback(data.text().indexOf(verb) !== -1);
  18331. });
  18332. },
  18333. options: function (url, options, callback) {
  18334. return ajax('OPTIONS', url, options, callback);
  18335. },
  18336. patch: function (url, options, callback) {
  18337. return ajax('PATCH', url, options, callback);
  18338. },
  18339. post: function (url, options, callback) {
  18340. return ajax('POST', url, options, callback);
  18341. },
  18342. put: function (url, options, callback) {
  18343. return ajax('PUT', url, options, callback);
  18344. },
  18345. trace: function (url, options, callback) {
  18346. return ajax('TRACE', url, options, callback);
  18347. }
  18348. };
  18349. var methode = options.type ? options.type.toLowerCase() : 'get';
  18350. http[methode](options.url, options, function (status, data) {
  18351. // file: protocol always gives status code 0, so check for data
  18352. if (status === 200 || (status === 0 && data.text())) {
  18353. options.success(data.json(), status, null);
  18354. } else {
  18355. options.error(data.text(), status, null);
  18356. }
  18357. });
  18358. }
  18359. var _cookie = {
  18360. create: function(name,value,minutes,domain) {
  18361. var expires;
  18362. if (minutes) {
  18363. var date = new Date();
  18364. date.setTime(date.getTime()+(minutes*60*1000));
  18365. expires = "; expires="+date.toGMTString();
  18366. }
  18367. else expires = "";
  18368. domain = (domain)? "domain="+domain+";" : "";
  18369. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18370. },
  18371. read: function(name) {
  18372. var nameEQ = name + "=";
  18373. var ca = document.cookie.split(';');
  18374. for(var i=0;i < ca.length;i++) {
  18375. var c = ca[i];
  18376. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18377. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18378. }
  18379. return null;
  18380. },
  18381. remove: function(name) {
  18382. this.create(name,"",-1);
  18383. }
  18384. };
  18385. var cookie_noop = {
  18386. create: function(name,value,minutes,domain) {},
  18387. read: function(name) { return null; },
  18388. remove: function(name) {}
  18389. };
  18390. // move dependent functions to a container so that
  18391. // they can be overriden easier in no jquery environment (node.js)
  18392. var f = {
  18393. extend: $ ? $.extend : _extend,
  18394. deepExtend: _deepExtend,
  18395. each: $ ? $.each : _each,
  18396. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18397. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18398. detectLanguage: detectLanguage,
  18399. escape: _escape,
  18400. log: function(str) {
  18401. if (o.debug && typeof console !== "undefined") console.log(str);
  18402. },
  18403. error: function(str) {
  18404. if (typeof console !== "undefined") console.error(str);
  18405. },
  18406. getCountyIndexOfLng: function(lng) {
  18407. var lng_index = 0;
  18408. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18409. return lng_index;
  18410. },
  18411. toLanguages: function(lng) {
  18412. var log = this.log;
  18413. function applyCase(l) {
  18414. var ret = l;
  18415. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18416. var parts = l.split('-');
  18417. ret = o.lowerCaseLng ?
  18418. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18419. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18420. } else {
  18421. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18422. }
  18423. return ret;
  18424. }
  18425. var languages = [];
  18426. var whitelist = o.lngWhitelist || false;
  18427. var addLanguage = function(language){
  18428. //reject langs not whitelisted
  18429. if(!whitelist || whitelist.indexOf(language) > -1){
  18430. languages.push(language);
  18431. }else{
  18432. log('rejecting non-whitelisted language: ' + language);
  18433. }
  18434. };
  18435. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18436. var parts = lng.split('-');
  18437. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18438. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18439. } else {
  18440. addLanguage(applyCase(lng));
  18441. }
  18442. for (var i = 0; i < o.fallbackLng.length; i++) {
  18443. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18444. }
  18445. return languages;
  18446. },
  18447. regexEscape: function(str) {
  18448. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18449. },
  18450. regexReplacementEscape: function(strOrFn) {
  18451. if (typeof strOrFn === 'string') {
  18452. return strOrFn.replace(/\$/g, "$$$$");
  18453. } else {
  18454. return strOrFn;
  18455. }
  18456. },
  18457. localStorage: {
  18458. setItem: function(key, value) {
  18459. if (window.localStorage) {
  18460. try {
  18461. window.localStorage.setItem(key, value);
  18462. } catch (e) {
  18463. f.log('failed to set value for key "' + key + '" to localStorage.');
  18464. }
  18465. }
  18466. }
  18467. }
  18468. };
  18469. function init(options, cb) {
  18470. if (typeof options === 'function') {
  18471. cb = options;
  18472. options = {};
  18473. }
  18474. options = options || {};
  18475. // override defaults with passed in options
  18476. f.extend(o, options);
  18477. delete o.fixLng; /* passed in each time */
  18478. // override functions: .log(), .detectLanguage(), etc
  18479. if (o.functions) {
  18480. delete o.functions;
  18481. f.extend(f, options.functions);
  18482. }
  18483. // create namespace object if namespace is passed in as string
  18484. if (typeof o.ns == 'string') {
  18485. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18486. }
  18487. // fallback namespaces
  18488. if (typeof o.fallbackNS == 'string') {
  18489. o.fallbackNS = [o.fallbackNS];
  18490. }
  18491. // fallback languages
  18492. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18493. o.fallbackLng = [o.fallbackLng];
  18494. }
  18495. // escape prefix/suffix
  18496. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18497. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18498. if (!o.lng) o.lng = f.detectLanguage();
  18499. languages = f.toLanguages(o.lng);
  18500. currentLng = languages[0];
  18501. f.log('currentLng set to: ' + currentLng);
  18502. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18503. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18504. }
  18505. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18506. f.localStorage.setItem('i18next_lng', currentLng);
  18507. }
  18508. var lngTranslate = translate;
  18509. if (options.fixLng) {
  18510. lngTranslate = function(key, options) {
  18511. options = options || {};
  18512. options.lng = options.lng || lngTranslate.lng;
  18513. return translate(key, options);
  18514. };
  18515. lngTranslate.lng = currentLng;
  18516. }
  18517. pluralExtensions.setCurrentLng(currentLng);
  18518. // add JQuery extensions
  18519. if ($ && o.setJqueryExt) addJqueryFunct();
  18520. // jQuery deferred
  18521. var deferred;
  18522. if ($ && $.Deferred) {
  18523. deferred = $.Deferred();
  18524. }
  18525. // return immidiatly if res are passed in
  18526. if (o.resStore) {
  18527. resStore = o.resStore;
  18528. initialized = true;
  18529. if (cb) cb(lngTranslate);
  18530. if (deferred) deferred.resolve(lngTranslate);
  18531. if (deferred) return deferred.promise();
  18532. return;
  18533. }
  18534. // languages to load
  18535. var lngsToLoad = f.toLanguages(o.lng);
  18536. if (typeof o.preload === 'string') o.preload = [o.preload];
  18537. for (var i = 0, l = o.preload.length; i < l; i++) {
  18538. var pres = f.toLanguages(o.preload[i]);
  18539. for (var y = 0, len = pres.length; y < len; y++) {
  18540. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18541. lngsToLoad.push(pres[y]);
  18542. }
  18543. }
  18544. }
  18545. // else load them
  18546. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18547. resStore = store;
  18548. initialized = true;
  18549. if (cb) cb(lngTranslate);
  18550. if (deferred) deferred.resolve(lngTranslate);
  18551. });
  18552. if (deferred) return deferred.promise();
  18553. }
  18554. function preload(lngs, cb) {
  18555. if (typeof lngs === 'string') lngs = [lngs];
  18556. for (var i = 0, l = lngs.length; i < l; i++) {
  18557. if (o.preload.indexOf(lngs[i]) < 0) {
  18558. o.preload.push(lngs[i]);
  18559. }
  18560. }
  18561. return init(cb);
  18562. }
  18563. function addResourceBundle(lng, ns, resources, deep) {
  18564. if (typeof ns !== 'string') {
  18565. resources = ns;
  18566. ns = o.ns.defaultNs;
  18567. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18568. o.ns.namespaces.push(ns);
  18569. }
  18570. resStore[lng] = resStore[lng] || {};
  18571. resStore[lng][ns] = resStore[lng][ns] || {};
  18572. if (deep) {
  18573. f.deepExtend(resStore[lng][ns], resources);
  18574. } else {
  18575. f.extend(resStore[lng][ns], resources);
  18576. }
  18577. }
  18578. function hasResourceBundle(lng, ns) {
  18579. if (typeof ns !== 'string') {
  18580. ns = o.ns.defaultNs;
  18581. }
  18582. resStore[lng] = resStore[lng] || {};
  18583. var res = resStore[lng][ns] || {};
  18584. var hasValues = false;
  18585. for(var prop in res) {
  18586. if (res.hasOwnProperty(prop)) {
  18587. hasValues = true;
  18588. }
  18589. }
  18590. return hasValues;
  18591. }
  18592. function removeResourceBundle(lng, ns) {
  18593. if (typeof ns !== 'string') {
  18594. ns = o.ns.defaultNs;
  18595. }
  18596. resStore[lng] = resStore[lng] || {};
  18597. resStore[lng][ns] = {};
  18598. }
  18599. function addResource(lng, ns, key, value) {
  18600. if (typeof ns !== 'string') {
  18601. resource = ns;
  18602. ns = o.ns.defaultNs;
  18603. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18604. o.ns.namespaces.push(ns);
  18605. }
  18606. resStore[lng] = resStore[lng] || {};
  18607. resStore[lng][ns] = resStore[lng][ns] || {};
  18608. var keys = key.split(o.keyseparator);
  18609. var x = 0;
  18610. var node = resStore[lng][ns];
  18611. var origRef = node;
  18612. while (keys[x]) {
  18613. if (x == keys.length - 1)
  18614. node[keys[x]] = value;
  18615. else {
  18616. if (node[keys[x]] == null)
  18617. node[keys[x]] = {};
  18618. node = node[keys[x]];
  18619. }
  18620. x++;
  18621. }
  18622. }
  18623. function addResources(lng, ns, resources) {
  18624. if (typeof ns !== 'string') {
  18625. resource = ns;
  18626. ns = o.ns.defaultNs;
  18627. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18628. o.ns.namespaces.push(ns);
  18629. }
  18630. for (var m in resources) {
  18631. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18632. }
  18633. }
  18634. function setDefaultNamespace(ns) {
  18635. o.ns.defaultNs = ns;
  18636. }
  18637. function loadNamespace(namespace, cb) {
  18638. loadNamespaces([namespace], cb);
  18639. }
  18640. function loadNamespaces(namespaces, cb) {
  18641. var opts = {
  18642. dynamicLoad: o.dynamicLoad,
  18643. resGetPath: o.resGetPath,
  18644. getAsync: o.getAsync,
  18645. customLoad: o.customLoad,
  18646. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18647. };
  18648. // languages to load
  18649. var lngsToLoad = f.toLanguages(o.lng);
  18650. if (typeof o.preload === 'string') o.preload = [o.preload];
  18651. for (var i = 0, l = o.preload.length; i < l; i++) {
  18652. var pres = f.toLanguages(o.preload[i]);
  18653. for (var y = 0, len = pres.length; y < len; y++) {
  18654. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18655. lngsToLoad.push(pres[y]);
  18656. }
  18657. }
  18658. }
  18659. // check if we have to load
  18660. var lngNeedLoad = [];
  18661. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18662. var needLoad = false;
  18663. var resSet = resStore[lngsToLoad[a]];
  18664. if (resSet) {
  18665. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18666. if (!resSet[namespaces[b]]) needLoad = true;
  18667. }
  18668. } else {
  18669. needLoad = true;
  18670. }
  18671. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18672. }
  18673. if (lngNeedLoad.length) {
  18674. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18675. var todo = namespaces.length * lngNeedLoad.length;
  18676. // load each file individual
  18677. f.each(namespaces, function(nsIndex, nsValue) {
  18678. // append namespace to namespace array
  18679. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18680. o.ns.namespaces.push(nsValue);
  18681. }
  18682. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18683. resStore[lngValue] = resStore[lngValue] || {};
  18684. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18685. todo--; // wait for all done befor callback
  18686. if (todo === 0 && cb) {
  18687. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18688. cb();
  18689. }
  18690. });
  18691. });
  18692. });
  18693. } else {
  18694. if (cb) cb();
  18695. }
  18696. }
  18697. function setLng(lng, options, cb) {
  18698. if (typeof options === 'function') {
  18699. cb = options;
  18700. options = {};
  18701. } else if (!options) {
  18702. options = {};
  18703. }
  18704. options.lng = lng;
  18705. return init(options, cb);
  18706. }
  18707. function lng() {
  18708. return currentLng;
  18709. }
  18710. function reload(cb) {
  18711. resStore = {};
  18712. setLng(currentLng, cb);
  18713. }
  18714. function addJqueryFunct() {
  18715. // $.t shortcut
  18716. $.t = $.t || translate;
  18717. function parse(ele, key, options) {
  18718. if (key.length === 0) return;
  18719. var attr = 'text';
  18720. if (key.indexOf('[') === 0) {
  18721. var parts = key.split(']');
  18722. key = parts[1];
  18723. attr = parts[0].substr(1, parts[0].length-1);
  18724. }
  18725. if (key.indexOf(';') === key.length-1) {
  18726. key = key.substr(0, key.length-2);
  18727. }
  18728. var optionsToUse;
  18729. if (attr === 'html') {
  18730. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18731. ele.html($.t(key, optionsToUse));
  18732. } else if (attr === 'text') {
  18733. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18734. ele.text($.t(key, optionsToUse));
  18735. } else if (attr === 'prepend') {
  18736. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18737. ele.prepend($.t(key, optionsToUse));
  18738. } else if (attr === 'append') {
  18739. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18740. ele.append($.t(key, optionsToUse));
  18741. } else if (attr.indexOf("data-") === 0) {
  18742. var dataAttr = attr.substr(("data-").length);
  18743. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18744. var translated = $.t(key, optionsToUse);
  18745. //we change into the data cache
  18746. ele.data(dataAttr, translated);
  18747. //we change into the dom
  18748. ele.attr(attr, translated);
  18749. } else {
  18750. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18751. ele.attr(attr, $.t(key, optionsToUse));
  18752. }
  18753. }
  18754. function localize(ele, options) {
  18755. var key = ele.attr(o.selectorAttr);
  18756. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18757. if (!key) return;
  18758. var target = ele
  18759. , targetSelector = ele.data("i18n-target");
  18760. if (targetSelector) {
  18761. target = ele.find(targetSelector) || ele;
  18762. }
  18763. if (!options && o.useDataAttrOptions === true) {
  18764. options = ele.data("i18n-options");
  18765. }
  18766. options = options || {};
  18767. if (key.indexOf(';') >= 0) {
  18768. var keys = key.split(';');
  18769. $.each(keys, function(m, k) {
  18770. if (k !== '') parse(target, k, options);
  18771. });
  18772. } else {
  18773. parse(target, key, options);
  18774. }
  18775. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18776. }
  18777. // fn
  18778. $.fn.i18n = function (options) {
  18779. return this.each(function() {
  18780. // localize element itself
  18781. localize($(this), options);
  18782. // localize childs
  18783. var elements = $(this).find('[' + o.selectorAttr + ']');
  18784. elements.each(function() {
  18785. localize($(this), options);
  18786. });
  18787. });
  18788. };
  18789. }
  18790. function applyReplacement(str, replacementHash, nestedKey, options) {
  18791. if (!str) return str;
  18792. options = options || replacementHash; // first call uses replacement hash combined with options
  18793. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18794. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18795. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18796. , unEscapingSuffix = 'HTML'+suffix;
  18797. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18798. f.each(hash, function(key, value) {
  18799. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18800. if (typeof value === 'object' && value !== null) {
  18801. str = applyReplacement(str, value, nextKey, options);
  18802. } else {
  18803. if (options.escapeInterpolation || o.escapeInterpolation) {
  18804. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18805. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18806. } else {
  18807. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18808. }
  18809. // str = options.escapeInterpolation;
  18810. }
  18811. });
  18812. return str;
  18813. }
  18814. // append it to functions
  18815. f.applyReplacement = applyReplacement;
  18816. function applyReuse(translated, options) {
  18817. var comma = ',';
  18818. var options_open = '{';
  18819. var options_close = '}';
  18820. var opts = f.extend({}, options);
  18821. delete opts.postProcess;
  18822. while (translated.indexOf(o.reusePrefix) != -1) {
  18823. replacementCounter++;
  18824. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18825. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18826. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18827. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18828. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18829. if (index_of_end_of_closing <= index_of_opening) {
  18830. f.error('there is an missing closing in following translation value', translated);
  18831. return '';
  18832. }
  18833. if (token_without_symbols.indexOf(comma) != -1) {
  18834. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18835. 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) {
  18836. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18837. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18838. try {
  18839. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18840. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18841. } catch (e) {
  18842. }
  18843. }
  18844. }
  18845. var translated_token = _translate(token_without_symbols, opts);
  18846. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18847. }
  18848. return translated;
  18849. }
  18850. function hasContext(options) {
  18851. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18852. }
  18853. function needsPlural(options, lng) {
  18854. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18855. }
  18856. function needsIndefiniteArticle(options) {
  18857. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18858. }
  18859. function exists(key, options) {
  18860. options = options || {};
  18861. var notFound = _getDefaultValue(key, options)
  18862. , found = _find(key, options);
  18863. return found !== undefined || found === notFound;
  18864. }
  18865. function translate(key, options) {
  18866. options = options || {};
  18867. if (!initialized) {
  18868. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18869. return options.defaultValue || '';
  18870. };
  18871. replacementCounter = 0;
  18872. return _translate.apply(null, arguments);
  18873. }
  18874. function _getDefaultValue(key, options) {
  18875. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18876. }
  18877. function _injectSprintfProcessor() {
  18878. var values = [];
  18879. // mh: build array from second argument onwards
  18880. for (var i = 1; i < arguments.length; i++) {
  18881. values.push(arguments[i]);
  18882. }
  18883. return {
  18884. postProcess: 'sprintf',
  18885. sprintf: values
  18886. };
  18887. }
  18888. function _translate(potentialKeys, options) {
  18889. if (options && typeof options !== 'object') {
  18890. if (o.shortcutFunction === 'sprintf') {
  18891. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18892. options = _injectSprintfProcessor.apply(null, arguments);
  18893. } else if (o.shortcutFunction === 'defaultValue') {
  18894. options = {
  18895. defaultValue: options
  18896. }
  18897. }
  18898. } else {
  18899. options = options || {};
  18900. }
  18901. if (typeof o.defaultVariables === 'object') {
  18902. options = f.extend({}, o.defaultVariables, options);
  18903. }
  18904. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18905. if (typeof potentialKeys === 'string') {
  18906. potentialKeys = [potentialKeys];
  18907. }
  18908. var key = potentialKeys[0];
  18909. if (potentialKeys.length > 1) {
  18910. for (var i = 0; i < potentialKeys.length; i++) {
  18911. key = potentialKeys[i];
  18912. if (exists(key, options)) {
  18913. break;
  18914. }
  18915. }
  18916. }
  18917. var notFound = _getDefaultValue(key, options)
  18918. , found = _find(key, options)
  18919. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18920. , ns = options.ns || o.ns.defaultNs
  18921. , parts;
  18922. // split ns and key
  18923. if (key.indexOf(o.nsseparator) > -1) {
  18924. parts = key.split(o.nsseparator);
  18925. ns = parts[0];
  18926. key = parts[1];
  18927. }
  18928. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18929. if (options.lng) {
  18930. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18931. } else {
  18932. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18933. }
  18934. }
  18935. var postProcessor = options.postProcess || o.postProcess;
  18936. if (found !== undefined && postProcessor) {
  18937. if (postProcessors[postProcessor]) {
  18938. found = postProcessors[postProcessor](found, key, options);
  18939. }
  18940. }
  18941. // process notFound if function exists
  18942. var splitNotFound = notFound;
  18943. if (notFound.indexOf(o.nsseparator) > -1) {
  18944. parts = notFound.split(o.nsseparator);
  18945. splitNotFound = parts[1];
  18946. }
  18947. if (splitNotFound === key && o.parseMissingKey) {
  18948. notFound = o.parseMissingKey(notFound);
  18949. }
  18950. if (found === undefined) {
  18951. notFound = applyReplacement(notFound, options);
  18952. notFound = applyReuse(notFound, options);
  18953. if (postProcessor && postProcessors[postProcessor]) {
  18954. var val = _getDefaultValue(key, options);
  18955. found = postProcessors[postProcessor](val, key, options);
  18956. }
  18957. }
  18958. return (found !== undefined) ? found : notFound;
  18959. }
  18960. function _find(key, options) {
  18961. options = options || {};
  18962. var optionWithoutCount, translated
  18963. , notFound = _getDefaultValue(key, options)
  18964. , lngs = languages;
  18965. if (!resStore) { return notFound; } // no resStore to translate from
  18966. // CI mode
  18967. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18968. // passed in lng
  18969. if (options.lngs) lngs = options.lngs;
  18970. if (options.lng) {
  18971. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18972. if (!resStore[lngs[0]]) {
  18973. var oldAsync = o.getAsync;
  18974. o.getAsync = false;
  18975. i18n.sync.load(lngs, o, function(err, store) {
  18976. f.extend(resStore, store);
  18977. o.getAsync = oldAsync;
  18978. });
  18979. }
  18980. }
  18981. var ns = options.ns || o.ns.defaultNs;
  18982. if (key.indexOf(o.nsseparator) > -1) {
  18983. var parts = key.split(o.nsseparator);
  18984. ns = parts[0];
  18985. key = parts[1];
  18986. }
  18987. if (hasContext(options)) {
  18988. optionWithoutCount = f.extend({}, options);
  18989. delete optionWithoutCount.context;
  18990. optionWithoutCount.defaultValue = o.contextNotFound;
  18991. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18992. translated = translate(contextKey, optionWithoutCount);
  18993. if (translated != o.contextNotFound) {
  18994. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18995. } // else continue translation with original/nonContext key
  18996. }
  18997. if (needsPlural(options, lngs[0])) {
  18998. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18999. delete optionWithoutCount.count;
  19000. delete optionWithoutCount.lng;
  19001. optionWithoutCount.defaultValue = o.pluralNotFound;
  19002. var pluralKey;
  19003. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19004. pluralKey = ns + o.nsseparator + key;
  19005. } else {
  19006. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19007. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19008. if (pluralExtension >= 0) {
  19009. pluralKey = pluralKey + '_' + pluralExtension;
  19010. } else if (pluralExtension === 1) {
  19011. pluralKey = ns + o.nsseparator + key; // singular
  19012. }
  19013. }
  19014. translated = translate(pluralKey, optionWithoutCount);
  19015. if (translated != o.pluralNotFound) {
  19016. return applyReplacement(translated, {
  19017. count: options.count,
  19018. interpolationPrefix: options.interpolationPrefix,
  19019. interpolationSuffix: options.interpolationSuffix
  19020. }); // apply replacement for count only
  19021. } else if (lngs.length > 1) {
  19022. // remove failed lng
  19023. var clone = lngs.slice();
  19024. clone.shift();
  19025. options = f.extend(options, { lngs: clone });
  19026. delete options.lng;
  19027. // retry with fallbacks
  19028. translated = translate(ns + o.nsseparator + key, options);
  19029. if (translated != o.pluralNotFound) return translated;
  19030. } else {
  19031. return translated;
  19032. }
  19033. }
  19034. if (needsIndefiniteArticle(options)) {
  19035. var optionsWithoutIndef = f.extend({}, options);
  19036. delete optionsWithoutIndef.indefinite_article;
  19037. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19038. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19039. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19040. translated = translate(indefiniteKey, optionsWithoutIndef);
  19041. if (translated != o.indefiniteNotFound) {
  19042. return translated;
  19043. }
  19044. }
  19045. var found;
  19046. var keys = key.split(o.keyseparator);
  19047. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19048. if (found !== undefined) break;
  19049. var l = lngs[i];
  19050. var x = 0;
  19051. var value = resStore[l] && resStore[l][ns];
  19052. while (keys[x]) {
  19053. value = value && value[keys[x]];
  19054. x++;
  19055. }
  19056. if (value !== undefined) {
  19057. var valueType = Object.prototype.toString.apply(value);
  19058. if (typeof value === 'string') {
  19059. value = applyReplacement(value, options);
  19060. value = applyReuse(value, options);
  19061. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19062. value = value.join('\n');
  19063. value = applyReplacement(value, options);
  19064. value = applyReuse(value, options);
  19065. } else if (value === null && o.fallbackOnNull === true) {
  19066. value = undefined;
  19067. } else if (value !== null) {
  19068. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19069. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19070. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19071. } else {
  19072. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19073. 'returned an object instead of string.';
  19074. f.log(value);
  19075. }
  19076. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19077. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19078. f.each(value, function(m) {
  19079. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19080. });
  19081. value = copy;
  19082. }
  19083. }
  19084. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19085. value = undefined;
  19086. found = value;
  19087. }
  19088. }
  19089. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19090. // set flag for fallback lookup - avoid recursion
  19091. options.isFallbackLookup = true;
  19092. if (o.fallbackNS.length) {
  19093. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19094. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19095. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19096. /* compare value without namespace */
  19097. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19098. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19099. if (foundValue !== notFoundValue) break;
  19100. }
  19101. }
  19102. } else {
  19103. found = _find(key, options); // fallback to default NS
  19104. }
  19105. options.isFallbackLookup = false;
  19106. }
  19107. return found;
  19108. }
  19109. function detectLanguage() {
  19110. var detectedLng;
  19111. var whitelist = o.lngWhitelist || [];
  19112. var userLngChoices = [];
  19113. // get from qs
  19114. var qsParm = [];
  19115. if (typeof window !== 'undefined') {
  19116. (function() {
  19117. var query = window.location.search.substring(1);
  19118. var params = query.split('&');
  19119. for (var i=0; i<params.length; i++) {
  19120. var pos = params[i].indexOf('=');
  19121. if (pos > 0) {
  19122. var key = params[i].substring(0,pos);
  19123. if (key == o.detectLngQS) {
  19124. userLngChoices.push(params[i].substring(pos+1));
  19125. }
  19126. }
  19127. }
  19128. })();
  19129. }
  19130. // get from cookie
  19131. if (o.useCookie && typeof document !== 'undefined') {
  19132. var c = f.cookie.read(o.cookieName);
  19133. if (c) userLngChoices.push(c);
  19134. }
  19135. // get from localStorage
  19136. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19137. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19138. }
  19139. // get from navigator
  19140. if (typeof navigator !== 'undefined') {
  19141. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19142. for (var i=0;i<navigator.languages.length;i++) {
  19143. userLngChoices.push(navigator.languages[i]);
  19144. }
  19145. }
  19146. if (navigator.userLanguage) {
  19147. userLngChoices.push(navigator.userLanguage);
  19148. }
  19149. if (navigator.language) {
  19150. userLngChoices.push(navigator.language);
  19151. }
  19152. }
  19153. (function() {
  19154. for (var i=0;i<userLngChoices.length;i++) {
  19155. var lng = userLngChoices[i];
  19156. if (lng.indexOf('-') > -1) {
  19157. var parts = lng.split('-');
  19158. lng = o.lowerCaseLng ?
  19159. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19160. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19161. }
  19162. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19163. detectedLng = lng;
  19164. break;
  19165. }
  19166. }
  19167. })();
  19168. //fallback
  19169. if (!detectedLng){
  19170. detectedLng = o.fallbackLng[0];
  19171. }
  19172. return detectedLng;
  19173. }
  19174. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19175. /* [code, name, numbers, pluralsType] */
  19176. var _rules = [
  19177. ["ach", "Acholi", [1,2], 1],
  19178. ["af", "Afrikaans",[1,2], 2],
  19179. ["ak", "Akan", [1,2], 1],
  19180. ["am", "Amharic", [1,2], 1],
  19181. ["an", "Aragonese",[1,2], 2],
  19182. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19183. ["arn", "Mapudungun",[1,2], 1],
  19184. ["ast", "Asturian", [1,2], 2],
  19185. ["ay", "Aymará", [1], 3],
  19186. ["az", "Azerbaijani",[1,2],2],
  19187. ["be", "Belarusian",[1,2,5],4],
  19188. ["bg", "Bulgarian",[1,2], 2],
  19189. ["bn", "Bengali", [1,2], 2],
  19190. ["bo", "Tibetan", [1], 3],
  19191. ["br", "Breton", [1,2], 1],
  19192. ["bs", "Bosnian", [1,2,5],4],
  19193. ["ca", "Catalan", [1,2], 2],
  19194. ["cgg", "Chiga", [1], 3],
  19195. ["cs", "Czech", [1,2,5],6],
  19196. ["csb", "Kashubian",[1,2,5],7],
  19197. ["cy", "Welsh", [1,2,3,8],8],
  19198. ["da", "Danish", [1,2], 2],
  19199. ["de", "German", [1,2], 2],
  19200. ["dev", "Development Fallback", [1,2], 2],
  19201. ["dz", "Dzongkha", [1], 3],
  19202. ["el", "Greek", [1,2], 2],
  19203. ["en", "English", [1,2], 2],
  19204. ["eo", "Esperanto",[1,2], 2],
  19205. ["es", "Spanish", [1,2], 2],
  19206. ["es_ar","Argentinean Spanish", [1,2], 2],
  19207. ["et", "Estonian", [1,2], 2],
  19208. ["eu", "Basque", [1,2], 2],
  19209. ["fa", "Persian", [1], 3],
  19210. ["fi", "Finnish", [1,2], 2],
  19211. ["fil", "Filipino", [1,2], 1],
  19212. ["fo", "Faroese", [1,2], 2],
  19213. ["fr", "French", [1,2], 9],
  19214. ["fur", "Friulian", [1,2], 2],
  19215. ["fy", "Frisian", [1,2], 2],
  19216. ["ga", "Irish", [1,2,3,7,11],10],
  19217. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19218. ["gl", "Galician", [1,2], 2],
  19219. ["gu", "Gujarati", [1,2], 2],
  19220. ["gun", "Gun", [1,2], 1],
  19221. ["ha", "Hausa", [1,2], 2],
  19222. ["he", "Hebrew", [1,2], 2],
  19223. ["hi", "Hindi", [1,2], 2],
  19224. ["hr", "Croatian", [1,2,5],4],
  19225. ["hu", "Hungarian",[1,2], 2],
  19226. ["hy", "Armenian", [1,2], 2],
  19227. ["ia", "Interlingua",[1,2],2],
  19228. ["id", "Indonesian",[1], 3],
  19229. ["is", "Icelandic",[1,2], 12],
  19230. ["it", "Italian", [1,2], 2],
  19231. ["ja", "Japanese", [1], 3],
  19232. ["jbo", "Lojban", [1], 3],
  19233. ["jv", "Javanese", [0,1], 13],
  19234. ["ka", "Georgian", [1], 3],
  19235. ["kk", "Kazakh", [1], 3],
  19236. ["km", "Khmer", [1], 3],
  19237. ["kn", "Kannada", [1,2], 2],
  19238. ["ko", "Korean", [1], 3],
  19239. ["ku", "Kurdish", [1,2], 2],
  19240. ["kw", "Cornish", [1,2,3,4],14],
  19241. ["ky", "Kyrgyz", [1], 3],
  19242. ["lb", "Letzeburgesch",[1,2],2],
  19243. ["ln", "Lingala", [1,2], 1],
  19244. ["lo", "Lao", [1], 3],
  19245. ["lt", "Lithuanian",[1,2,10],15],
  19246. ["lv", "Latvian", [1,2,0],16],
  19247. ["mai", "Maithili", [1,2], 2],
  19248. ["mfe", "Mauritian Creole",[1,2],1],
  19249. ["mg", "Malagasy", [1,2], 1],
  19250. ["mi", "Maori", [1,2], 1],
  19251. ["mk", "Macedonian",[1,2],17],
  19252. ["ml", "Malayalam",[1,2], 2],
  19253. ["mn", "Mongolian",[1,2], 2],
  19254. ["mnk", "Mandinka", [0,1,2],18],
  19255. ["mr", "Marathi", [1,2], 2],
  19256. ["ms", "Malay", [1], 3],
  19257. ["mt", "Maltese", [1,2,11,20],19],
  19258. ["nah", "Nahuatl", [1,2], 2],
  19259. ["nap", "Neapolitan",[1,2], 2],
  19260. ["nb", "Norwegian Bokmal",[1,2],2],
  19261. ["ne", "Nepali", [1,2], 2],
  19262. ["nl", "Dutch", [1,2], 2],
  19263. ["nn", "Norwegian Nynorsk",[1,2],2],
  19264. ["no", "Norwegian",[1,2], 2],
  19265. ["nso", "Northern Sotho",[1,2],2],
  19266. ["oc", "Occitan", [1,2], 1],
  19267. ["or", "Oriya", [2,1], 2],
  19268. ["pa", "Punjabi", [1,2], 2],
  19269. ["pap", "Papiamento",[1,2], 2],
  19270. ["pl", "Polish", [1,2,5],7],
  19271. ["pms", "Piemontese",[1,2], 2],
  19272. ["ps", "Pashto", [1,2], 2],
  19273. ["pt", "Portuguese",[1,2], 2],
  19274. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19275. ["rm", "Romansh", [1,2], 2],
  19276. ["ro", "Romanian", [1,2,20],20],
  19277. ["ru", "Russian", [1,2,5],4],
  19278. ["sah", "Yakut", [1], 3],
  19279. ["sco", "Scots", [1,2], 2],
  19280. ["se", "Northern Sami",[1,2], 2],
  19281. ["si", "Sinhala", [1,2], 2],
  19282. ["sk", "Slovak", [1,2,5],6],
  19283. ["sl", "Slovenian",[5,1,2,3],21],
  19284. ["so", "Somali", [1,2], 2],
  19285. ["son", "Songhay", [1,2], 2],
  19286. ["sq", "Albanian", [1,2], 2],
  19287. ["sr", "Serbian", [1,2,5],4],
  19288. ["su", "Sundanese",[1], 3],
  19289. ["sv", "Swedish", [1,2], 2],
  19290. ["sw", "Swahili", [1,2], 2],
  19291. ["ta", "Tamil", [1,2], 2],
  19292. ["te", "Telugu", [1,2], 2],
  19293. ["tg", "Tajik", [1,2], 1],
  19294. ["th", "Thai", [1], 3],
  19295. ["ti", "Tigrinya", [1,2], 1],
  19296. ["tk", "Turkmen", [1,2], 2],
  19297. ["tr", "Turkish", [1,2], 1],
  19298. ["tt", "Tatar", [1], 3],
  19299. ["ug", "Uyghur", [1], 3],
  19300. ["uk", "Ukrainian",[1,2,5],4],
  19301. ["ur", "Urdu", [1,2], 2],
  19302. ["uz", "Uzbek", [1,2], 1],
  19303. ["vi", "Vietnamese",[1], 3],
  19304. ["wa", "Walloon", [1,2], 1],
  19305. ["wo", "Wolof", [1], 3],
  19306. ["yo", "Yoruba", [1,2], 2],
  19307. ["zh", "Chinese", [1], 3]
  19308. ];
  19309. var _rulesPluralsTypes = {
  19310. 1: function(n) {return Number(n > 1);},
  19311. 2: function(n) {return Number(n != 1);},
  19312. 3: function(n) {return 0;},
  19313. 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);},
  19314. 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);},
  19315. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19316. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19317. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19318. 9: function(n) {return Number(n >= 2);},
  19319. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19320. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19321. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19322. 13: function(n) {return Number(n !== 0);},
  19323. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19324. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19325. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19326. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19327. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19328. 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);},
  19329. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19330. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19331. };
  19332. var pluralExtensions = {
  19333. rules: (function () {
  19334. var l, rules = {};
  19335. for (l=_rules.length; l-- ;) {
  19336. rules[_rules[l][0]] = {
  19337. name: _rules[l][1],
  19338. numbers: _rules[l][2],
  19339. plurals: _rulesPluralsTypes[_rules[l][3]]
  19340. }
  19341. }
  19342. return rules;
  19343. }()),
  19344. // you can add your own pluralExtensions
  19345. addRule: function(lng, obj) {
  19346. pluralExtensions.rules[lng] = obj;
  19347. },
  19348. setCurrentLng: function(lng) {
  19349. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19350. var parts = lng.split('-');
  19351. pluralExtensions.currentRule = {
  19352. lng: lng,
  19353. rule: pluralExtensions.rules[parts[0]]
  19354. };
  19355. }
  19356. },
  19357. needsPlural: function(lng, count) {
  19358. var parts = lng.split('-');
  19359. var ext;
  19360. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19361. ext = pluralExtensions.currentRule.rule;
  19362. } else {
  19363. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19364. }
  19365. if (ext && ext.numbers.length <= 1) {
  19366. return false;
  19367. } else {
  19368. return this.get(lng, count) !== 1;
  19369. }
  19370. },
  19371. get: function(lng, count) {
  19372. var parts = lng.split('-');
  19373. function getResult(l, c) {
  19374. var ext;
  19375. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19376. ext = pluralExtensions.currentRule.rule;
  19377. } else {
  19378. ext = pluralExtensions.rules[l];
  19379. }
  19380. if (ext) {
  19381. var i;
  19382. if (ext.noAbs) {
  19383. i = ext.plurals(c);
  19384. } else {
  19385. i = ext.plurals(Math.abs(c));
  19386. }
  19387. var number = ext.numbers[i];
  19388. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19389. if (number === 2) {
  19390. number = -1; // regular plural
  19391. } else if (number === 1) {
  19392. number = 1; // singular
  19393. }
  19394. }//console.log(count + '-' + number);
  19395. return number;
  19396. } else {
  19397. return c === 1 ? '1' : '-1';
  19398. }
  19399. }
  19400. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19401. }
  19402. };
  19403. var postProcessors = {};
  19404. var addPostProcessor = function(name, fc) {
  19405. postProcessors[name] = fc;
  19406. };
  19407. // sprintf support
  19408. var sprintf = (function() {
  19409. function get_type(variable) {
  19410. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19411. }
  19412. function str_repeat(input, multiplier) {
  19413. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19414. return output.join('');
  19415. }
  19416. var str_format = function() {
  19417. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19418. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19419. }
  19420. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19421. };
  19422. str_format.format = function(parse_tree, argv) {
  19423. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19424. for (i = 0; i < tree_length; i++) {
  19425. node_type = get_type(parse_tree[i]);
  19426. if (node_type === 'string') {
  19427. output.push(parse_tree[i]);
  19428. }
  19429. else if (node_type === 'array') {
  19430. match = parse_tree[i]; // convenience purposes only
  19431. if (match[2]) { // keyword argument
  19432. arg = argv[cursor];
  19433. for (k = 0; k < match[2].length; k++) {
  19434. if (!arg.hasOwnProperty(match[2][k])) {
  19435. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19436. }
  19437. arg = arg[match[2][k]];
  19438. }
  19439. }
  19440. else if (match[1]) { // positional argument (explicit)
  19441. arg = argv[match[1]];
  19442. }
  19443. else { // positional argument (implicit)
  19444. arg = argv[cursor++];
  19445. }
  19446. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19447. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19448. }
  19449. switch (match[8]) {
  19450. case 'b': arg = arg.toString(2); break;
  19451. case 'c': arg = String.fromCharCode(arg); break;
  19452. case 'd': arg = parseInt(arg, 10); break;
  19453. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19454. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19455. case 'o': arg = arg.toString(8); break;
  19456. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19457. case 'u': arg = Math.abs(arg); break;
  19458. case 'x': arg = arg.toString(16); break;
  19459. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19460. }
  19461. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19462. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19463. pad_length = match[6] - String(arg).length;
  19464. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19465. output.push(match[5] ? arg + pad : pad + arg);
  19466. }
  19467. }
  19468. return output.join('');
  19469. };
  19470. str_format.cache = {};
  19471. str_format.parse = function(fmt) {
  19472. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19473. while (_fmt) {
  19474. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19475. parse_tree.push(match[0]);
  19476. }
  19477. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19478. parse_tree.push('%');
  19479. }
  19480. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19481. if (match[2]) {
  19482. arg_names |= 1;
  19483. var field_list = [], replacement_field = match[2], field_match = [];
  19484. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19485. field_list.push(field_match[1]);
  19486. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19487. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19488. field_list.push(field_match[1]);
  19489. }
  19490. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19491. field_list.push(field_match[1]);
  19492. }
  19493. else {
  19494. throw('[sprintf] huh?');
  19495. }
  19496. }
  19497. }
  19498. else {
  19499. throw('[sprintf] huh?');
  19500. }
  19501. match[2] = field_list;
  19502. }
  19503. else {
  19504. arg_names |= 2;
  19505. }
  19506. if (arg_names === 3) {
  19507. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19508. }
  19509. parse_tree.push(match);
  19510. }
  19511. else {
  19512. throw('[sprintf] huh?');
  19513. }
  19514. _fmt = _fmt.substring(match[0].length);
  19515. }
  19516. return parse_tree;
  19517. };
  19518. return str_format;
  19519. })();
  19520. var vsprintf = function(fmt, argv) {
  19521. argv.unshift(fmt);
  19522. return sprintf.apply(null, argv);
  19523. };
  19524. addPostProcessor("sprintf", function(val, key, opts) {
  19525. if (!opts.sprintf) return val;
  19526. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19527. return vsprintf(val, opts.sprintf);
  19528. } else if (typeof opts.sprintf === 'object') {
  19529. return sprintf(val, opts.sprintf);
  19530. }
  19531. return val;
  19532. });
  19533. // public api interface
  19534. i18n.init = init;
  19535. i18n.setLng = setLng;
  19536. i18n.preload = preload;
  19537. i18n.addResourceBundle = addResourceBundle;
  19538. i18n.hasResourceBundle = hasResourceBundle;
  19539. i18n.addResource = addResource;
  19540. i18n.addResources = addResources;
  19541. i18n.removeResourceBundle = removeResourceBundle;
  19542. i18n.loadNamespace = loadNamespace;
  19543. i18n.loadNamespaces = loadNamespaces;
  19544. i18n.setDefaultNamespace = setDefaultNamespace;
  19545. i18n.t = translate;
  19546. i18n.translate = translate;
  19547. i18n.exists = exists;
  19548. i18n.detectLanguage = f.detectLanguage;
  19549. i18n.pluralExtensions = pluralExtensions;
  19550. i18n.sync = sync;
  19551. i18n.functions = f;
  19552. i18n.lng = lng;
  19553. i18n.addPostProcessor = addPostProcessor;
  19554. i18n.options = o;
  19555. })();
  19556. },{"jquery":"jquery"}],70:[function(require,module,exports){
  19557. // Top level file is just a mixin of submodules & constants
  19558. 'use strict';
  19559. var assign = require('./lib/utils/common').assign;
  19560. var deflate = require('./lib/deflate');
  19561. var inflate = require('./lib/inflate');
  19562. var constants = require('./lib/zlib/constants');
  19563. var pako = {};
  19564. assign(pako, deflate, inflate, constants);
  19565. module.exports = pako;
  19566. },{"./lib/deflate":71,"./lib/inflate":72,"./lib/utils/common":73,"./lib/zlib/constants":76}],71:[function(require,module,exports){
  19567. 'use strict';
  19568. var zlib_deflate = require('./zlib/deflate.js');
  19569. var utils = require('./utils/common');
  19570. var strings = require('./utils/strings');
  19571. var msg = require('./zlib/messages');
  19572. var zstream = require('./zlib/zstream');
  19573. var toString = Object.prototype.toString;
  19574. /* Public constants ==========================================================*/
  19575. /* ===========================================================================*/
  19576. var Z_NO_FLUSH = 0;
  19577. var Z_FINISH = 4;
  19578. var Z_OK = 0;
  19579. var Z_STREAM_END = 1;
  19580. var Z_SYNC_FLUSH = 2;
  19581. var Z_DEFAULT_COMPRESSION = -1;
  19582. var Z_DEFAULT_STRATEGY = 0;
  19583. var Z_DEFLATED = 8;
  19584. /* ===========================================================================*/
  19585. /**
  19586. * class Deflate
  19587. *
  19588. * Generic JS-style wrapper for zlib calls. If you don't need
  19589. * streaming behaviour - use more simple functions: [[deflate]],
  19590. * [[deflateRaw]] and [[gzip]].
  19591. **/
  19592. /* internal
  19593. * Deflate.chunks -> Array
  19594. *
  19595. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19596. **/
  19597. /**
  19598. * Deflate.result -> Uint8Array|Array
  19599. *
  19600. * Compressed result, generated by default [[Deflate#onData]]
  19601. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19602. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19603. * push a chunk with explicit flush (call [[Deflate#push]] with
  19604. * `Z_SYNC_FLUSH` param).
  19605. **/
  19606. /**
  19607. * Deflate.err -> Number
  19608. *
  19609. * Error code after deflate finished. 0 (Z_OK) on success.
  19610. * You will not need it in real life, because deflate errors
  19611. * are possible only on wrong options or bad `onData` / `onEnd`
  19612. * custom handlers.
  19613. **/
  19614. /**
  19615. * Deflate.msg -> String
  19616. *
  19617. * Error message, if [[Deflate.err]] != 0
  19618. **/
  19619. /**
  19620. * new Deflate(options)
  19621. * - options (Object): zlib deflate options.
  19622. *
  19623. * Creates new deflator instance with specified params. Throws exception
  19624. * on bad params. Supported options:
  19625. *
  19626. * - `level`
  19627. * - `windowBits`
  19628. * - `memLevel`
  19629. * - `strategy`
  19630. *
  19631. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19632. * for more information on these.
  19633. *
  19634. * Additional options, for internal needs:
  19635. *
  19636. * - `chunkSize` - size of generated data chunks (16K by default)
  19637. * - `raw` (Boolean) - do raw deflate
  19638. * - `gzip` (Boolean) - create gzip wrapper
  19639. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19640. * (each char code [0..255])
  19641. * - `header` (Object) - custom header for gzip
  19642. * - `text` (Boolean) - true if compressed data believed to be text
  19643. * - `time` (Number) - modification time, unix timestamp
  19644. * - `os` (Number) - operation system code
  19645. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19646. * - `name` (String) - file name (binary string)
  19647. * - `comment` (String) - comment (binary string)
  19648. * - `hcrc` (Boolean) - true if header crc should be added
  19649. *
  19650. * ##### Example:
  19651. *
  19652. * ```javascript
  19653. * var pako = require('pako')
  19654. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19655. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19656. *
  19657. * var deflate = new pako.Deflate({ level: 3});
  19658. *
  19659. * deflate.push(chunk1, false);
  19660. * deflate.push(chunk2, true); // true -> last chunk
  19661. *
  19662. * if (deflate.err) { throw new Error(deflate.err); }
  19663. *
  19664. * console.log(deflate.result);
  19665. * ```
  19666. **/
  19667. var Deflate = function(options) {
  19668. this.options = utils.assign({
  19669. level: Z_DEFAULT_COMPRESSION,
  19670. method: Z_DEFLATED,
  19671. chunkSize: 16384,
  19672. windowBits: 15,
  19673. memLevel: 8,
  19674. strategy: Z_DEFAULT_STRATEGY,
  19675. to: ''
  19676. }, options || {});
  19677. var opt = this.options;
  19678. if (opt.raw && (opt.windowBits > 0)) {
  19679. opt.windowBits = -opt.windowBits;
  19680. }
  19681. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19682. opt.windowBits += 16;
  19683. }
  19684. this.err = 0; // error code, if happens (0 = Z_OK)
  19685. this.msg = ''; // error message
  19686. this.ended = false; // used to avoid multiple onEnd() calls
  19687. this.chunks = []; // chunks of compressed data
  19688. this.strm = new zstream();
  19689. this.strm.avail_out = 0;
  19690. var status = zlib_deflate.deflateInit2(
  19691. this.strm,
  19692. opt.level,
  19693. opt.method,
  19694. opt.windowBits,
  19695. opt.memLevel,
  19696. opt.strategy
  19697. );
  19698. if (status !== Z_OK) {
  19699. throw new Error(msg[status]);
  19700. }
  19701. if (opt.header) {
  19702. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19703. }
  19704. };
  19705. /**
  19706. * Deflate#push(data[, mode]) -> Boolean
  19707. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19708. * converted to utf8 byte sequence.
  19709. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19710. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19711. *
  19712. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19713. * new compressed chunks. Returns `true` on success. The last data block must have
  19714. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19715. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19716. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19717. *
  19718. * On fail call [[Deflate#onEnd]] with error code and return false.
  19719. *
  19720. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19721. * array format is detected automatically). Also, don't skip last param and always
  19722. * use the same type in your code (boolean or number). That will improve JS speed.
  19723. *
  19724. * For regular `Array`-s make sure all elements are [0..255].
  19725. *
  19726. * ##### Example
  19727. *
  19728. * ```javascript
  19729. * push(chunk, false); // push one of data chunks
  19730. * ...
  19731. * push(chunk, true); // push last chunk
  19732. * ```
  19733. **/
  19734. Deflate.prototype.push = function(data, mode) {
  19735. var strm = this.strm;
  19736. var chunkSize = this.options.chunkSize;
  19737. var status, _mode;
  19738. if (this.ended) { return false; }
  19739. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19740. // Convert data if needed
  19741. if (typeof data === 'string') {
  19742. // If we need to compress text, change encoding to utf8.
  19743. strm.input = strings.string2buf(data);
  19744. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19745. strm.input = new Uint8Array(data);
  19746. } else {
  19747. strm.input = data;
  19748. }
  19749. strm.next_in = 0;
  19750. strm.avail_in = strm.input.length;
  19751. do {
  19752. if (strm.avail_out === 0) {
  19753. strm.output = new utils.Buf8(chunkSize);
  19754. strm.next_out = 0;
  19755. strm.avail_out = chunkSize;
  19756. }
  19757. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19758. if (status !== Z_STREAM_END && status !== Z_OK) {
  19759. this.onEnd(status);
  19760. this.ended = true;
  19761. return false;
  19762. }
  19763. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19764. if (this.options.to === 'string') {
  19765. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19766. } else {
  19767. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19768. }
  19769. }
  19770. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19771. // Finalize on the last chunk.
  19772. if (_mode === Z_FINISH) {
  19773. status = zlib_deflate.deflateEnd(this.strm);
  19774. this.onEnd(status);
  19775. this.ended = true;
  19776. return status === Z_OK;
  19777. }
  19778. // callback interim results if Z_SYNC_FLUSH.
  19779. if (_mode === Z_SYNC_FLUSH) {
  19780. this.onEnd(Z_OK);
  19781. strm.avail_out = 0;
  19782. return true;
  19783. }
  19784. return true;
  19785. };
  19786. /**
  19787. * Deflate#onData(chunk) -> Void
  19788. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19789. * on js engine support. When string output requested, each chunk
  19790. * will be string.
  19791. *
  19792. * By default, stores data blocks in `chunks[]` property and glue
  19793. * those in `onEnd`. Override this handler, if you need another behaviour.
  19794. **/
  19795. Deflate.prototype.onData = function(chunk) {
  19796. this.chunks.push(chunk);
  19797. };
  19798. /**
  19799. * Deflate#onEnd(status) -> Void
  19800. * - status (Number): deflate status. 0 (Z_OK) on success,
  19801. * other if not.
  19802. *
  19803. * Called once after you tell deflate that the input stream is
  19804. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19805. * or if an error happened. By default - join collected chunks,
  19806. * free memory and fill `results` / `err` properties.
  19807. **/
  19808. Deflate.prototype.onEnd = function(status) {
  19809. // On success - join
  19810. if (status === Z_OK) {
  19811. if (this.options.to === 'string') {
  19812. this.result = this.chunks.join('');
  19813. } else {
  19814. this.result = utils.flattenChunks(this.chunks);
  19815. }
  19816. }
  19817. this.chunks = [];
  19818. this.err = status;
  19819. this.msg = this.strm.msg;
  19820. };
  19821. /**
  19822. * deflate(data[, options]) -> Uint8Array|Array|String
  19823. * - data (Uint8Array|Array|String): input data to compress.
  19824. * - options (Object): zlib deflate options.
  19825. *
  19826. * Compress `data` with deflate alrorythm and `options`.
  19827. *
  19828. * Supported options are:
  19829. *
  19830. * - level
  19831. * - windowBits
  19832. * - memLevel
  19833. * - strategy
  19834. *
  19835. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19836. * for more information on these.
  19837. *
  19838. * Sugar (options):
  19839. *
  19840. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19841. * negative windowBits implicitly.
  19842. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19843. * (each char code [0..255])
  19844. *
  19845. * ##### Example:
  19846. *
  19847. * ```javascript
  19848. * var pako = require('pako')
  19849. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19850. *
  19851. * console.log(pako.deflate(data));
  19852. * ```
  19853. **/
  19854. function deflate(input, options) {
  19855. var deflator = new Deflate(options);
  19856. deflator.push(input, true);
  19857. // That will never happens, if you don't cheat with options :)
  19858. if (deflator.err) { throw deflator.msg; }
  19859. return deflator.result;
  19860. }
  19861. /**
  19862. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19863. * - data (Uint8Array|Array|String): input data to compress.
  19864. * - options (Object): zlib deflate options.
  19865. *
  19866. * The same as [[deflate]], but creates raw data, without wrapper
  19867. * (header and adler32 crc).
  19868. **/
  19869. function deflateRaw(input, options) {
  19870. options = options || {};
  19871. options.raw = true;
  19872. return deflate(input, options);
  19873. }
  19874. /**
  19875. * gzip(data[, options]) -> Uint8Array|Array|String
  19876. * - data (Uint8Array|Array|String): input data to compress.
  19877. * - options (Object): zlib deflate options.
  19878. *
  19879. * The same as [[deflate]], but create gzip wrapper instead of
  19880. * deflate one.
  19881. **/
  19882. function gzip(input, options) {
  19883. options = options || {};
  19884. options.gzip = true;
  19885. return deflate(input, options);
  19886. }
  19887. exports.Deflate = Deflate;
  19888. exports.deflate = deflate;
  19889. exports.deflateRaw = deflateRaw;
  19890. exports.gzip = gzip;
  19891. },{"./utils/common":73,"./utils/strings":74,"./zlib/deflate.js":78,"./zlib/messages":83,"./zlib/zstream":85}],72:[function(require,module,exports){
  19892. 'use strict';
  19893. var zlib_inflate = require('./zlib/inflate.js');
  19894. var utils = require('./utils/common');
  19895. var strings = require('./utils/strings');
  19896. var c = require('./zlib/constants');
  19897. var msg = require('./zlib/messages');
  19898. var zstream = require('./zlib/zstream');
  19899. var gzheader = require('./zlib/gzheader');
  19900. var toString = Object.prototype.toString;
  19901. /**
  19902. * class Inflate
  19903. *
  19904. * Generic JS-style wrapper for zlib calls. If you don't need
  19905. * streaming behaviour - use more simple functions: [[inflate]]
  19906. * and [[inflateRaw]].
  19907. **/
  19908. /* internal
  19909. * inflate.chunks -> Array
  19910. *
  19911. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19912. **/
  19913. /**
  19914. * Inflate.result -> Uint8Array|Array|String
  19915. *
  19916. * Uncompressed result, generated by default [[Inflate#onData]]
  19917. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19918. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19919. * push a chunk with explicit flush (call [[Inflate#push]] with
  19920. * `Z_SYNC_FLUSH` param).
  19921. **/
  19922. /**
  19923. * Inflate.err -> Number
  19924. *
  19925. * Error code after inflate finished. 0 (Z_OK) on success.
  19926. * Should be checked if broken data possible.
  19927. **/
  19928. /**
  19929. * Inflate.msg -> String
  19930. *
  19931. * Error message, if [[Inflate.err]] != 0
  19932. **/
  19933. /**
  19934. * new Inflate(options)
  19935. * - options (Object): zlib inflate options.
  19936. *
  19937. * Creates new inflator instance with specified params. Throws exception
  19938. * on bad params. Supported options:
  19939. *
  19940. * - `windowBits`
  19941. *
  19942. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19943. * for more information on these.
  19944. *
  19945. * Additional options, for internal needs:
  19946. *
  19947. * - `chunkSize` - size of generated data chunks (16K by default)
  19948. * - `raw` (Boolean) - do raw inflate
  19949. * - `to` (String) - if equal to 'string', then result will be converted
  19950. * from utf8 to utf16 (javascript) string. When string output requested,
  19951. * chunk length can differ from `chunkSize`, depending on content.
  19952. *
  19953. * By default, when no options set, autodetect deflate/gzip data format via
  19954. * wrapper header.
  19955. *
  19956. * ##### Example:
  19957. *
  19958. * ```javascript
  19959. * var pako = require('pako')
  19960. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19961. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19962. *
  19963. * var inflate = new pako.Inflate({ level: 3});
  19964. *
  19965. * inflate.push(chunk1, false);
  19966. * inflate.push(chunk2, true); // true -> last chunk
  19967. *
  19968. * if (inflate.err) { throw new Error(inflate.err); }
  19969. *
  19970. * console.log(inflate.result);
  19971. * ```
  19972. **/
  19973. var Inflate = function(options) {
  19974. this.options = utils.assign({
  19975. chunkSize: 16384,
  19976. windowBits: 0,
  19977. to: ''
  19978. }, options || {});
  19979. var opt = this.options;
  19980. // Force window size for `raw` data, if not set directly,
  19981. // because we have no header for autodetect.
  19982. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19983. opt.windowBits = -opt.windowBits;
  19984. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19985. }
  19986. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19987. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19988. !(options && options.windowBits)) {
  19989. opt.windowBits += 32;
  19990. }
  19991. // Gzip header has no info about windows size, we can do autodetect only
  19992. // for deflate. So, if window size not set, force it to max when gzip possible
  19993. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19994. // bit 3 (16) -> gzipped data
  19995. // bit 4 (32) -> autodetect gzip/deflate
  19996. if ((opt.windowBits & 15) === 0) {
  19997. opt.windowBits |= 15;
  19998. }
  19999. }
  20000. this.err = 0; // error code, if happens (0 = Z_OK)
  20001. this.msg = ''; // error message
  20002. this.ended = false; // used to avoid multiple onEnd() calls
  20003. this.chunks = []; // chunks of compressed data
  20004. this.strm = new zstream();
  20005. this.strm.avail_out = 0;
  20006. var status = zlib_inflate.inflateInit2(
  20007. this.strm,
  20008. opt.windowBits
  20009. );
  20010. if (status !== c.Z_OK) {
  20011. throw new Error(msg[status]);
  20012. }
  20013. this.header = new gzheader();
  20014. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20015. };
  20016. /**
  20017. * Inflate#push(data[, mode]) -> Boolean
  20018. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20019. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20020. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20021. *
  20022. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20023. * new output chunks. Returns `true` on success. The last data block must have
  20024. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20025. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20026. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20027. *
  20028. * On fail call [[Inflate#onEnd]] with error code and return false.
  20029. *
  20030. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20031. * format is detected automatically). Also, don't skip last param and always
  20032. * use the same type in your code (boolean or number). That will improve JS speed.
  20033. *
  20034. * For regular `Array`-s make sure all elements are [0..255].
  20035. *
  20036. * ##### Example
  20037. *
  20038. * ```javascript
  20039. * push(chunk, false); // push one of data chunks
  20040. * ...
  20041. * push(chunk, true); // push last chunk
  20042. * ```
  20043. **/
  20044. Inflate.prototype.push = function(data, mode) {
  20045. var strm = this.strm;
  20046. var chunkSize = this.options.chunkSize;
  20047. var status, _mode;
  20048. var next_out_utf8, tail, utf8str;
  20049. if (this.ended) { return false; }
  20050. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20051. // Convert data if needed
  20052. if (typeof data === 'string') {
  20053. // Only binary strings can be decompressed on practice
  20054. strm.input = strings.binstring2buf(data);
  20055. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20056. strm.input = new Uint8Array(data);
  20057. } else {
  20058. strm.input = data;
  20059. }
  20060. strm.next_in = 0;
  20061. strm.avail_in = strm.input.length;
  20062. do {
  20063. if (strm.avail_out === 0) {
  20064. strm.output = new utils.Buf8(chunkSize);
  20065. strm.next_out = 0;
  20066. strm.avail_out = chunkSize;
  20067. }
  20068. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20069. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20070. this.onEnd(status);
  20071. this.ended = true;
  20072. return false;
  20073. }
  20074. if (strm.next_out) {
  20075. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20076. if (this.options.to === 'string') {
  20077. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20078. tail = strm.next_out - next_out_utf8;
  20079. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20080. // move tail
  20081. strm.next_out = tail;
  20082. strm.avail_out = chunkSize - tail;
  20083. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20084. this.onData(utf8str);
  20085. } else {
  20086. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20087. }
  20088. }
  20089. }
  20090. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20091. if (status === c.Z_STREAM_END) {
  20092. _mode = c.Z_FINISH;
  20093. }
  20094. // Finalize on the last chunk.
  20095. if (_mode === c.Z_FINISH) {
  20096. status = zlib_inflate.inflateEnd(this.strm);
  20097. this.onEnd(status);
  20098. this.ended = true;
  20099. return status === c.Z_OK;
  20100. }
  20101. // callback interim results if Z_SYNC_FLUSH.
  20102. if (_mode === c.Z_SYNC_FLUSH) {
  20103. this.onEnd(c.Z_OK);
  20104. strm.avail_out = 0;
  20105. return true;
  20106. }
  20107. return true;
  20108. };
  20109. /**
  20110. * Inflate#onData(chunk) -> Void
  20111. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20112. * on js engine support. When string output requested, each chunk
  20113. * will be string.
  20114. *
  20115. * By default, stores data blocks in `chunks[]` property and glue
  20116. * those in `onEnd`. Override this handler, if you need another behaviour.
  20117. **/
  20118. Inflate.prototype.onData = function(chunk) {
  20119. this.chunks.push(chunk);
  20120. };
  20121. /**
  20122. * Inflate#onEnd(status) -> Void
  20123. * - status (Number): inflate status. 0 (Z_OK) on success,
  20124. * other if not.
  20125. *
  20126. * Called either after you tell inflate that the input stream is
  20127. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20128. * or if an error happened. By default - join collected chunks,
  20129. * free memory and fill `results` / `err` properties.
  20130. **/
  20131. Inflate.prototype.onEnd = function(status) {
  20132. // On success - join
  20133. if (status === c.Z_OK) {
  20134. if (this.options.to === 'string') {
  20135. // Glue & convert here, until we teach pako to send
  20136. // utf8 alligned strings to onData
  20137. this.result = this.chunks.join('');
  20138. } else {
  20139. this.result = utils.flattenChunks(this.chunks);
  20140. }
  20141. }
  20142. this.chunks = [];
  20143. this.err = status;
  20144. this.msg = this.strm.msg;
  20145. };
  20146. /**
  20147. * inflate(data[, options]) -> Uint8Array|Array|String
  20148. * - data (Uint8Array|Array|String): input data to decompress.
  20149. * - options (Object): zlib inflate options.
  20150. *
  20151. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20152. * format via wrapper header by default. That's why we don't provide
  20153. * separate `ungzip` method.
  20154. *
  20155. * Supported options are:
  20156. *
  20157. * - windowBits
  20158. *
  20159. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20160. * for more information.
  20161. *
  20162. * Sugar (options):
  20163. *
  20164. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20165. * negative windowBits implicitly.
  20166. * - `to` (String) - if equal to 'string', then result will be converted
  20167. * from utf8 to utf16 (javascript) string. When string output requested,
  20168. * chunk length can differ from `chunkSize`, depending on content.
  20169. *
  20170. *
  20171. * ##### Example:
  20172. *
  20173. * ```javascript
  20174. * var pako = require('pako')
  20175. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20176. * , output;
  20177. *
  20178. * try {
  20179. * output = pako.inflate(input);
  20180. * } catch (err)
  20181. * console.log(err);
  20182. * }
  20183. * ```
  20184. **/
  20185. function inflate(input, options) {
  20186. var inflator = new Inflate(options);
  20187. inflator.push(input, true);
  20188. // That will never happens, if you don't cheat with options :)
  20189. if (inflator.err) { throw inflator.msg; }
  20190. return inflator.result;
  20191. }
  20192. /**
  20193. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20194. * - data (Uint8Array|Array|String): input data to decompress.
  20195. * - options (Object): zlib inflate options.
  20196. *
  20197. * The same as [[inflate]], but creates raw data, without wrapper
  20198. * (header and adler32 crc).
  20199. **/
  20200. function inflateRaw(input, options) {
  20201. options = options || {};
  20202. options.raw = true;
  20203. return inflate(input, options);
  20204. }
  20205. /**
  20206. * ungzip(data[, options]) -> Uint8Array|Array|String
  20207. * - data (Uint8Array|Array|String): input data to decompress.
  20208. * - options (Object): zlib inflate options.
  20209. *
  20210. * Just shortcut to [[inflate]], because it autodetects format
  20211. * by header.content. Done for convenience.
  20212. **/
  20213. exports.Inflate = Inflate;
  20214. exports.inflate = inflate;
  20215. exports.inflateRaw = inflateRaw;
  20216. exports.ungzip = inflate;
  20217. },{"./utils/common":73,"./utils/strings":74,"./zlib/constants":76,"./zlib/gzheader":79,"./zlib/inflate.js":81,"./zlib/messages":83,"./zlib/zstream":85}],73:[function(require,module,exports){
  20218. 'use strict';
  20219. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20220. (typeof Uint16Array !== 'undefined') &&
  20221. (typeof Int32Array !== 'undefined');
  20222. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20223. var sources = Array.prototype.slice.call(arguments, 1);
  20224. while (sources.length) {
  20225. var source = sources.shift();
  20226. if (!source) { continue; }
  20227. if (typeof source !== 'object') {
  20228. throw new TypeError(source + 'must be non-object');
  20229. }
  20230. for (var p in source) {
  20231. if (source.hasOwnProperty(p)) {
  20232. obj[p] = source[p];
  20233. }
  20234. }
  20235. }
  20236. return obj;
  20237. };
  20238. // reduce buffer size, avoiding mem copy
  20239. exports.shrinkBuf = function (buf, size) {
  20240. if (buf.length === size) { return buf; }
  20241. if (buf.subarray) { return buf.subarray(0, size); }
  20242. buf.length = size;
  20243. return buf;
  20244. };
  20245. var fnTyped = {
  20246. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20247. if (src.subarray && dest.subarray) {
  20248. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20249. return;
  20250. }
  20251. // Fallback to ordinary array
  20252. for (var i=0; i<len; i++) {
  20253. dest[dest_offs + i] = src[src_offs + i];
  20254. }
  20255. },
  20256. // Join array of chunks to single array.
  20257. flattenChunks: function(chunks) {
  20258. var i, l, len, pos, chunk, result;
  20259. // calculate data length
  20260. len = 0;
  20261. for (i=0, l=chunks.length; i<l; i++) {
  20262. len += chunks[i].length;
  20263. }
  20264. // join chunks
  20265. result = new Uint8Array(len);
  20266. pos = 0;
  20267. for (i=0, l=chunks.length; i<l; i++) {
  20268. chunk = chunks[i];
  20269. result.set(chunk, pos);
  20270. pos += chunk.length;
  20271. }
  20272. return result;
  20273. }
  20274. };
  20275. var fnUntyped = {
  20276. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20277. for (var i=0; i<len; i++) {
  20278. dest[dest_offs + i] = src[src_offs + i];
  20279. }
  20280. },
  20281. // Join array of chunks to single array.
  20282. flattenChunks: function(chunks) {
  20283. return [].concat.apply([], chunks);
  20284. }
  20285. };
  20286. // Enable/Disable typed arrays use, for testing
  20287. //
  20288. exports.setTyped = function (on) {
  20289. if (on) {
  20290. exports.Buf8 = Uint8Array;
  20291. exports.Buf16 = Uint16Array;
  20292. exports.Buf32 = Int32Array;
  20293. exports.assign(exports, fnTyped);
  20294. } else {
  20295. exports.Buf8 = Array;
  20296. exports.Buf16 = Array;
  20297. exports.Buf32 = Array;
  20298. exports.assign(exports, fnUntyped);
  20299. }
  20300. };
  20301. exports.setTyped(TYPED_OK);
  20302. },{}],74:[function(require,module,exports){
  20303. // String encode/decode helpers
  20304. 'use strict';
  20305. var utils = require('./common');
  20306. // Quick check if we can use fast array to bin string conversion
  20307. //
  20308. // - apply(Array) can fail on Android 2.2
  20309. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20310. //
  20311. var STR_APPLY_OK = true;
  20312. var STR_APPLY_UIA_OK = true;
  20313. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20314. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20315. // Table with utf8 lengths (calculated by first byte of sequence)
  20316. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20317. // because max possible codepoint is 0x10ffff
  20318. var _utf8len = new utils.Buf8(256);
  20319. for (var q=0; q<256; q++) {
  20320. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20321. }
  20322. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20323. // convert string to array (typed, when possible)
  20324. exports.string2buf = function (str) {
  20325. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20326. // count binary size
  20327. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20328. c = str.charCodeAt(m_pos);
  20329. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20330. c2 = str.charCodeAt(m_pos+1);
  20331. if ((c2 & 0xfc00) === 0xdc00) {
  20332. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20333. m_pos++;
  20334. }
  20335. }
  20336. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20337. }
  20338. // allocate buffer
  20339. buf = new utils.Buf8(buf_len);
  20340. // convert
  20341. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20342. c = str.charCodeAt(m_pos);
  20343. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20344. c2 = str.charCodeAt(m_pos+1);
  20345. if ((c2 & 0xfc00) === 0xdc00) {
  20346. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20347. m_pos++;
  20348. }
  20349. }
  20350. if (c < 0x80) {
  20351. /* one byte */
  20352. buf[i++] = c;
  20353. } else if (c < 0x800) {
  20354. /* two bytes */
  20355. buf[i++] = 0xC0 | (c >>> 6);
  20356. buf[i++] = 0x80 | (c & 0x3f);
  20357. } else if (c < 0x10000) {
  20358. /* three bytes */
  20359. buf[i++] = 0xE0 | (c >>> 12);
  20360. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20361. buf[i++] = 0x80 | (c & 0x3f);
  20362. } else {
  20363. /* four bytes */
  20364. buf[i++] = 0xf0 | (c >>> 18);
  20365. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20366. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20367. buf[i++] = 0x80 | (c & 0x3f);
  20368. }
  20369. }
  20370. return buf;
  20371. };
  20372. // Helper (used in 2 places)
  20373. function buf2binstring(buf, len) {
  20374. // use fallback for big arrays to avoid stack overflow
  20375. if (len < 65537) {
  20376. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20377. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20378. }
  20379. }
  20380. var result = '';
  20381. for (var i=0; i < len; i++) {
  20382. result += String.fromCharCode(buf[i]);
  20383. }
  20384. return result;
  20385. }
  20386. // Convert byte array to binary string
  20387. exports.buf2binstring = function(buf) {
  20388. return buf2binstring(buf, buf.length);
  20389. };
  20390. // Convert binary string (typed, when possible)
  20391. exports.binstring2buf = function(str) {
  20392. var buf = new utils.Buf8(str.length);
  20393. for (var i=0, len=buf.length; i < len; i++) {
  20394. buf[i] = str.charCodeAt(i);
  20395. }
  20396. return buf;
  20397. };
  20398. // convert array to string
  20399. exports.buf2string = function (buf, max) {
  20400. var i, out, c, c_len;
  20401. var len = max || buf.length;
  20402. // Reserve max possible length (2 words per char)
  20403. // NB: by unknown reasons, Array is significantly faster for
  20404. // String.fromCharCode.apply than Uint16Array.
  20405. var utf16buf = new Array(len*2);
  20406. for (out=0, i=0; i<len;) {
  20407. c = buf[i++];
  20408. // quick process ascii
  20409. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20410. c_len = _utf8len[c];
  20411. // skip 5 & 6 byte codes
  20412. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20413. // apply mask on first byte
  20414. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20415. // join the rest
  20416. while (c_len > 1 && i < len) {
  20417. c = (c << 6) | (buf[i++] & 0x3f);
  20418. c_len--;
  20419. }
  20420. // terminated by end of string?
  20421. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20422. if (c < 0x10000) {
  20423. utf16buf[out++] = c;
  20424. } else {
  20425. c -= 0x10000;
  20426. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20427. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20428. }
  20429. }
  20430. return buf2binstring(utf16buf, out);
  20431. };
  20432. // Calculate max possible position in utf8 buffer,
  20433. // that will not break sequence. If that's not possible
  20434. // - (very small limits) return max size as is.
  20435. //
  20436. // buf[] - utf8 bytes array
  20437. // max - length limit (mandatory);
  20438. exports.utf8border = function(buf, max) {
  20439. var pos;
  20440. max = max || buf.length;
  20441. if (max > buf.length) { max = buf.length; }
  20442. // go back from last position, until start of sequence found
  20443. pos = max-1;
  20444. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20445. // Fuckup - very small and broken sequence,
  20446. // return max, because we should return something anyway.
  20447. if (pos < 0) { return max; }
  20448. // If we came to start of buffer - that means vuffer is too small,
  20449. // return max too.
  20450. if (pos === 0) { return max; }
  20451. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20452. };
  20453. },{"./common":73}],75:[function(require,module,exports){
  20454. 'use strict';
  20455. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20456. // It doesn't worth to make additional optimizationa as in original.
  20457. // Small size is preferable.
  20458. function adler32(adler, buf, len, pos) {
  20459. var s1 = (adler & 0xffff) |0,
  20460. s2 = ((adler >>> 16) & 0xffff) |0,
  20461. n = 0;
  20462. while (len !== 0) {
  20463. // Set limit ~ twice less than 5552, to keep
  20464. // s2 in 31-bits, because we force signed ints.
  20465. // in other case %= will fail.
  20466. n = len > 2000 ? 2000 : len;
  20467. len -= n;
  20468. do {
  20469. s1 = (s1 + buf[pos++]) |0;
  20470. s2 = (s2 + s1) |0;
  20471. } while (--n);
  20472. s1 %= 65521;
  20473. s2 %= 65521;
  20474. }
  20475. return (s1 | (s2 << 16)) |0;
  20476. }
  20477. module.exports = adler32;
  20478. },{}],76:[function(require,module,exports){
  20479. module.exports = {
  20480. /* Allowed flush values; see deflate() and inflate() below for details */
  20481. Z_NO_FLUSH: 0,
  20482. Z_PARTIAL_FLUSH: 1,
  20483. Z_SYNC_FLUSH: 2,
  20484. Z_FULL_FLUSH: 3,
  20485. Z_FINISH: 4,
  20486. Z_BLOCK: 5,
  20487. Z_TREES: 6,
  20488. /* Return codes for the compression/decompression functions. Negative values
  20489. * are errors, positive values are used for special but normal events.
  20490. */
  20491. Z_OK: 0,
  20492. Z_STREAM_END: 1,
  20493. Z_NEED_DICT: 2,
  20494. Z_ERRNO: -1,
  20495. Z_STREAM_ERROR: -2,
  20496. Z_DATA_ERROR: -3,
  20497. //Z_MEM_ERROR: -4,
  20498. Z_BUF_ERROR: -5,
  20499. //Z_VERSION_ERROR: -6,
  20500. /* compression levels */
  20501. Z_NO_COMPRESSION: 0,
  20502. Z_BEST_SPEED: 1,
  20503. Z_BEST_COMPRESSION: 9,
  20504. Z_DEFAULT_COMPRESSION: -1,
  20505. Z_FILTERED: 1,
  20506. Z_HUFFMAN_ONLY: 2,
  20507. Z_RLE: 3,
  20508. Z_FIXED: 4,
  20509. Z_DEFAULT_STRATEGY: 0,
  20510. /* Possible values of the data_type field (though see inflate()) */
  20511. Z_BINARY: 0,
  20512. Z_TEXT: 1,
  20513. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20514. Z_UNKNOWN: 2,
  20515. /* The deflate compression method */
  20516. Z_DEFLATED: 8
  20517. //Z_NULL: null // Use -1 or null inline, depending on var type
  20518. };
  20519. },{}],77:[function(require,module,exports){
  20520. 'use strict';
  20521. // Note: we can't get significant speed boost here.
  20522. // So write code to minimize size - no pregenerated tables
  20523. // and array tools dependencies.
  20524. // Use ordinary array, since untyped makes no boost here
  20525. function makeTable() {
  20526. var c, table = [];
  20527. for (var n =0; n < 256; n++) {
  20528. c = n;
  20529. for (var k =0; k < 8; k++) {
  20530. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20531. }
  20532. table[n] = c;
  20533. }
  20534. return table;
  20535. }
  20536. // Create table on load. Just 255 signed longs. Not a problem.
  20537. var crcTable = makeTable();
  20538. function crc32(crc, buf, len, pos) {
  20539. var t = crcTable,
  20540. end = pos + len;
  20541. crc = crc ^ (-1);
  20542. for (var i = pos; i < end; i++) {
  20543. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20544. }
  20545. return (crc ^ (-1)); // >>> 0;
  20546. }
  20547. module.exports = crc32;
  20548. },{}],78:[function(require,module,exports){
  20549. 'use strict';
  20550. var utils = require('../utils/common');
  20551. var trees = require('./trees');
  20552. var adler32 = require('./adler32');
  20553. var crc32 = require('./crc32');
  20554. var msg = require('./messages');
  20555. /* Public constants ==========================================================*/
  20556. /* ===========================================================================*/
  20557. /* Allowed flush values; see deflate() and inflate() below for details */
  20558. var Z_NO_FLUSH = 0;
  20559. var Z_PARTIAL_FLUSH = 1;
  20560. //var Z_SYNC_FLUSH = 2;
  20561. var Z_FULL_FLUSH = 3;
  20562. var Z_FINISH = 4;
  20563. var Z_BLOCK = 5;
  20564. //var Z_TREES = 6;
  20565. /* Return codes for the compression/decompression functions. Negative values
  20566. * are errors, positive values are used for special but normal events.
  20567. */
  20568. var Z_OK = 0;
  20569. var Z_STREAM_END = 1;
  20570. //var Z_NEED_DICT = 2;
  20571. //var Z_ERRNO = -1;
  20572. var Z_STREAM_ERROR = -2;
  20573. var Z_DATA_ERROR = -3;
  20574. //var Z_MEM_ERROR = -4;
  20575. var Z_BUF_ERROR = -5;
  20576. //var Z_VERSION_ERROR = -6;
  20577. /* compression levels */
  20578. //var Z_NO_COMPRESSION = 0;
  20579. //var Z_BEST_SPEED = 1;
  20580. //var Z_BEST_COMPRESSION = 9;
  20581. var Z_DEFAULT_COMPRESSION = -1;
  20582. var Z_FILTERED = 1;
  20583. var Z_HUFFMAN_ONLY = 2;
  20584. var Z_RLE = 3;
  20585. var Z_FIXED = 4;
  20586. var Z_DEFAULT_STRATEGY = 0;
  20587. /* Possible values of the data_type field (though see inflate()) */
  20588. //var Z_BINARY = 0;
  20589. //var Z_TEXT = 1;
  20590. //var Z_ASCII = 1; // = Z_TEXT
  20591. var Z_UNKNOWN = 2;
  20592. /* The deflate compression method */
  20593. var Z_DEFLATED = 8;
  20594. /*============================================================================*/
  20595. var MAX_MEM_LEVEL = 9;
  20596. /* Maximum value for memLevel in deflateInit2 */
  20597. var MAX_WBITS = 15;
  20598. /* 32K LZ77 window */
  20599. var DEF_MEM_LEVEL = 8;
  20600. var LENGTH_CODES = 29;
  20601. /* number of length codes, not counting the special END_BLOCK code */
  20602. var LITERALS = 256;
  20603. /* number of literal bytes 0..255 */
  20604. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20605. /* number of Literal or Length codes, including the END_BLOCK code */
  20606. var D_CODES = 30;
  20607. /* number of distance codes */
  20608. var BL_CODES = 19;
  20609. /* number of codes used to transfer the bit lengths */
  20610. var HEAP_SIZE = 2*L_CODES + 1;
  20611. /* maximum heap size */
  20612. var MAX_BITS = 15;
  20613. /* All codes must not exceed MAX_BITS bits */
  20614. var MIN_MATCH = 3;
  20615. var MAX_MATCH = 258;
  20616. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20617. var PRESET_DICT = 0x20;
  20618. var INIT_STATE = 42;
  20619. var EXTRA_STATE = 69;
  20620. var NAME_STATE = 73;
  20621. var COMMENT_STATE = 91;
  20622. var HCRC_STATE = 103;
  20623. var BUSY_STATE = 113;
  20624. var FINISH_STATE = 666;
  20625. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20626. var BS_BLOCK_DONE = 2; /* block flush performed */
  20627. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20628. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20629. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20630. function err(strm, errorCode) {
  20631. strm.msg = msg[errorCode];
  20632. return errorCode;
  20633. }
  20634. function rank(f) {
  20635. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20636. }
  20637. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20638. /* =========================================================================
  20639. * Flush as much pending output as possible. All deflate() output goes
  20640. * through this function so some applications may wish to modify it
  20641. * to avoid allocating a large strm->output buffer and copying into it.
  20642. * (See also read_buf()).
  20643. */
  20644. function flush_pending(strm) {
  20645. var s = strm.state;
  20646. //_tr_flush_bits(s);
  20647. var len = s.pending;
  20648. if (len > strm.avail_out) {
  20649. len = strm.avail_out;
  20650. }
  20651. if (len === 0) { return; }
  20652. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20653. strm.next_out += len;
  20654. s.pending_out += len;
  20655. strm.total_out += len;
  20656. strm.avail_out -= len;
  20657. s.pending -= len;
  20658. if (s.pending === 0) {
  20659. s.pending_out = 0;
  20660. }
  20661. }
  20662. function flush_block_only (s, last) {
  20663. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20664. s.block_start = s.strstart;
  20665. flush_pending(s.strm);
  20666. }
  20667. function put_byte(s, b) {
  20668. s.pending_buf[s.pending++] = b;
  20669. }
  20670. /* =========================================================================
  20671. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20672. * IN assertion: the stream state is correct and there is enough room in
  20673. * pending_buf.
  20674. */
  20675. function putShortMSB(s, b) {
  20676. // put_byte(s, (Byte)(b >> 8));
  20677. // put_byte(s, (Byte)(b & 0xff));
  20678. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20679. s.pending_buf[s.pending++] = b & 0xff;
  20680. }
  20681. /* ===========================================================================
  20682. * Read a new buffer from the current input stream, update the adler32
  20683. * and total number of bytes read. All deflate() input goes through
  20684. * this function so some applications may wish to modify it to avoid
  20685. * allocating a large strm->input buffer and copying from it.
  20686. * (See also flush_pending()).
  20687. */
  20688. function read_buf(strm, buf, start, size) {
  20689. var len = strm.avail_in;
  20690. if (len > size) { len = size; }
  20691. if (len === 0) { return 0; }
  20692. strm.avail_in -= len;
  20693. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20694. if (strm.state.wrap === 1) {
  20695. strm.adler = adler32(strm.adler, buf, len, start);
  20696. }
  20697. else if (strm.state.wrap === 2) {
  20698. strm.adler = crc32(strm.adler, buf, len, start);
  20699. }
  20700. strm.next_in += len;
  20701. strm.total_in += len;
  20702. return len;
  20703. }
  20704. /* ===========================================================================
  20705. * Set match_start to the longest match starting at the given string and
  20706. * return its length. Matches shorter or equal to prev_length are discarded,
  20707. * in which case the result is equal to prev_length and match_start is
  20708. * garbage.
  20709. * IN assertions: cur_match is the head of the hash chain for the current
  20710. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20711. * OUT assertion: the match length is not greater than s->lookahead.
  20712. */
  20713. function longest_match(s, cur_match) {
  20714. var chain_length = s.max_chain_length; /* max hash chain length */
  20715. var scan = s.strstart; /* current string */
  20716. var match; /* matched string */
  20717. var len; /* length of current match */
  20718. var best_len = s.prev_length; /* best match length so far */
  20719. var nice_match = s.nice_match; /* stop if match long enough */
  20720. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20721. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20722. var _win = s.window; // shortcut
  20723. var wmask = s.w_mask;
  20724. var prev = s.prev;
  20725. /* Stop when cur_match becomes <= limit. To simplify the code,
  20726. * we prevent matches with the string of window index 0.
  20727. */
  20728. var strend = s.strstart + MAX_MATCH;
  20729. var scan_end1 = _win[scan + best_len - 1];
  20730. var scan_end = _win[scan + best_len];
  20731. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20732. * It is easy to get rid of this optimization if necessary.
  20733. */
  20734. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20735. /* Do not waste too much time if we already have a good match: */
  20736. if (s.prev_length >= s.good_match) {
  20737. chain_length >>= 2;
  20738. }
  20739. /* Do not look for matches beyond the end of the input. This is necessary
  20740. * to make deflate deterministic.
  20741. */
  20742. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20743. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20744. do {
  20745. // Assert(cur_match < s->strstart, "no future");
  20746. match = cur_match;
  20747. /* Skip to next match if the match length cannot increase
  20748. * or if the match length is less than 2. Note that the checks below
  20749. * for insufficient lookahead only occur occasionally for performance
  20750. * reasons. Therefore uninitialized memory will be accessed, and
  20751. * conditional jumps will be made that depend on those values.
  20752. * However the length of the match is limited to the lookahead, so
  20753. * the output of deflate is not affected by the uninitialized values.
  20754. */
  20755. if (_win[match + best_len] !== scan_end ||
  20756. _win[match + best_len - 1] !== scan_end1 ||
  20757. _win[match] !== _win[scan] ||
  20758. _win[++match] !== _win[scan + 1]) {
  20759. continue;
  20760. }
  20761. /* The check at best_len-1 can be removed because it will be made
  20762. * again later. (This heuristic is not always a win.)
  20763. * It is not necessary to compare scan[2] and match[2] since they
  20764. * are always equal when the other bytes match, given that
  20765. * the hash keys are equal and that HASH_BITS >= 8.
  20766. */
  20767. scan += 2;
  20768. match++;
  20769. // Assert(*scan == *match, "match[2]?");
  20770. /* We check for insufficient lookahead only every 8th comparison;
  20771. * the 256th check will be made at strstart+258.
  20772. */
  20773. do {
  20774. /*jshint noempty:false*/
  20775. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20776. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20777. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20778. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20779. scan < strend);
  20780. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20781. len = MAX_MATCH - (strend - scan);
  20782. scan = strend - MAX_MATCH;
  20783. if (len > best_len) {
  20784. s.match_start = cur_match;
  20785. best_len = len;
  20786. if (len >= nice_match) {
  20787. break;
  20788. }
  20789. scan_end1 = _win[scan + best_len - 1];
  20790. scan_end = _win[scan + best_len];
  20791. }
  20792. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20793. if (best_len <= s.lookahead) {
  20794. return best_len;
  20795. }
  20796. return s.lookahead;
  20797. }
  20798. /* ===========================================================================
  20799. * Fill the window when the lookahead becomes insufficient.
  20800. * Updates strstart and lookahead.
  20801. *
  20802. * IN assertion: lookahead < MIN_LOOKAHEAD
  20803. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20804. * At least one byte has been read, or avail_in == 0; reads are
  20805. * performed for at least two bytes (required for the zip translate_eol
  20806. * option -- not supported here).
  20807. */
  20808. function fill_window(s) {
  20809. var _w_size = s.w_size;
  20810. var p, n, m, more, str;
  20811. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20812. do {
  20813. more = s.window_size - s.lookahead - s.strstart;
  20814. // JS ints have 32 bit, block below not needed
  20815. /* Deal with !@#$% 64K limit: */
  20816. //if (sizeof(int) <= 2) {
  20817. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20818. // more = wsize;
  20819. //
  20820. // } else if (more == (unsigned)(-1)) {
  20821. // /* Very unlikely, but possible on 16 bit machine if
  20822. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20823. // */
  20824. // more--;
  20825. // }
  20826. //}
  20827. /* If the window is almost full and there is insufficient lookahead,
  20828. * move the upper half to the lower one to make room in the upper half.
  20829. */
  20830. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20831. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20832. s.match_start -= _w_size;
  20833. s.strstart -= _w_size;
  20834. /* we now have strstart >= MAX_DIST */
  20835. s.block_start -= _w_size;
  20836. /* Slide the hash table (could be avoided with 32 bit values
  20837. at the expense of memory usage). We slide even when level == 0
  20838. to keep the hash table consistent if we switch back to level > 0
  20839. later. (Using level 0 permanently is not an optimal usage of
  20840. zlib, so we don't care about this pathological case.)
  20841. */
  20842. n = s.hash_size;
  20843. p = n;
  20844. do {
  20845. m = s.head[--p];
  20846. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20847. } while (--n);
  20848. n = _w_size;
  20849. p = n;
  20850. do {
  20851. m = s.prev[--p];
  20852. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20853. /* If n is not on any hash chain, prev[n] is garbage but
  20854. * its value will never be used.
  20855. */
  20856. } while (--n);
  20857. more += _w_size;
  20858. }
  20859. if (s.strm.avail_in === 0) {
  20860. break;
  20861. }
  20862. /* If there was no sliding:
  20863. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20864. * more == window_size - lookahead - strstart
  20865. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20866. * => more >= window_size - 2*WSIZE + 2
  20867. * In the BIG_MEM or MMAP case (not yet supported),
  20868. * window_size == input_size + MIN_LOOKAHEAD &&
  20869. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20870. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20871. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20872. */
  20873. //Assert(more >= 2, "more < 2");
  20874. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20875. s.lookahead += n;
  20876. /* Initialize the hash value now that we have some input: */
  20877. if (s.lookahead + s.insert >= MIN_MATCH) {
  20878. str = s.strstart - s.insert;
  20879. s.ins_h = s.window[str];
  20880. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20881. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20882. //#if MIN_MATCH != 3
  20883. // Call update_hash() MIN_MATCH-3 more times
  20884. //#endif
  20885. while (s.insert) {
  20886. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20887. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20888. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20889. s.head[s.ins_h] = str;
  20890. str++;
  20891. s.insert--;
  20892. if (s.lookahead + s.insert < MIN_MATCH) {
  20893. break;
  20894. }
  20895. }
  20896. }
  20897. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20898. * but this is not important since only literal bytes will be emitted.
  20899. */
  20900. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20901. /* If the WIN_INIT bytes after the end of the current data have never been
  20902. * written, then zero those bytes in order to avoid memory check reports of
  20903. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20904. * the longest match routines. Update the high water mark for the next
  20905. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20906. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20907. */
  20908. // if (s.high_water < s.window_size) {
  20909. // var curr = s.strstart + s.lookahead;
  20910. // var init = 0;
  20911. //
  20912. // if (s.high_water < curr) {
  20913. // /* Previous high water mark below current data -- zero WIN_INIT
  20914. // * bytes or up to end of window, whichever is less.
  20915. // */
  20916. // init = s.window_size - curr;
  20917. // if (init > WIN_INIT)
  20918. // init = WIN_INIT;
  20919. // zmemzero(s->window + curr, (unsigned)init);
  20920. // s->high_water = curr + init;
  20921. // }
  20922. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20923. // /* High water mark at or above current data, but below current data
  20924. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20925. // * to end of window, whichever is less.
  20926. // */
  20927. // init = (ulg)curr + WIN_INIT - s->high_water;
  20928. // if (init > s->window_size - s->high_water)
  20929. // init = s->window_size - s->high_water;
  20930. // zmemzero(s->window + s->high_water, (unsigned)init);
  20931. // s->high_water += init;
  20932. // }
  20933. // }
  20934. //
  20935. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20936. // "not enough room for search");
  20937. }
  20938. /* ===========================================================================
  20939. * Copy without compression as much as possible from the input stream, return
  20940. * the current block state.
  20941. * This function does not insert new strings in the dictionary since
  20942. * uncompressible data is probably not useful. This function is used
  20943. * only for the level=0 compression option.
  20944. * NOTE: this function should be optimized to avoid extra copying from
  20945. * window to pending_buf.
  20946. */
  20947. function deflate_stored(s, flush) {
  20948. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20949. * to pending_buf_size, and each stored block has a 5 byte header:
  20950. */
  20951. var max_block_size = 0xffff;
  20952. if (max_block_size > s.pending_buf_size - 5) {
  20953. max_block_size = s.pending_buf_size - 5;
  20954. }
  20955. /* Copy as much as possible from input to output: */
  20956. for (;;) {
  20957. /* Fill the window as much as possible: */
  20958. if (s.lookahead <= 1) {
  20959. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20960. // s->block_start >= (long)s->w_size, "slide too late");
  20961. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20962. // s.block_start >= s.w_size)) {
  20963. // throw new Error("slide too late");
  20964. // }
  20965. fill_window(s);
  20966. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20967. return BS_NEED_MORE;
  20968. }
  20969. if (s.lookahead === 0) {
  20970. break;
  20971. }
  20972. /* flush the current block */
  20973. }
  20974. //Assert(s->block_start >= 0L, "block gone");
  20975. // if (s.block_start < 0) throw new Error("block gone");
  20976. s.strstart += s.lookahead;
  20977. s.lookahead = 0;
  20978. /* Emit a stored block if pending_buf will be full: */
  20979. var max_start = s.block_start + max_block_size;
  20980. if (s.strstart === 0 || s.strstart >= max_start) {
  20981. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20982. s.lookahead = s.strstart - max_start;
  20983. s.strstart = max_start;
  20984. /*** FLUSH_BLOCK(s, 0); ***/
  20985. flush_block_only(s, false);
  20986. if (s.strm.avail_out === 0) {
  20987. return BS_NEED_MORE;
  20988. }
  20989. /***/
  20990. }
  20991. /* Flush if we may have to slide, otherwise block_start may become
  20992. * negative and the data will be gone:
  20993. */
  20994. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20995. /*** FLUSH_BLOCK(s, 0); ***/
  20996. flush_block_only(s, false);
  20997. if (s.strm.avail_out === 0) {
  20998. return BS_NEED_MORE;
  20999. }
  21000. /***/
  21001. }
  21002. }
  21003. s.insert = 0;
  21004. if (flush === Z_FINISH) {
  21005. /*** FLUSH_BLOCK(s, 1); ***/
  21006. flush_block_only(s, true);
  21007. if (s.strm.avail_out === 0) {
  21008. return BS_FINISH_STARTED;
  21009. }
  21010. /***/
  21011. return BS_FINISH_DONE;
  21012. }
  21013. if (s.strstart > s.block_start) {
  21014. /*** FLUSH_BLOCK(s, 0); ***/
  21015. flush_block_only(s, false);
  21016. if (s.strm.avail_out === 0) {
  21017. return BS_NEED_MORE;
  21018. }
  21019. /***/
  21020. }
  21021. return BS_NEED_MORE;
  21022. }
  21023. /* ===========================================================================
  21024. * Compress as much as possible from the input stream, return the current
  21025. * block state.
  21026. * This function does not perform lazy evaluation of matches and inserts
  21027. * new strings in the dictionary only for unmatched strings or for short
  21028. * matches. It is used only for the fast compression options.
  21029. */
  21030. function deflate_fast(s, flush) {
  21031. var hash_head; /* head of the hash chain */
  21032. var bflush; /* set if current block must be flushed */
  21033. for (;;) {
  21034. /* Make sure that we always have enough lookahead, except
  21035. * at the end of the input file. We need MAX_MATCH bytes
  21036. * for the next match, plus MIN_MATCH bytes to insert the
  21037. * string following the next match.
  21038. */
  21039. if (s.lookahead < MIN_LOOKAHEAD) {
  21040. fill_window(s);
  21041. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21042. return BS_NEED_MORE;
  21043. }
  21044. if (s.lookahead === 0) {
  21045. break; /* flush the current block */
  21046. }
  21047. }
  21048. /* Insert the string window[strstart .. strstart+2] in the
  21049. * dictionary, and set hash_head to the head of the hash chain:
  21050. */
  21051. hash_head = 0/*NIL*/;
  21052. if (s.lookahead >= MIN_MATCH) {
  21053. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21054. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21055. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21056. s.head[s.ins_h] = s.strstart;
  21057. /***/
  21058. }
  21059. /* Find the longest match, discarding those <= prev_length.
  21060. * At this point we have always match_length < MIN_MATCH
  21061. */
  21062. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21063. /* To simplify the code, we prevent matches with the string
  21064. * of window index 0 (in particular we have to avoid a match
  21065. * of the string with itself at the start of the input file).
  21066. */
  21067. s.match_length = longest_match(s, hash_head);
  21068. /* longest_match() sets match_start */
  21069. }
  21070. if (s.match_length >= MIN_MATCH) {
  21071. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21072. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21073. s.match_length - MIN_MATCH, bflush); ***/
  21074. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21075. s.lookahead -= s.match_length;
  21076. /* Insert new strings in the hash table only if the match length
  21077. * is not too large. This saves time but degrades compression.
  21078. */
  21079. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21080. s.match_length--; /* string at strstart already in table */
  21081. do {
  21082. s.strstart++;
  21083. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21084. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21085. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21086. s.head[s.ins_h] = s.strstart;
  21087. /***/
  21088. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21089. * always MIN_MATCH bytes ahead.
  21090. */
  21091. } while (--s.match_length !== 0);
  21092. s.strstart++;
  21093. } else
  21094. {
  21095. s.strstart += s.match_length;
  21096. s.match_length = 0;
  21097. s.ins_h = s.window[s.strstart];
  21098. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21099. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21100. //#if MIN_MATCH != 3
  21101. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21102. //#endif
  21103. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21104. * matter since it will be recomputed at next deflate call.
  21105. */
  21106. }
  21107. } else {
  21108. /* No match, output a literal byte */
  21109. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21110. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21111. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21112. s.lookahead--;
  21113. s.strstart++;
  21114. }
  21115. if (bflush) {
  21116. /*** FLUSH_BLOCK(s, 0); ***/
  21117. flush_block_only(s, false);
  21118. if (s.strm.avail_out === 0) {
  21119. return BS_NEED_MORE;
  21120. }
  21121. /***/
  21122. }
  21123. }
  21124. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21125. if (flush === Z_FINISH) {
  21126. /*** FLUSH_BLOCK(s, 1); ***/
  21127. flush_block_only(s, true);
  21128. if (s.strm.avail_out === 0) {
  21129. return BS_FINISH_STARTED;
  21130. }
  21131. /***/
  21132. return BS_FINISH_DONE;
  21133. }
  21134. if (s.last_lit) {
  21135. /*** FLUSH_BLOCK(s, 0); ***/
  21136. flush_block_only(s, false);
  21137. if (s.strm.avail_out === 0) {
  21138. return BS_NEED_MORE;
  21139. }
  21140. /***/
  21141. }
  21142. return BS_BLOCK_DONE;
  21143. }
  21144. /* ===========================================================================
  21145. * Same as above, but achieves better compression. We use a lazy
  21146. * evaluation for matches: a match is finally adopted only if there is
  21147. * no better match at the next window position.
  21148. */
  21149. function deflate_slow(s, flush) {
  21150. var hash_head; /* head of hash chain */
  21151. var bflush; /* set if current block must be flushed */
  21152. var max_insert;
  21153. /* Process the input block. */
  21154. for (;;) {
  21155. /* Make sure that we always have enough lookahead, except
  21156. * at the end of the input file. We need MAX_MATCH bytes
  21157. * for the next match, plus MIN_MATCH bytes to insert the
  21158. * string following the next match.
  21159. */
  21160. if (s.lookahead < MIN_LOOKAHEAD) {
  21161. fill_window(s);
  21162. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21163. return BS_NEED_MORE;
  21164. }
  21165. if (s.lookahead === 0) { break; } /* flush the current block */
  21166. }
  21167. /* Insert the string window[strstart .. strstart+2] in the
  21168. * dictionary, and set hash_head to the head of the hash chain:
  21169. */
  21170. hash_head = 0/*NIL*/;
  21171. if (s.lookahead >= MIN_MATCH) {
  21172. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21173. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21174. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21175. s.head[s.ins_h] = s.strstart;
  21176. /***/
  21177. }
  21178. /* Find the longest match, discarding those <= prev_length.
  21179. */
  21180. s.prev_length = s.match_length;
  21181. s.prev_match = s.match_start;
  21182. s.match_length = MIN_MATCH-1;
  21183. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21184. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21185. /* To simplify the code, we prevent matches with the string
  21186. * of window index 0 (in particular we have to avoid a match
  21187. * of the string with itself at the start of the input file).
  21188. */
  21189. s.match_length = longest_match(s, hash_head);
  21190. /* longest_match() sets match_start */
  21191. if (s.match_length <= 5 &&
  21192. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21193. /* If prev_match is also MIN_MATCH, match_start is garbage
  21194. * but we will ignore the current match anyway.
  21195. */
  21196. s.match_length = MIN_MATCH-1;
  21197. }
  21198. }
  21199. /* If there was a match at the previous step and the current
  21200. * match is not better, output the previous match:
  21201. */
  21202. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21203. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21204. /* Do not insert strings in hash table beyond this. */
  21205. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21206. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21207. s.prev_length - MIN_MATCH, bflush);***/
  21208. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21209. /* Insert in hash table all strings up to the end of the match.
  21210. * strstart-1 and strstart are already inserted. If there is not
  21211. * enough lookahead, the last two strings are not inserted in
  21212. * the hash table.
  21213. */
  21214. s.lookahead -= s.prev_length-1;
  21215. s.prev_length -= 2;
  21216. do {
  21217. if (++s.strstart <= max_insert) {
  21218. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21219. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21220. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21221. s.head[s.ins_h] = s.strstart;
  21222. /***/
  21223. }
  21224. } while (--s.prev_length !== 0);
  21225. s.match_available = 0;
  21226. s.match_length = MIN_MATCH-1;
  21227. s.strstart++;
  21228. if (bflush) {
  21229. /*** FLUSH_BLOCK(s, 0); ***/
  21230. flush_block_only(s, false);
  21231. if (s.strm.avail_out === 0) {
  21232. return BS_NEED_MORE;
  21233. }
  21234. /***/
  21235. }
  21236. } else if (s.match_available) {
  21237. /* If there was no match at the previous position, output a
  21238. * single literal. If there was a match but the current match
  21239. * is longer, truncate the previous match to a single literal.
  21240. */
  21241. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21242. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21243. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21244. if (bflush) {
  21245. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21246. flush_block_only(s, false);
  21247. /***/
  21248. }
  21249. s.strstart++;
  21250. s.lookahead--;
  21251. if (s.strm.avail_out === 0) {
  21252. return BS_NEED_MORE;
  21253. }
  21254. } else {
  21255. /* There is no previous match to compare with, wait for
  21256. * the next step to decide.
  21257. */
  21258. s.match_available = 1;
  21259. s.strstart++;
  21260. s.lookahead--;
  21261. }
  21262. }
  21263. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21264. if (s.match_available) {
  21265. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21266. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21267. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21268. s.match_available = 0;
  21269. }
  21270. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21271. if (flush === Z_FINISH) {
  21272. /*** FLUSH_BLOCK(s, 1); ***/
  21273. flush_block_only(s, true);
  21274. if (s.strm.avail_out === 0) {
  21275. return BS_FINISH_STARTED;
  21276. }
  21277. /***/
  21278. return BS_FINISH_DONE;
  21279. }
  21280. if (s.last_lit) {
  21281. /*** FLUSH_BLOCK(s, 0); ***/
  21282. flush_block_only(s, false);
  21283. if (s.strm.avail_out === 0) {
  21284. return BS_NEED_MORE;
  21285. }
  21286. /***/
  21287. }
  21288. return BS_BLOCK_DONE;
  21289. }
  21290. /* ===========================================================================
  21291. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21292. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21293. * deflate switches away from Z_RLE.)
  21294. */
  21295. function deflate_rle(s, flush) {
  21296. var bflush; /* set if current block must be flushed */
  21297. var prev; /* byte at distance one to match */
  21298. var scan, strend; /* scan goes up to strend for length of run */
  21299. var _win = s.window;
  21300. for (;;) {
  21301. /* Make sure that we always have enough lookahead, except
  21302. * at the end of the input file. We need MAX_MATCH bytes
  21303. * for the longest run, plus one for the unrolled loop.
  21304. */
  21305. if (s.lookahead <= MAX_MATCH) {
  21306. fill_window(s);
  21307. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21308. return BS_NEED_MORE;
  21309. }
  21310. if (s.lookahead === 0) { break; } /* flush the current block */
  21311. }
  21312. /* See how many times the previous byte repeats */
  21313. s.match_length = 0;
  21314. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21315. scan = s.strstart - 1;
  21316. prev = _win[scan];
  21317. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21318. strend = s.strstart + MAX_MATCH;
  21319. do {
  21320. /*jshint noempty:false*/
  21321. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21322. prev === _win[++scan] && prev === _win[++scan] &&
  21323. prev === _win[++scan] && prev === _win[++scan] &&
  21324. prev === _win[++scan] && prev === _win[++scan] &&
  21325. scan < strend);
  21326. s.match_length = MAX_MATCH - (strend - scan);
  21327. if (s.match_length > s.lookahead) {
  21328. s.match_length = s.lookahead;
  21329. }
  21330. }
  21331. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21332. }
  21333. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21334. if (s.match_length >= MIN_MATCH) {
  21335. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21336. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21337. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21338. s.lookahead -= s.match_length;
  21339. s.strstart += s.match_length;
  21340. s.match_length = 0;
  21341. } else {
  21342. /* No match, output a literal byte */
  21343. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21344. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21345. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21346. s.lookahead--;
  21347. s.strstart++;
  21348. }
  21349. if (bflush) {
  21350. /*** FLUSH_BLOCK(s, 0); ***/
  21351. flush_block_only(s, false);
  21352. if (s.strm.avail_out === 0) {
  21353. return BS_NEED_MORE;
  21354. }
  21355. /***/
  21356. }
  21357. }
  21358. s.insert = 0;
  21359. if (flush === Z_FINISH) {
  21360. /*** FLUSH_BLOCK(s, 1); ***/
  21361. flush_block_only(s, true);
  21362. if (s.strm.avail_out === 0) {
  21363. return BS_FINISH_STARTED;
  21364. }
  21365. /***/
  21366. return BS_FINISH_DONE;
  21367. }
  21368. if (s.last_lit) {
  21369. /*** FLUSH_BLOCK(s, 0); ***/
  21370. flush_block_only(s, false);
  21371. if (s.strm.avail_out === 0) {
  21372. return BS_NEED_MORE;
  21373. }
  21374. /***/
  21375. }
  21376. return BS_BLOCK_DONE;
  21377. }
  21378. /* ===========================================================================
  21379. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21380. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21381. */
  21382. function deflate_huff(s, flush) {
  21383. var bflush; /* set if current block must be flushed */
  21384. for (;;) {
  21385. /* Make sure that we have a literal to write. */
  21386. if (s.lookahead === 0) {
  21387. fill_window(s);
  21388. if (s.lookahead === 0) {
  21389. if (flush === Z_NO_FLUSH) {
  21390. return BS_NEED_MORE;
  21391. }
  21392. break; /* flush the current block */
  21393. }
  21394. }
  21395. /* Output a literal byte */
  21396. s.match_length = 0;
  21397. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21398. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21399. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21400. s.lookahead--;
  21401. s.strstart++;
  21402. if (bflush) {
  21403. /*** FLUSH_BLOCK(s, 0); ***/
  21404. flush_block_only(s, false);
  21405. if (s.strm.avail_out === 0) {
  21406. return BS_NEED_MORE;
  21407. }
  21408. /***/
  21409. }
  21410. }
  21411. s.insert = 0;
  21412. if (flush === Z_FINISH) {
  21413. /*** FLUSH_BLOCK(s, 1); ***/
  21414. flush_block_only(s, true);
  21415. if (s.strm.avail_out === 0) {
  21416. return BS_FINISH_STARTED;
  21417. }
  21418. /***/
  21419. return BS_FINISH_DONE;
  21420. }
  21421. if (s.last_lit) {
  21422. /*** FLUSH_BLOCK(s, 0); ***/
  21423. flush_block_only(s, false);
  21424. if (s.strm.avail_out === 0) {
  21425. return BS_NEED_MORE;
  21426. }
  21427. /***/
  21428. }
  21429. return BS_BLOCK_DONE;
  21430. }
  21431. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21432. * the desired pack level (0..9). The values given below have been tuned to
  21433. * exclude worst case performance for pathological files. Better values may be
  21434. * found for specific files.
  21435. */
  21436. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21437. this.good_length = good_length;
  21438. this.max_lazy = max_lazy;
  21439. this.nice_length = nice_length;
  21440. this.max_chain = max_chain;
  21441. this.func = func;
  21442. };
  21443. var configuration_table;
  21444. configuration_table = [
  21445. /* good lazy nice chain */
  21446. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21447. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21448. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21449. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21450. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21451. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21452. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21453. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21454. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21455. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21456. ];
  21457. /* ===========================================================================
  21458. * Initialize the "longest match" routines for a new zlib stream
  21459. */
  21460. function lm_init(s) {
  21461. s.window_size = 2 * s.w_size;
  21462. /*** CLEAR_HASH(s); ***/
  21463. zero(s.head); // Fill with NIL (= 0);
  21464. /* Set the default configuration parameters:
  21465. */
  21466. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21467. s.good_match = configuration_table[s.level].good_length;
  21468. s.nice_match = configuration_table[s.level].nice_length;
  21469. s.max_chain_length = configuration_table[s.level].max_chain;
  21470. s.strstart = 0;
  21471. s.block_start = 0;
  21472. s.lookahead = 0;
  21473. s.insert = 0;
  21474. s.match_length = s.prev_length = MIN_MATCH - 1;
  21475. s.match_available = 0;
  21476. s.ins_h = 0;
  21477. }
  21478. function DeflateState() {
  21479. this.strm = null; /* pointer back to this zlib stream */
  21480. this.status = 0; /* as the name implies */
  21481. this.pending_buf = null; /* output still pending */
  21482. this.pending_buf_size = 0; /* size of pending_buf */
  21483. this.pending_out = 0; /* next pending byte to output to the stream */
  21484. this.pending = 0; /* nb of bytes in the pending buffer */
  21485. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21486. this.gzhead = null; /* gzip header information to write */
  21487. this.gzindex = 0; /* where in extra, name, or comment */
  21488. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21489. this.last_flush = -1; /* value of flush param for previous deflate call */
  21490. this.w_size = 0; /* LZ77 window size (32K by default) */
  21491. this.w_bits = 0; /* log2(w_size) (8..16) */
  21492. this.w_mask = 0; /* w_size - 1 */
  21493. this.window = null;
  21494. /* Sliding window. Input bytes are read into the second half of the window,
  21495. * and move to the first half later to keep a dictionary of at least wSize
  21496. * bytes. With this organization, matches are limited to a distance of
  21497. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21498. * performed with a length multiple of the block size.
  21499. */
  21500. this.window_size = 0;
  21501. /* Actual size of window: 2*wSize, except when the user input buffer
  21502. * is directly used as sliding window.
  21503. */
  21504. this.prev = null;
  21505. /* Link to older string with same hash index. To limit the size of this
  21506. * array to 64K, this link is maintained only for the last 32K strings.
  21507. * An index in this array is thus a window index modulo 32K.
  21508. */
  21509. this.head = null; /* Heads of the hash chains or NIL. */
  21510. this.ins_h = 0; /* hash index of string to be inserted */
  21511. this.hash_size = 0; /* number of elements in hash table */
  21512. this.hash_bits = 0; /* log2(hash_size) */
  21513. this.hash_mask = 0; /* hash_size-1 */
  21514. this.hash_shift = 0;
  21515. /* Number of bits by which ins_h must be shifted at each input
  21516. * step. It must be such that after MIN_MATCH steps, the oldest
  21517. * byte no longer takes part in the hash key, that is:
  21518. * hash_shift * MIN_MATCH >= hash_bits
  21519. */
  21520. this.block_start = 0;
  21521. /* Window position at the beginning of the current output block. Gets
  21522. * negative when the window is moved backwards.
  21523. */
  21524. this.match_length = 0; /* length of best match */
  21525. this.prev_match = 0; /* previous match */
  21526. this.match_available = 0; /* set if previous match exists */
  21527. this.strstart = 0; /* start of string to insert */
  21528. this.match_start = 0; /* start of matching string */
  21529. this.lookahead = 0; /* number of valid bytes ahead in window */
  21530. this.prev_length = 0;
  21531. /* Length of the best match at previous step. Matches not greater than this
  21532. * are discarded. This is used in the lazy match evaluation.
  21533. */
  21534. this.max_chain_length = 0;
  21535. /* To speed up deflation, hash chains are never searched beyond this
  21536. * length. A higher limit improves compression ratio but degrades the
  21537. * speed.
  21538. */
  21539. this.max_lazy_match = 0;
  21540. /* Attempt to find a better match only when the current match is strictly
  21541. * smaller than this value. This mechanism is used only for compression
  21542. * levels >= 4.
  21543. */
  21544. // That's alias to max_lazy_match, don't use directly
  21545. //this.max_insert_length = 0;
  21546. /* Insert new strings in the hash table only if the match length is not
  21547. * greater than this length. This saves time but degrades compression.
  21548. * max_insert_length is used only for compression levels <= 3.
  21549. */
  21550. this.level = 0; /* compression level (1..9) */
  21551. this.strategy = 0; /* favor or force Huffman coding*/
  21552. this.good_match = 0;
  21553. /* Use a faster search when the previous match is longer than this */
  21554. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21555. /* used by trees.c: */
  21556. /* Didn't use ct_data typedef below to suppress compiler warning */
  21557. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21558. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21559. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21560. // Use flat array of DOUBLE size, with interleaved fata,
  21561. // because JS does not support effective
  21562. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21563. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21564. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21565. zero(this.dyn_ltree);
  21566. zero(this.dyn_dtree);
  21567. zero(this.bl_tree);
  21568. this.l_desc = null; /* desc. for literal tree */
  21569. this.d_desc = null; /* desc. for distance tree */
  21570. this.bl_desc = null; /* desc. for bit length tree */
  21571. //ush bl_count[MAX_BITS+1];
  21572. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21573. /* number of codes at each bit length for an optimal tree */
  21574. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21575. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21576. zero(this.heap);
  21577. this.heap_len = 0; /* number of elements in the heap */
  21578. this.heap_max = 0; /* element of largest frequency */
  21579. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21580. * The same heap array is used to build all trees.
  21581. */
  21582. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21583. zero(this.depth);
  21584. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21585. */
  21586. this.l_buf = 0; /* buffer index for literals or lengths */
  21587. this.lit_bufsize = 0;
  21588. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21589. * limiting lit_bufsize to 64K:
  21590. * - frequencies can be kept in 16 bit counters
  21591. * - if compression is not successful for the first block, all input
  21592. * data is still in the window so we can still emit a stored block even
  21593. * when input comes from standard input. (This can also be done for
  21594. * all blocks if lit_bufsize is not greater than 32K.)
  21595. * - if compression is not successful for a file smaller than 64K, we can
  21596. * even emit a stored file instead of a stored block (saving 5 bytes).
  21597. * This is applicable only for zip (not gzip or zlib).
  21598. * - creating new Huffman trees less frequently may not provide fast
  21599. * adaptation to changes in the input data statistics. (Take for
  21600. * example a binary file with poorly compressible code followed by
  21601. * a highly compressible string table.) Smaller buffer sizes give
  21602. * fast adaptation but have of course the overhead of transmitting
  21603. * trees more frequently.
  21604. * - I can't count above 4
  21605. */
  21606. this.last_lit = 0; /* running index in l_buf */
  21607. this.d_buf = 0;
  21608. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21609. * the same number of elements. To use different lengths, an extra flag
  21610. * array would be necessary.
  21611. */
  21612. this.opt_len = 0; /* bit length of current block with optimal trees */
  21613. this.static_len = 0; /* bit length of current block with static trees */
  21614. this.matches = 0; /* number of string matches in current block */
  21615. this.insert = 0; /* bytes at end of window left to insert */
  21616. this.bi_buf = 0;
  21617. /* Output buffer. bits are inserted starting at the bottom (least
  21618. * significant bits).
  21619. */
  21620. this.bi_valid = 0;
  21621. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21622. * are always zero.
  21623. */
  21624. // Used for window memory init. We safely ignore it for JS. That makes
  21625. // sense only for pointers and memory check tools.
  21626. //this.high_water = 0;
  21627. /* High water mark offset in window for initialized bytes -- bytes above
  21628. * this are set to zero in order to avoid memory check warnings when
  21629. * longest match routines access bytes past the input. This is then
  21630. * updated to the new high water mark.
  21631. */
  21632. }
  21633. function deflateResetKeep(strm) {
  21634. var s;
  21635. if (!strm || !strm.state) {
  21636. return err(strm, Z_STREAM_ERROR);
  21637. }
  21638. strm.total_in = strm.total_out = 0;
  21639. strm.data_type = Z_UNKNOWN;
  21640. s = strm.state;
  21641. s.pending = 0;
  21642. s.pending_out = 0;
  21643. if (s.wrap < 0) {
  21644. s.wrap = -s.wrap;
  21645. /* was made negative by deflate(..., Z_FINISH); */
  21646. }
  21647. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21648. strm.adler = (s.wrap === 2) ?
  21649. 0 // crc32(0, Z_NULL, 0)
  21650. :
  21651. 1; // adler32(0, Z_NULL, 0)
  21652. s.last_flush = Z_NO_FLUSH;
  21653. trees._tr_init(s);
  21654. return Z_OK;
  21655. }
  21656. function deflateReset(strm) {
  21657. var ret = deflateResetKeep(strm);
  21658. if (ret === Z_OK) {
  21659. lm_init(strm.state);
  21660. }
  21661. return ret;
  21662. }
  21663. function deflateSetHeader(strm, head) {
  21664. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21665. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21666. strm.state.gzhead = head;
  21667. return Z_OK;
  21668. }
  21669. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21670. if (!strm) { // === Z_NULL
  21671. return Z_STREAM_ERROR;
  21672. }
  21673. var wrap = 1;
  21674. if (level === Z_DEFAULT_COMPRESSION) {
  21675. level = 6;
  21676. }
  21677. if (windowBits < 0) { /* suppress zlib wrapper */
  21678. wrap = 0;
  21679. windowBits = -windowBits;
  21680. }
  21681. else if (windowBits > 15) {
  21682. wrap = 2; /* write gzip wrapper instead */
  21683. windowBits -= 16;
  21684. }
  21685. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21686. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21687. strategy < 0 || strategy > Z_FIXED) {
  21688. return err(strm, Z_STREAM_ERROR);
  21689. }
  21690. if (windowBits === 8) {
  21691. windowBits = 9;
  21692. }
  21693. /* until 256-byte window bug fixed */
  21694. var s = new DeflateState();
  21695. strm.state = s;
  21696. s.strm = strm;
  21697. s.wrap = wrap;
  21698. s.gzhead = null;
  21699. s.w_bits = windowBits;
  21700. s.w_size = 1 << s.w_bits;
  21701. s.w_mask = s.w_size - 1;
  21702. s.hash_bits = memLevel + 7;
  21703. s.hash_size = 1 << s.hash_bits;
  21704. s.hash_mask = s.hash_size - 1;
  21705. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21706. s.window = new utils.Buf8(s.w_size * 2);
  21707. s.head = new utils.Buf16(s.hash_size);
  21708. s.prev = new utils.Buf16(s.w_size);
  21709. // Don't need mem init magic for JS.
  21710. //s.high_water = 0; /* nothing written to s->window yet */
  21711. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21712. s.pending_buf_size = s.lit_bufsize * 4;
  21713. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21714. s.d_buf = s.lit_bufsize >> 1;
  21715. s.l_buf = (1 + 2) * s.lit_bufsize;
  21716. s.level = level;
  21717. s.strategy = strategy;
  21718. s.method = method;
  21719. return deflateReset(strm);
  21720. }
  21721. function deflateInit(strm, level) {
  21722. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21723. }
  21724. function deflate(strm, flush) {
  21725. var old_flush, s;
  21726. var beg, val; // for gzip header write only
  21727. if (!strm || !strm.state ||
  21728. flush > Z_BLOCK || flush < 0) {
  21729. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21730. }
  21731. s = strm.state;
  21732. if (!strm.output ||
  21733. (!strm.input && strm.avail_in !== 0) ||
  21734. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21735. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21736. }
  21737. s.strm = strm; /* just in case */
  21738. old_flush = s.last_flush;
  21739. s.last_flush = flush;
  21740. /* Write the header */
  21741. if (s.status === INIT_STATE) {
  21742. if (s.wrap === 2) { // GZIP header
  21743. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21744. put_byte(s, 31);
  21745. put_byte(s, 139);
  21746. put_byte(s, 8);
  21747. if (!s.gzhead) { // s->gzhead == Z_NULL
  21748. put_byte(s, 0);
  21749. put_byte(s, 0);
  21750. put_byte(s, 0);
  21751. put_byte(s, 0);
  21752. put_byte(s, 0);
  21753. put_byte(s, s.level === 9 ? 2 :
  21754. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21755. 4 : 0));
  21756. put_byte(s, OS_CODE);
  21757. s.status = BUSY_STATE;
  21758. }
  21759. else {
  21760. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21761. (s.gzhead.hcrc ? 2 : 0) +
  21762. (!s.gzhead.extra ? 0 : 4) +
  21763. (!s.gzhead.name ? 0 : 8) +
  21764. (!s.gzhead.comment ? 0 : 16)
  21765. );
  21766. put_byte(s, s.gzhead.time & 0xff);
  21767. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21768. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21769. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21770. put_byte(s, s.level === 9 ? 2 :
  21771. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21772. 4 : 0));
  21773. put_byte(s, s.gzhead.os & 0xff);
  21774. if (s.gzhead.extra && s.gzhead.extra.length) {
  21775. put_byte(s, s.gzhead.extra.length & 0xff);
  21776. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21777. }
  21778. if (s.gzhead.hcrc) {
  21779. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21780. }
  21781. s.gzindex = 0;
  21782. s.status = EXTRA_STATE;
  21783. }
  21784. }
  21785. else // DEFLATE header
  21786. {
  21787. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21788. var level_flags = -1;
  21789. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21790. level_flags = 0;
  21791. } else if (s.level < 6) {
  21792. level_flags = 1;
  21793. } else if (s.level === 6) {
  21794. level_flags = 2;
  21795. } else {
  21796. level_flags = 3;
  21797. }
  21798. header |= (level_flags << 6);
  21799. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21800. header += 31 - (header % 31);
  21801. s.status = BUSY_STATE;
  21802. putShortMSB(s, header);
  21803. /* Save the adler32 of the preset dictionary: */
  21804. if (s.strstart !== 0) {
  21805. putShortMSB(s, strm.adler >>> 16);
  21806. putShortMSB(s, strm.adler & 0xffff);
  21807. }
  21808. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21809. }
  21810. }
  21811. //#ifdef GZIP
  21812. if (s.status === EXTRA_STATE) {
  21813. if (s.gzhead.extra/* != Z_NULL*/) {
  21814. beg = s.pending; /* start of bytes to update crc */
  21815. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21816. if (s.pending === s.pending_buf_size) {
  21817. if (s.gzhead.hcrc && s.pending > beg) {
  21818. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21819. }
  21820. flush_pending(strm);
  21821. beg = s.pending;
  21822. if (s.pending === s.pending_buf_size) {
  21823. break;
  21824. }
  21825. }
  21826. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21827. s.gzindex++;
  21828. }
  21829. if (s.gzhead.hcrc && s.pending > beg) {
  21830. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21831. }
  21832. if (s.gzindex === s.gzhead.extra.length) {
  21833. s.gzindex = 0;
  21834. s.status = NAME_STATE;
  21835. }
  21836. }
  21837. else {
  21838. s.status = NAME_STATE;
  21839. }
  21840. }
  21841. if (s.status === NAME_STATE) {
  21842. if (s.gzhead.name/* != Z_NULL*/) {
  21843. beg = s.pending; /* start of bytes to update crc */
  21844. //int val;
  21845. do {
  21846. if (s.pending === s.pending_buf_size) {
  21847. if (s.gzhead.hcrc && s.pending > beg) {
  21848. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21849. }
  21850. flush_pending(strm);
  21851. beg = s.pending;
  21852. if (s.pending === s.pending_buf_size) {
  21853. val = 1;
  21854. break;
  21855. }
  21856. }
  21857. // JS specific: little magic to add zero terminator to end of string
  21858. if (s.gzindex < s.gzhead.name.length) {
  21859. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21860. } else {
  21861. val = 0;
  21862. }
  21863. put_byte(s, val);
  21864. } while (val !== 0);
  21865. if (s.gzhead.hcrc && s.pending > beg) {
  21866. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21867. }
  21868. if (val === 0) {
  21869. s.gzindex = 0;
  21870. s.status = COMMENT_STATE;
  21871. }
  21872. }
  21873. else {
  21874. s.status = COMMENT_STATE;
  21875. }
  21876. }
  21877. if (s.status === COMMENT_STATE) {
  21878. if (s.gzhead.comment/* != Z_NULL*/) {
  21879. beg = s.pending; /* start of bytes to update crc */
  21880. //int val;
  21881. do {
  21882. if (s.pending === s.pending_buf_size) {
  21883. if (s.gzhead.hcrc && s.pending > beg) {
  21884. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21885. }
  21886. flush_pending(strm);
  21887. beg = s.pending;
  21888. if (s.pending === s.pending_buf_size) {
  21889. val = 1;
  21890. break;
  21891. }
  21892. }
  21893. // JS specific: little magic to add zero terminator to end of string
  21894. if (s.gzindex < s.gzhead.comment.length) {
  21895. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21896. } else {
  21897. val = 0;
  21898. }
  21899. put_byte(s, val);
  21900. } while (val !== 0);
  21901. if (s.gzhead.hcrc && s.pending > beg) {
  21902. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21903. }
  21904. if (val === 0) {
  21905. s.status = HCRC_STATE;
  21906. }
  21907. }
  21908. else {
  21909. s.status = HCRC_STATE;
  21910. }
  21911. }
  21912. if (s.status === HCRC_STATE) {
  21913. if (s.gzhead.hcrc) {
  21914. if (s.pending + 2 > s.pending_buf_size) {
  21915. flush_pending(strm);
  21916. }
  21917. if (s.pending + 2 <= s.pending_buf_size) {
  21918. put_byte(s, strm.adler & 0xff);
  21919. put_byte(s, (strm.adler >> 8) & 0xff);
  21920. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21921. s.status = BUSY_STATE;
  21922. }
  21923. }
  21924. else {
  21925. s.status = BUSY_STATE;
  21926. }
  21927. }
  21928. //#endif
  21929. /* Flush as much pending output as possible */
  21930. if (s.pending !== 0) {
  21931. flush_pending(strm);
  21932. if (strm.avail_out === 0) {
  21933. /* Since avail_out is 0, deflate will be called again with
  21934. * more output space, but possibly with both pending and
  21935. * avail_in equal to zero. There won't be anything to do,
  21936. * but this is not an error situation so make sure we
  21937. * return OK instead of BUF_ERROR at next call of deflate:
  21938. */
  21939. s.last_flush = -1;
  21940. return Z_OK;
  21941. }
  21942. /* Make sure there is something to do and avoid duplicate consecutive
  21943. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21944. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21945. */
  21946. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21947. flush !== Z_FINISH) {
  21948. return err(strm, Z_BUF_ERROR);
  21949. }
  21950. /* User must not provide more input after the first FINISH: */
  21951. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21952. return err(strm, Z_BUF_ERROR);
  21953. }
  21954. /* Start a new block or continue the current one.
  21955. */
  21956. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21957. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21958. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21959. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21960. configuration_table[s.level].func(s, flush));
  21961. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21962. s.status = FINISH_STATE;
  21963. }
  21964. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21965. if (strm.avail_out === 0) {
  21966. s.last_flush = -1;
  21967. /* avoid BUF_ERROR next call, see above */
  21968. }
  21969. return Z_OK;
  21970. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21971. * of deflate should use the same flush parameter to make sure
  21972. * that the flush is complete. So we don't have to output an
  21973. * empty block here, this will be done at next call. This also
  21974. * ensures that for a very small output buffer, we emit at most
  21975. * one empty block.
  21976. */
  21977. }
  21978. if (bstate === BS_BLOCK_DONE) {
  21979. if (flush === Z_PARTIAL_FLUSH) {
  21980. trees._tr_align(s);
  21981. }
  21982. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21983. trees._tr_stored_block(s, 0, 0, false);
  21984. /* For a full flush, this empty block will be recognized
  21985. * as a special marker by inflate_sync().
  21986. */
  21987. if (flush === Z_FULL_FLUSH) {
  21988. /*** CLEAR_HASH(s); ***/ /* forget history */
  21989. zero(s.head); // Fill with NIL (= 0);
  21990. if (s.lookahead === 0) {
  21991. s.strstart = 0;
  21992. s.block_start = 0;
  21993. s.insert = 0;
  21994. }
  21995. }
  21996. }
  21997. flush_pending(strm);
  21998. if (strm.avail_out === 0) {
  21999. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22000. return Z_OK;
  22001. }
  22002. }
  22003. }
  22004. //Assert(strm->avail_out > 0, "bug2");
  22005. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22006. if (flush !== Z_FINISH) { return Z_OK; }
  22007. if (s.wrap <= 0) { return Z_STREAM_END; }
  22008. /* Write the trailer */
  22009. if (s.wrap === 2) {
  22010. put_byte(s, strm.adler & 0xff);
  22011. put_byte(s, (strm.adler >> 8) & 0xff);
  22012. put_byte(s, (strm.adler >> 16) & 0xff);
  22013. put_byte(s, (strm.adler >> 24) & 0xff);
  22014. put_byte(s, strm.total_in & 0xff);
  22015. put_byte(s, (strm.total_in >> 8) & 0xff);
  22016. put_byte(s, (strm.total_in >> 16) & 0xff);
  22017. put_byte(s, (strm.total_in >> 24) & 0xff);
  22018. }
  22019. else
  22020. {
  22021. putShortMSB(s, strm.adler >>> 16);
  22022. putShortMSB(s, strm.adler & 0xffff);
  22023. }
  22024. flush_pending(strm);
  22025. /* If avail_out is zero, the application will call deflate again
  22026. * to flush the rest.
  22027. */
  22028. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22029. /* write the trailer only once! */
  22030. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22031. }
  22032. function deflateEnd(strm) {
  22033. var status;
  22034. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22035. return Z_STREAM_ERROR;
  22036. }
  22037. status = strm.state.status;
  22038. if (status !== INIT_STATE &&
  22039. status !== EXTRA_STATE &&
  22040. status !== NAME_STATE &&
  22041. status !== COMMENT_STATE &&
  22042. status !== HCRC_STATE &&
  22043. status !== BUSY_STATE &&
  22044. status !== FINISH_STATE
  22045. ) {
  22046. return err(strm, Z_STREAM_ERROR);
  22047. }
  22048. strm.state = null;
  22049. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22050. }
  22051. /* =========================================================================
  22052. * Copy the source state to the destination state
  22053. */
  22054. //function deflateCopy(dest, source) {
  22055. //
  22056. //}
  22057. exports.deflateInit = deflateInit;
  22058. exports.deflateInit2 = deflateInit2;
  22059. exports.deflateReset = deflateReset;
  22060. exports.deflateResetKeep = deflateResetKeep;
  22061. exports.deflateSetHeader = deflateSetHeader;
  22062. exports.deflate = deflate;
  22063. exports.deflateEnd = deflateEnd;
  22064. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22065. /* Not implemented
  22066. exports.deflateBound = deflateBound;
  22067. exports.deflateCopy = deflateCopy;
  22068. exports.deflateSetDictionary = deflateSetDictionary;
  22069. exports.deflateParams = deflateParams;
  22070. exports.deflatePending = deflatePending;
  22071. exports.deflatePrime = deflatePrime;
  22072. exports.deflateTune = deflateTune;
  22073. */
  22074. },{"../utils/common":73,"./adler32":75,"./crc32":77,"./messages":83,"./trees":84}],79:[function(require,module,exports){
  22075. 'use strict';
  22076. function GZheader() {
  22077. /* true if compressed data believed to be text */
  22078. this.text = 0;
  22079. /* modification time */
  22080. this.time = 0;
  22081. /* extra flags (not used when writing a gzip file) */
  22082. this.xflags = 0;
  22083. /* operating system */
  22084. this.os = 0;
  22085. /* pointer to extra field or Z_NULL if none */
  22086. this.extra = null;
  22087. /* extra field length (valid if extra != Z_NULL) */
  22088. this.extra_len = 0; // Actually, we don't need it in JS,
  22089. // but leave for few code modifications
  22090. //
  22091. // Setup limits is not necessary because in js we should not preallocate memory
  22092. // for inflate use constant limit in 65536 bytes
  22093. //
  22094. /* space at extra (only when reading header) */
  22095. // this.extra_max = 0;
  22096. /* pointer to zero-terminated file name or Z_NULL */
  22097. this.name = '';
  22098. /* space at name (only when reading header) */
  22099. // this.name_max = 0;
  22100. /* pointer to zero-terminated comment or Z_NULL */
  22101. this.comment = '';
  22102. /* space at comment (only when reading header) */
  22103. // this.comm_max = 0;
  22104. /* true if there was or will be a header crc */
  22105. this.hcrc = 0;
  22106. /* true when done reading gzip header (not used when writing a gzip file) */
  22107. this.done = false;
  22108. }
  22109. module.exports = GZheader;
  22110. },{}],80:[function(require,module,exports){
  22111. 'use strict';
  22112. // See state defs from inflate.js
  22113. var BAD = 30; /* got a data error -- remain here until reset */
  22114. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22115. /*
  22116. Decode literal, length, and distance codes and write out the resulting
  22117. literal and match bytes until either not enough input or output is
  22118. available, an end-of-block is encountered, or a data error is encountered.
  22119. When large enough input and output buffers are supplied to inflate(), for
  22120. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22121. inflate execution time is spent in this routine.
  22122. Entry assumptions:
  22123. state.mode === LEN
  22124. strm.avail_in >= 6
  22125. strm.avail_out >= 258
  22126. start >= strm.avail_out
  22127. state.bits < 8
  22128. On return, state.mode is one of:
  22129. LEN -- ran out of enough output space or enough available input
  22130. TYPE -- reached end of block code, inflate() to interpret next block
  22131. BAD -- error in block data
  22132. Notes:
  22133. - The maximum input bits used by a length/distance pair is 15 bits for the
  22134. length code, 5 bits for the length extra, 15 bits for the distance code,
  22135. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22136. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22137. checking for available input while decoding.
  22138. - The maximum bytes that a single length/distance pair can output is 258
  22139. bytes, which is the maximum length that can be coded. inflate_fast()
  22140. requires strm.avail_out >= 258 for each loop to avoid checking for
  22141. output space.
  22142. */
  22143. module.exports = function inflate_fast(strm, start) {
  22144. var state;
  22145. var _in; /* local strm.input */
  22146. var last; /* have enough input while in < last */
  22147. var _out; /* local strm.output */
  22148. var beg; /* inflate()'s initial strm.output */
  22149. var end; /* while out < end, enough space available */
  22150. //#ifdef INFLATE_STRICT
  22151. var dmax; /* maximum distance from zlib header */
  22152. //#endif
  22153. var wsize; /* window size or zero if not using window */
  22154. var whave; /* valid bytes in the window */
  22155. var wnext; /* window write index */
  22156. var window; /* allocated sliding window, if wsize != 0 */
  22157. var hold; /* local strm.hold */
  22158. var bits; /* local strm.bits */
  22159. var lcode; /* local strm.lencode */
  22160. var dcode; /* local strm.distcode */
  22161. var lmask; /* mask for first level of length codes */
  22162. var dmask; /* mask for first level of distance codes */
  22163. var here; /* retrieved table entry */
  22164. var op; /* code bits, operation, extra bits, or */
  22165. /* window position, window bytes to copy */
  22166. var len; /* match length, unused bytes */
  22167. var dist; /* match distance */
  22168. var from; /* where to copy match from */
  22169. var from_source;
  22170. var input, output; // JS specific, because we have no pointers
  22171. /* copy state to local variables */
  22172. state = strm.state;
  22173. //here = state.here;
  22174. _in = strm.next_in;
  22175. input = strm.input;
  22176. last = _in + (strm.avail_in - 5);
  22177. _out = strm.next_out;
  22178. output = strm.output;
  22179. beg = _out - (start - strm.avail_out);
  22180. end = _out + (strm.avail_out - 257);
  22181. //#ifdef INFLATE_STRICT
  22182. dmax = state.dmax;
  22183. //#endif
  22184. wsize = state.wsize;
  22185. whave = state.whave;
  22186. wnext = state.wnext;
  22187. window = state.window;
  22188. hold = state.hold;
  22189. bits = state.bits;
  22190. lcode = state.lencode;
  22191. dcode = state.distcode;
  22192. lmask = (1 << state.lenbits) - 1;
  22193. dmask = (1 << state.distbits) - 1;
  22194. /* decode literals and length/distances until end-of-block or not enough
  22195. input data or output space */
  22196. top:
  22197. do {
  22198. if (bits < 15) {
  22199. hold += input[_in++] << bits;
  22200. bits += 8;
  22201. hold += input[_in++] << bits;
  22202. bits += 8;
  22203. }
  22204. here = lcode[hold & lmask];
  22205. dolen:
  22206. for (;;) { // Goto emulation
  22207. op = here >>> 24/*here.bits*/;
  22208. hold >>>= op;
  22209. bits -= op;
  22210. op = (here >>> 16) & 0xff/*here.op*/;
  22211. if (op === 0) { /* literal */
  22212. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22213. // "inflate: literal '%c'\n" :
  22214. // "inflate: literal 0x%02x\n", here.val));
  22215. output[_out++] = here & 0xffff/*here.val*/;
  22216. }
  22217. else if (op & 16) { /* length base */
  22218. len = here & 0xffff/*here.val*/;
  22219. op &= 15; /* number of extra bits */
  22220. if (op) {
  22221. if (bits < op) {
  22222. hold += input[_in++] << bits;
  22223. bits += 8;
  22224. }
  22225. len += hold & ((1 << op) - 1);
  22226. hold >>>= op;
  22227. bits -= op;
  22228. }
  22229. //Tracevv((stderr, "inflate: length %u\n", len));
  22230. if (bits < 15) {
  22231. hold += input[_in++] << bits;
  22232. bits += 8;
  22233. hold += input[_in++] << bits;
  22234. bits += 8;
  22235. }
  22236. here = dcode[hold & dmask];
  22237. dodist:
  22238. for (;;) { // goto emulation
  22239. op = here >>> 24/*here.bits*/;
  22240. hold >>>= op;
  22241. bits -= op;
  22242. op = (here >>> 16) & 0xff/*here.op*/;
  22243. if (op & 16) { /* distance base */
  22244. dist = here & 0xffff/*here.val*/;
  22245. op &= 15; /* number of extra bits */
  22246. if (bits < op) {
  22247. hold += input[_in++] << bits;
  22248. bits += 8;
  22249. if (bits < op) {
  22250. hold += input[_in++] << bits;
  22251. bits += 8;
  22252. }
  22253. }
  22254. dist += hold & ((1 << op) - 1);
  22255. //#ifdef INFLATE_STRICT
  22256. if (dist > dmax) {
  22257. strm.msg = 'invalid distance too far back';
  22258. state.mode = BAD;
  22259. break top;
  22260. }
  22261. //#endif
  22262. hold >>>= op;
  22263. bits -= op;
  22264. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22265. op = _out - beg; /* max distance in output */
  22266. if (dist > op) { /* see if copy from window */
  22267. op = dist - op; /* distance back in window */
  22268. if (op > whave) {
  22269. if (state.sane) {
  22270. strm.msg = 'invalid distance too far back';
  22271. state.mode = BAD;
  22272. break top;
  22273. }
  22274. // (!) This block is disabled in zlib defailts,
  22275. // don't enable it for binary compatibility
  22276. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22277. // if (len <= op - whave) {
  22278. // do {
  22279. // output[_out++] = 0;
  22280. // } while (--len);
  22281. // continue top;
  22282. // }
  22283. // len -= op - whave;
  22284. // do {
  22285. // output[_out++] = 0;
  22286. // } while (--op > whave);
  22287. // if (op === 0) {
  22288. // from = _out - dist;
  22289. // do {
  22290. // output[_out++] = output[from++];
  22291. // } while (--len);
  22292. // continue top;
  22293. // }
  22294. //#endif
  22295. }
  22296. from = 0; // window index
  22297. from_source = window;
  22298. if (wnext === 0) { /* very common case */
  22299. from += wsize - op;
  22300. if (op < len) { /* some from window */
  22301. len -= op;
  22302. do {
  22303. output[_out++] = window[from++];
  22304. } while (--op);
  22305. from = _out - dist; /* rest from output */
  22306. from_source = output;
  22307. }
  22308. }
  22309. else if (wnext < op) { /* wrap around window */
  22310. from += wsize + wnext - op;
  22311. op -= wnext;
  22312. if (op < len) { /* some from end of window */
  22313. len -= op;
  22314. do {
  22315. output[_out++] = window[from++];
  22316. } while (--op);
  22317. from = 0;
  22318. if (wnext < len) { /* some from start of window */
  22319. op = wnext;
  22320. len -= op;
  22321. do {
  22322. output[_out++] = window[from++];
  22323. } while (--op);
  22324. from = _out - dist; /* rest from output */
  22325. from_source = output;
  22326. }
  22327. }
  22328. }
  22329. else { /* contiguous in window */
  22330. from += wnext - op;
  22331. if (op < len) { /* some from window */
  22332. len -= op;
  22333. do {
  22334. output[_out++] = window[from++];
  22335. } while (--op);
  22336. from = _out - dist; /* rest from output */
  22337. from_source = output;
  22338. }
  22339. }
  22340. while (len > 2) {
  22341. output[_out++] = from_source[from++];
  22342. output[_out++] = from_source[from++];
  22343. output[_out++] = from_source[from++];
  22344. len -= 3;
  22345. }
  22346. if (len) {
  22347. output[_out++] = from_source[from++];
  22348. if (len > 1) {
  22349. output[_out++] = from_source[from++];
  22350. }
  22351. }
  22352. }
  22353. else {
  22354. from = _out - dist; /* copy direct from output */
  22355. do { /* minimum length is three */
  22356. output[_out++] = output[from++];
  22357. output[_out++] = output[from++];
  22358. output[_out++] = output[from++];
  22359. len -= 3;
  22360. } while (len > 2);
  22361. if (len) {
  22362. output[_out++] = output[from++];
  22363. if (len > 1) {
  22364. output[_out++] = output[from++];
  22365. }
  22366. }
  22367. }
  22368. }
  22369. else if ((op & 64) === 0) { /* 2nd level distance code */
  22370. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22371. continue dodist;
  22372. }
  22373. else {
  22374. strm.msg = 'invalid distance code';
  22375. state.mode = BAD;
  22376. break top;
  22377. }
  22378. break; // need to emulate goto via "continue"
  22379. }
  22380. }
  22381. else if ((op & 64) === 0) { /* 2nd level length code */
  22382. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22383. continue dolen;
  22384. }
  22385. else if (op & 32) { /* end-of-block */
  22386. //Tracevv((stderr, "inflate: end of block\n"));
  22387. state.mode = TYPE;
  22388. break top;
  22389. }
  22390. else {
  22391. strm.msg = 'invalid literal/length code';
  22392. state.mode = BAD;
  22393. break top;
  22394. }
  22395. break; // need to emulate goto via "continue"
  22396. }
  22397. } while (_in < last && _out < end);
  22398. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22399. len = bits >> 3;
  22400. _in -= len;
  22401. bits -= len << 3;
  22402. hold &= (1 << bits) - 1;
  22403. /* update state and return */
  22404. strm.next_in = _in;
  22405. strm.next_out = _out;
  22406. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22407. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22408. state.hold = hold;
  22409. state.bits = bits;
  22410. return;
  22411. };
  22412. },{}],81:[function(require,module,exports){
  22413. 'use strict';
  22414. var utils = require('../utils/common');
  22415. var adler32 = require('./adler32');
  22416. var crc32 = require('./crc32');
  22417. var inflate_fast = require('./inffast');
  22418. var inflate_table = require('./inftrees');
  22419. var CODES = 0;
  22420. var LENS = 1;
  22421. var DISTS = 2;
  22422. /* Public constants ==========================================================*/
  22423. /* ===========================================================================*/
  22424. /* Allowed flush values; see deflate() and inflate() below for details */
  22425. //var Z_NO_FLUSH = 0;
  22426. //var Z_PARTIAL_FLUSH = 1;
  22427. //var Z_SYNC_FLUSH = 2;
  22428. //var Z_FULL_FLUSH = 3;
  22429. var Z_FINISH = 4;
  22430. var Z_BLOCK = 5;
  22431. var Z_TREES = 6;
  22432. /* Return codes for the compression/decompression functions. Negative values
  22433. * are errors, positive values are used for special but normal events.
  22434. */
  22435. var Z_OK = 0;
  22436. var Z_STREAM_END = 1;
  22437. var Z_NEED_DICT = 2;
  22438. //var Z_ERRNO = -1;
  22439. var Z_STREAM_ERROR = -2;
  22440. var Z_DATA_ERROR = -3;
  22441. var Z_MEM_ERROR = -4;
  22442. var Z_BUF_ERROR = -5;
  22443. //var Z_VERSION_ERROR = -6;
  22444. /* The deflate compression method */
  22445. var Z_DEFLATED = 8;
  22446. /* STATES ====================================================================*/
  22447. /* ===========================================================================*/
  22448. var HEAD = 1; /* i: waiting for magic header */
  22449. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22450. var TIME = 3; /* i: waiting for modification time (gzip) */
  22451. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22452. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22453. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22454. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22455. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22456. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22457. var DICTID = 10; /* i: waiting for dictionary check value */
  22458. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22459. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22460. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22461. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22462. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22463. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22464. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22465. var LENLENS = 18; /* i: waiting for code length code lengths */
  22466. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22467. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22468. var LEN = 21; /* i: waiting for length/lit/eob code */
  22469. var LENEXT = 22; /* i: waiting for length extra bits */
  22470. var DIST = 23; /* i: waiting for distance code */
  22471. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22472. var MATCH = 25; /* o: waiting for output space to copy string */
  22473. var LIT = 26; /* o: waiting for output space to write literal */
  22474. var CHECK = 27; /* i: waiting for 32-bit check value */
  22475. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22476. var DONE = 29; /* finished check, done -- remain here until reset */
  22477. var BAD = 30; /* got a data error -- remain here until reset */
  22478. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22479. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22480. /* ===========================================================================*/
  22481. var ENOUGH_LENS = 852;
  22482. var ENOUGH_DISTS = 592;
  22483. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22484. var MAX_WBITS = 15;
  22485. /* 32K LZ77 window */
  22486. var DEF_WBITS = MAX_WBITS;
  22487. function ZSWAP32(q) {
  22488. return (((q >>> 24) & 0xff) +
  22489. ((q >>> 8) & 0xff00) +
  22490. ((q & 0xff00) << 8) +
  22491. ((q & 0xff) << 24));
  22492. }
  22493. function InflateState() {
  22494. this.mode = 0; /* current inflate mode */
  22495. this.last = false; /* true if processing last block */
  22496. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22497. this.havedict = false; /* true if dictionary provided */
  22498. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22499. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22500. this.check = 0; /* protected copy of check value */
  22501. this.total = 0; /* protected copy of output count */
  22502. // TODO: may be {}
  22503. this.head = null; /* where to save gzip header information */
  22504. /* sliding window */
  22505. this.wbits = 0; /* log base 2 of requested window size */
  22506. this.wsize = 0; /* window size or zero if not using window */
  22507. this.whave = 0; /* valid bytes in the window */
  22508. this.wnext = 0; /* window write index */
  22509. this.window = null; /* allocated sliding window, if needed */
  22510. /* bit accumulator */
  22511. this.hold = 0; /* input bit accumulator */
  22512. this.bits = 0; /* number of bits in "in" */
  22513. /* for string and stored block copying */
  22514. this.length = 0; /* literal or length of data to copy */
  22515. this.offset = 0; /* distance back to copy string from */
  22516. /* for table and code decoding */
  22517. this.extra = 0; /* extra bits needed */
  22518. /* fixed and dynamic code tables */
  22519. this.lencode = null; /* starting table for length/literal codes */
  22520. this.distcode = null; /* starting table for distance codes */
  22521. this.lenbits = 0; /* index bits for lencode */
  22522. this.distbits = 0; /* index bits for distcode */
  22523. /* dynamic table building */
  22524. this.ncode = 0; /* number of code length code lengths */
  22525. this.nlen = 0; /* number of length code lengths */
  22526. this.ndist = 0; /* number of distance code lengths */
  22527. this.have = 0; /* number of code lengths in lens[] */
  22528. this.next = null; /* next available space in codes[] */
  22529. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22530. this.work = new utils.Buf16(288); /* work area for code table building */
  22531. /*
  22532. because we don't have pointers in js, we use lencode and distcode directly
  22533. as buffers so we don't need codes
  22534. */
  22535. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22536. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22537. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22538. this.sane = 0; /* if false, allow invalid distance too far */
  22539. this.back = 0; /* bits back of last unprocessed length/lit */
  22540. this.was = 0; /* initial length of match */
  22541. }
  22542. function inflateResetKeep(strm) {
  22543. var state;
  22544. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22545. state = strm.state;
  22546. strm.total_in = strm.total_out = state.total = 0;
  22547. strm.msg = ''; /*Z_NULL*/
  22548. if (state.wrap) { /* to support ill-conceived Java test suite */
  22549. strm.adler = state.wrap & 1;
  22550. }
  22551. state.mode = HEAD;
  22552. state.last = 0;
  22553. state.havedict = 0;
  22554. state.dmax = 32768;
  22555. state.head = null/*Z_NULL*/;
  22556. state.hold = 0;
  22557. state.bits = 0;
  22558. //state.lencode = state.distcode = state.next = state.codes;
  22559. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22560. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22561. state.sane = 1;
  22562. state.back = -1;
  22563. //Tracev((stderr, "inflate: reset\n"));
  22564. return Z_OK;
  22565. }
  22566. function inflateReset(strm) {
  22567. var state;
  22568. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22569. state = strm.state;
  22570. state.wsize = 0;
  22571. state.whave = 0;
  22572. state.wnext = 0;
  22573. return inflateResetKeep(strm);
  22574. }
  22575. function inflateReset2(strm, windowBits) {
  22576. var wrap;
  22577. var state;
  22578. /* get the state */
  22579. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22580. state = strm.state;
  22581. /* extract wrap request from windowBits parameter */
  22582. if (windowBits < 0) {
  22583. wrap = 0;
  22584. windowBits = -windowBits;
  22585. }
  22586. else {
  22587. wrap = (windowBits >> 4) + 1;
  22588. if (windowBits < 48) {
  22589. windowBits &= 15;
  22590. }
  22591. }
  22592. /* set number of window bits, free window if different */
  22593. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22594. return Z_STREAM_ERROR;
  22595. }
  22596. if (state.window !== null && state.wbits !== windowBits) {
  22597. state.window = null;
  22598. }
  22599. /* update state and reset the rest of it */
  22600. state.wrap = wrap;
  22601. state.wbits = windowBits;
  22602. return inflateReset(strm);
  22603. }
  22604. function inflateInit2(strm, windowBits) {
  22605. var ret;
  22606. var state;
  22607. if (!strm) { return Z_STREAM_ERROR; }
  22608. //strm.msg = Z_NULL; /* in case we return an error */
  22609. state = new InflateState();
  22610. //if (state === Z_NULL) return Z_MEM_ERROR;
  22611. //Tracev((stderr, "inflate: allocated\n"));
  22612. strm.state = state;
  22613. state.window = null/*Z_NULL*/;
  22614. ret = inflateReset2(strm, windowBits);
  22615. if (ret !== Z_OK) {
  22616. strm.state = null/*Z_NULL*/;
  22617. }
  22618. return ret;
  22619. }
  22620. function inflateInit(strm) {
  22621. return inflateInit2(strm, DEF_WBITS);
  22622. }
  22623. /*
  22624. Return state with length and distance decoding tables and index sizes set to
  22625. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22626. If BUILDFIXED is defined, then instead this routine builds the tables the
  22627. first time it's called, and returns those tables the first time and
  22628. thereafter. This reduces the size of the code by about 2K bytes, in
  22629. exchange for a little execution time. However, BUILDFIXED should not be
  22630. used for threaded applications, since the rewriting of the tables and virgin
  22631. may not be thread-safe.
  22632. */
  22633. var virgin = true;
  22634. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22635. function fixedtables(state) {
  22636. /* build fixed huffman tables if first call (may not be thread safe) */
  22637. if (virgin) {
  22638. var sym;
  22639. lenfix = new utils.Buf32(512);
  22640. distfix = new utils.Buf32(32);
  22641. /* literal/length table */
  22642. sym = 0;
  22643. while (sym < 144) { state.lens[sym++] = 8; }
  22644. while (sym < 256) { state.lens[sym++] = 9; }
  22645. while (sym < 280) { state.lens[sym++] = 7; }
  22646. while (sym < 288) { state.lens[sym++] = 8; }
  22647. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22648. /* distance table */
  22649. sym = 0;
  22650. while (sym < 32) { state.lens[sym++] = 5; }
  22651. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22652. /* do this just once */
  22653. virgin = false;
  22654. }
  22655. state.lencode = lenfix;
  22656. state.lenbits = 9;
  22657. state.distcode = distfix;
  22658. state.distbits = 5;
  22659. }
  22660. /*
  22661. Update the window with the last wsize (normally 32K) bytes written before
  22662. returning. If window does not exist yet, create it. This is only called
  22663. when a window is already in use, or when output has been written during this
  22664. inflate call, but the end of the deflate stream has not been reached yet.
  22665. It is also called to create a window for dictionary data when a dictionary
  22666. is loaded.
  22667. Providing output buffers larger than 32K to inflate() should provide a speed
  22668. advantage, since only the last 32K of output is copied to the sliding window
  22669. upon return from inflate(), and since all distances after the first 32K of
  22670. output will fall in the output data, making match copies simpler and faster.
  22671. The advantage may be dependent on the size of the processor's data caches.
  22672. */
  22673. function updatewindow(strm, src, end, copy) {
  22674. var dist;
  22675. var state = strm.state;
  22676. /* if it hasn't been done already, allocate space for the window */
  22677. if (state.window === null) {
  22678. state.wsize = 1 << state.wbits;
  22679. state.wnext = 0;
  22680. state.whave = 0;
  22681. state.window = new utils.Buf8(state.wsize);
  22682. }
  22683. /* copy state->wsize or less output bytes into the circular window */
  22684. if (copy >= state.wsize) {
  22685. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22686. state.wnext = 0;
  22687. state.whave = state.wsize;
  22688. }
  22689. else {
  22690. dist = state.wsize - state.wnext;
  22691. if (dist > copy) {
  22692. dist = copy;
  22693. }
  22694. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22695. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22696. copy -= dist;
  22697. if (copy) {
  22698. //zmemcpy(state->window, end - copy, copy);
  22699. utils.arraySet(state.window,src, end - copy, copy, 0);
  22700. state.wnext = copy;
  22701. state.whave = state.wsize;
  22702. }
  22703. else {
  22704. state.wnext += dist;
  22705. if (state.wnext === state.wsize) { state.wnext = 0; }
  22706. if (state.whave < state.wsize) { state.whave += dist; }
  22707. }
  22708. }
  22709. return 0;
  22710. }
  22711. function inflate(strm, flush) {
  22712. var state;
  22713. var input, output; // input/output buffers
  22714. var next; /* next input INDEX */
  22715. var put; /* next output INDEX */
  22716. var have, left; /* available input and output */
  22717. var hold; /* bit buffer */
  22718. var bits; /* bits in bit buffer */
  22719. var _in, _out; /* save starting available input and output */
  22720. var copy; /* number of stored or match bytes to copy */
  22721. var from; /* where to copy match bytes from */
  22722. var from_source;
  22723. var here = 0; /* current decoding table entry */
  22724. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22725. //var last; /* parent table entry */
  22726. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22727. var len; /* length to copy for repeats, bits to drop */
  22728. var ret; /* return code */
  22729. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22730. var opts;
  22731. var n; // temporary var for NEED_BITS
  22732. var order = /* permutation of code lengths */
  22733. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22734. if (!strm || !strm.state || !strm.output ||
  22735. (!strm.input && strm.avail_in !== 0)) {
  22736. return Z_STREAM_ERROR;
  22737. }
  22738. state = strm.state;
  22739. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22740. //--- LOAD() ---
  22741. put = strm.next_out;
  22742. output = strm.output;
  22743. left = strm.avail_out;
  22744. next = strm.next_in;
  22745. input = strm.input;
  22746. have = strm.avail_in;
  22747. hold = state.hold;
  22748. bits = state.bits;
  22749. //---
  22750. _in = have;
  22751. _out = left;
  22752. ret = Z_OK;
  22753. inf_leave: // goto emulation
  22754. for (;;) {
  22755. switch (state.mode) {
  22756. case HEAD:
  22757. if (state.wrap === 0) {
  22758. state.mode = TYPEDO;
  22759. break;
  22760. }
  22761. //=== NEEDBITS(16);
  22762. while (bits < 16) {
  22763. if (have === 0) { break inf_leave; }
  22764. have--;
  22765. hold += input[next++] << bits;
  22766. bits += 8;
  22767. }
  22768. //===//
  22769. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22770. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22771. //=== CRC2(state.check, hold);
  22772. hbuf[0] = hold & 0xff;
  22773. hbuf[1] = (hold >>> 8) & 0xff;
  22774. state.check = crc32(state.check, hbuf, 2, 0);
  22775. //===//
  22776. //=== INITBITS();
  22777. hold = 0;
  22778. bits = 0;
  22779. //===//
  22780. state.mode = FLAGS;
  22781. break;
  22782. }
  22783. state.flags = 0; /* expect zlib header */
  22784. if (state.head) {
  22785. state.head.done = false;
  22786. }
  22787. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22788. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22789. strm.msg = 'incorrect header check';
  22790. state.mode = BAD;
  22791. break;
  22792. }
  22793. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22794. strm.msg = 'unknown compression method';
  22795. state.mode = BAD;
  22796. break;
  22797. }
  22798. //--- DROPBITS(4) ---//
  22799. hold >>>= 4;
  22800. bits -= 4;
  22801. //---//
  22802. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22803. if (state.wbits === 0) {
  22804. state.wbits = len;
  22805. }
  22806. else if (len > state.wbits) {
  22807. strm.msg = 'invalid window size';
  22808. state.mode = BAD;
  22809. break;
  22810. }
  22811. state.dmax = 1 << len;
  22812. //Tracev((stderr, "inflate: zlib header ok\n"));
  22813. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22814. state.mode = hold & 0x200 ? DICTID : TYPE;
  22815. //=== INITBITS();
  22816. hold = 0;
  22817. bits = 0;
  22818. //===//
  22819. break;
  22820. case FLAGS:
  22821. //=== NEEDBITS(16); */
  22822. while (bits < 16) {
  22823. if (have === 0) { break inf_leave; }
  22824. have--;
  22825. hold += input[next++] << bits;
  22826. bits += 8;
  22827. }
  22828. //===//
  22829. state.flags = hold;
  22830. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22831. strm.msg = 'unknown compression method';
  22832. state.mode = BAD;
  22833. break;
  22834. }
  22835. if (state.flags & 0xe000) {
  22836. strm.msg = 'unknown header flags set';
  22837. state.mode = BAD;
  22838. break;
  22839. }
  22840. if (state.head) {
  22841. state.head.text = ((hold >> 8) & 1);
  22842. }
  22843. if (state.flags & 0x0200) {
  22844. //=== CRC2(state.check, hold);
  22845. hbuf[0] = hold & 0xff;
  22846. hbuf[1] = (hold >>> 8) & 0xff;
  22847. state.check = crc32(state.check, hbuf, 2, 0);
  22848. //===//
  22849. }
  22850. //=== INITBITS();
  22851. hold = 0;
  22852. bits = 0;
  22853. //===//
  22854. state.mode = TIME;
  22855. /* falls through */
  22856. case TIME:
  22857. //=== NEEDBITS(32); */
  22858. while (bits < 32) {
  22859. if (have === 0) { break inf_leave; }
  22860. have--;
  22861. hold += input[next++] << bits;
  22862. bits += 8;
  22863. }
  22864. //===//
  22865. if (state.head) {
  22866. state.head.time = hold;
  22867. }
  22868. if (state.flags & 0x0200) {
  22869. //=== CRC4(state.check, hold)
  22870. hbuf[0] = hold & 0xff;
  22871. hbuf[1] = (hold >>> 8) & 0xff;
  22872. hbuf[2] = (hold >>> 16) & 0xff;
  22873. hbuf[3] = (hold >>> 24) & 0xff;
  22874. state.check = crc32(state.check, hbuf, 4, 0);
  22875. //===
  22876. }
  22877. //=== INITBITS();
  22878. hold = 0;
  22879. bits = 0;
  22880. //===//
  22881. state.mode = OS;
  22882. /* falls through */
  22883. case OS:
  22884. //=== NEEDBITS(16); */
  22885. while (bits < 16) {
  22886. if (have === 0) { break inf_leave; }
  22887. have--;
  22888. hold += input[next++] << bits;
  22889. bits += 8;
  22890. }
  22891. //===//
  22892. if (state.head) {
  22893. state.head.xflags = (hold & 0xff);
  22894. state.head.os = (hold >> 8);
  22895. }
  22896. if (state.flags & 0x0200) {
  22897. //=== CRC2(state.check, hold);
  22898. hbuf[0] = hold & 0xff;
  22899. hbuf[1] = (hold >>> 8) & 0xff;
  22900. state.check = crc32(state.check, hbuf, 2, 0);
  22901. //===//
  22902. }
  22903. //=== INITBITS();
  22904. hold = 0;
  22905. bits = 0;
  22906. //===//
  22907. state.mode = EXLEN;
  22908. /* falls through */
  22909. case EXLEN:
  22910. if (state.flags & 0x0400) {
  22911. //=== NEEDBITS(16); */
  22912. while (bits < 16) {
  22913. if (have === 0) { break inf_leave; }
  22914. have--;
  22915. hold += input[next++] << bits;
  22916. bits += 8;
  22917. }
  22918. //===//
  22919. state.length = hold;
  22920. if (state.head) {
  22921. state.head.extra_len = hold;
  22922. }
  22923. if (state.flags & 0x0200) {
  22924. //=== CRC2(state.check, hold);
  22925. hbuf[0] = hold & 0xff;
  22926. hbuf[1] = (hold >>> 8) & 0xff;
  22927. state.check = crc32(state.check, hbuf, 2, 0);
  22928. //===//
  22929. }
  22930. //=== INITBITS();
  22931. hold = 0;
  22932. bits = 0;
  22933. //===//
  22934. }
  22935. else if (state.head) {
  22936. state.head.extra = null/*Z_NULL*/;
  22937. }
  22938. state.mode = EXTRA;
  22939. /* falls through */
  22940. case EXTRA:
  22941. if (state.flags & 0x0400) {
  22942. copy = state.length;
  22943. if (copy > have) { copy = have; }
  22944. if (copy) {
  22945. if (state.head) {
  22946. len = state.head.extra_len - state.length;
  22947. if (!state.head.extra) {
  22948. // Use untyped array for more conveniend processing later
  22949. state.head.extra = new Array(state.head.extra_len);
  22950. }
  22951. utils.arraySet(
  22952. state.head.extra,
  22953. input,
  22954. next,
  22955. // extra field is limited to 65536 bytes
  22956. // - no need for additional size check
  22957. copy,
  22958. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22959. len
  22960. );
  22961. //zmemcpy(state.head.extra + len, next,
  22962. // len + copy > state.head.extra_max ?
  22963. // state.head.extra_max - len : copy);
  22964. }
  22965. if (state.flags & 0x0200) {
  22966. state.check = crc32(state.check, input, copy, next);
  22967. }
  22968. have -= copy;
  22969. next += copy;
  22970. state.length -= copy;
  22971. }
  22972. if (state.length) { break inf_leave; }
  22973. }
  22974. state.length = 0;
  22975. state.mode = NAME;
  22976. /* falls through */
  22977. case NAME:
  22978. if (state.flags & 0x0800) {
  22979. if (have === 0) { break inf_leave; }
  22980. copy = 0;
  22981. do {
  22982. // TODO: 2 or 1 bytes?
  22983. len = input[next + copy++];
  22984. /* use constant limit because in js we should not preallocate memory */
  22985. if (state.head && len &&
  22986. (state.length < 65536 /*state.head.name_max*/)) {
  22987. state.head.name += String.fromCharCode(len);
  22988. }
  22989. } while (len && copy < have);
  22990. if (state.flags & 0x0200) {
  22991. state.check = crc32(state.check, input, copy, next);
  22992. }
  22993. have -= copy;
  22994. next += copy;
  22995. if (len) { break inf_leave; }
  22996. }
  22997. else if (state.head) {
  22998. state.head.name = null;
  22999. }
  23000. state.length = 0;
  23001. state.mode = COMMENT;
  23002. /* falls through */
  23003. case COMMENT:
  23004. if (state.flags & 0x1000) {
  23005. if (have === 0) { break inf_leave; }
  23006. copy = 0;
  23007. do {
  23008. len = input[next + copy++];
  23009. /* use constant limit because in js we should not preallocate memory */
  23010. if (state.head && len &&
  23011. (state.length < 65536 /*state.head.comm_max*/)) {
  23012. state.head.comment += String.fromCharCode(len);
  23013. }
  23014. } while (len && copy < have);
  23015. if (state.flags & 0x0200) {
  23016. state.check = crc32(state.check, input, copy, next);
  23017. }
  23018. have -= copy;
  23019. next += copy;
  23020. if (len) { break inf_leave; }
  23021. }
  23022. else if (state.head) {
  23023. state.head.comment = null;
  23024. }
  23025. state.mode = HCRC;
  23026. /* falls through */
  23027. case HCRC:
  23028. if (state.flags & 0x0200) {
  23029. //=== NEEDBITS(16); */
  23030. while (bits < 16) {
  23031. if (have === 0) { break inf_leave; }
  23032. have--;
  23033. hold += input[next++] << bits;
  23034. bits += 8;
  23035. }
  23036. //===//
  23037. if (hold !== (state.check & 0xffff)) {
  23038. strm.msg = 'header crc mismatch';
  23039. state.mode = BAD;
  23040. break;
  23041. }
  23042. //=== INITBITS();
  23043. hold = 0;
  23044. bits = 0;
  23045. //===//
  23046. }
  23047. if (state.head) {
  23048. state.head.hcrc = ((state.flags >> 9) & 1);
  23049. state.head.done = true;
  23050. }
  23051. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23052. state.mode = TYPE;
  23053. break;
  23054. case DICTID:
  23055. //=== NEEDBITS(32); */
  23056. while (bits < 32) {
  23057. if (have === 0) { break inf_leave; }
  23058. have--;
  23059. hold += input[next++] << bits;
  23060. bits += 8;
  23061. }
  23062. //===//
  23063. strm.adler = state.check = ZSWAP32(hold);
  23064. //=== INITBITS();
  23065. hold = 0;
  23066. bits = 0;
  23067. //===//
  23068. state.mode = DICT;
  23069. /* falls through */
  23070. case DICT:
  23071. if (state.havedict === 0) {
  23072. //--- RESTORE() ---
  23073. strm.next_out = put;
  23074. strm.avail_out = left;
  23075. strm.next_in = next;
  23076. strm.avail_in = have;
  23077. state.hold = hold;
  23078. state.bits = bits;
  23079. //---
  23080. return Z_NEED_DICT;
  23081. }
  23082. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23083. state.mode = TYPE;
  23084. /* falls through */
  23085. case TYPE:
  23086. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23087. /* falls through */
  23088. case TYPEDO:
  23089. if (state.last) {
  23090. //--- BYTEBITS() ---//
  23091. hold >>>= bits & 7;
  23092. bits -= bits & 7;
  23093. //---//
  23094. state.mode = CHECK;
  23095. break;
  23096. }
  23097. //=== NEEDBITS(3); */
  23098. while (bits < 3) {
  23099. if (have === 0) { break inf_leave; }
  23100. have--;
  23101. hold += input[next++] << bits;
  23102. bits += 8;
  23103. }
  23104. //===//
  23105. state.last = (hold & 0x01)/*BITS(1)*/;
  23106. //--- DROPBITS(1) ---//
  23107. hold >>>= 1;
  23108. bits -= 1;
  23109. //---//
  23110. switch ((hold & 0x03)/*BITS(2)*/) {
  23111. case 0: /* stored block */
  23112. //Tracev((stderr, "inflate: stored block%s\n",
  23113. // state.last ? " (last)" : ""));
  23114. state.mode = STORED;
  23115. break;
  23116. case 1: /* fixed block */
  23117. fixedtables(state);
  23118. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23119. // state.last ? " (last)" : ""));
  23120. state.mode = LEN_; /* decode codes */
  23121. if (flush === Z_TREES) {
  23122. //--- DROPBITS(2) ---//
  23123. hold >>>= 2;
  23124. bits -= 2;
  23125. //---//
  23126. break inf_leave;
  23127. }
  23128. break;
  23129. case 2: /* dynamic block */
  23130. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23131. // state.last ? " (last)" : ""));
  23132. state.mode = TABLE;
  23133. break;
  23134. case 3:
  23135. strm.msg = 'invalid block type';
  23136. state.mode = BAD;
  23137. }
  23138. //--- DROPBITS(2) ---//
  23139. hold >>>= 2;
  23140. bits -= 2;
  23141. //---//
  23142. break;
  23143. case STORED:
  23144. //--- BYTEBITS() ---// /* go to byte boundary */
  23145. hold >>>= bits & 7;
  23146. bits -= bits & 7;
  23147. //---//
  23148. //=== NEEDBITS(32); */
  23149. while (bits < 32) {
  23150. if (have === 0) { break inf_leave; }
  23151. have--;
  23152. hold += input[next++] << bits;
  23153. bits += 8;
  23154. }
  23155. //===//
  23156. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23157. strm.msg = 'invalid stored block lengths';
  23158. state.mode = BAD;
  23159. break;
  23160. }
  23161. state.length = hold & 0xffff;
  23162. //Tracev((stderr, "inflate: stored length %u\n",
  23163. // state.length));
  23164. //=== INITBITS();
  23165. hold = 0;
  23166. bits = 0;
  23167. //===//
  23168. state.mode = COPY_;
  23169. if (flush === Z_TREES) { break inf_leave; }
  23170. /* falls through */
  23171. case COPY_:
  23172. state.mode = COPY;
  23173. /* falls through */
  23174. case COPY:
  23175. copy = state.length;
  23176. if (copy) {
  23177. if (copy > have) { copy = have; }
  23178. if (copy > left) { copy = left; }
  23179. if (copy === 0) { break inf_leave; }
  23180. //--- zmemcpy(put, next, copy); ---
  23181. utils.arraySet(output, input, next, copy, put);
  23182. //---//
  23183. have -= copy;
  23184. next += copy;
  23185. left -= copy;
  23186. put += copy;
  23187. state.length -= copy;
  23188. break;
  23189. }
  23190. //Tracev((stderr, "inflate: stored end\n"));
  23191. state.mode = TYPE;
  23192. break;
  23193. case TABLE:
  23194. //=== NEEDBITS(14); */
  23195. while (bits < 14) {
  23196. if (have === 0) { break inf_leave; }
  23197. have--;
  23198. hold += input[next++] << bits;
  23199. bits += 8;
  23200. }
  23201. //===//
  23202. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23203. //--- DROPBITS(5) ---//
  23204. hold >>>= 5;
  23205. bits -= 5;
  23206. //---//
  23207. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23208. //--- DROPBITS(5) ---//
  23209. hold >>>= 5;
  23210. bits -= 5;
  23211. //---//
  23212. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23213. //--- DROPBITS(4) ---//
  23214. hold >>>= 4;
  23215. bits -= 4;
  23216. //---//
  23217. //#ifndef PKZIP_BUG_WORKAROUND
  23218. if (state.nlen > 286 || state.ndist > 30) {
  23219. strm.msg = 'too many length or distance symbols';
  23220. state.mode = BAD;
  23221. break;
  23222. }
  23223. //#endif
  23224. //Tracev((stderr, "inflate: table sizes ok\n"));
  23225. state.have = 0;
  23226. state.mode = LENLENS;
  23227. /* falls through */
  23228. case LENLENS:
  23229. while (state.have < state.ncode) {
  23230. //=== NEEDBITS(3);
  23231. while (bits < 3) {
  23232. if (have === 0) { break inf_leave; }
  23233. have--;
  23234. hold += input[next++] << bits;
  23235. bits += 8;
  23236. }
  23237. //===//
  23238. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23239. //--- DROPBITS(3) ---//
  23240. hold >>>= 3;
  23241. bits -= 3;
  23242. //---//
  23243. }
  23244. while (state.have < 19) {
  23245. state.lens[order[state.have++]] = 0;
  23246. }
  23247. // We have separate tables & no pointers. 2 commented lines below not needed.
  23248. //state.next = state.codes;
  23249. //state.lencode = state.next;
  23250. // Switch to use dynamic table
  23251. state.lencode = state.lendyn;
  23252. state.lenbits = 7;
  23253. opts = {bits: state.lenbits};
  23254. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23255. state.lenbits = opts.bits;
  23256. if (ret) {
  23257. strm.msg = 'invalid code lengths set';
  23258. state.mode = BAD;
  23259. break;
  23260. }
  23261. //Tracev((stderr, "inflate: code lengths ok\n"));
  23262. state.have = 0;
  23263. state.mode = CODELENS;
  23264. /* falls through */
  23265. case CODELENS:
  23266. while (state.have < state.nlen + state.ndist) {
  23267. for (;;) {
  23268. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23269. here_bits = here >>> 24;
  23270. here_op = (here >>> 16) & 0xff;
  23271. here_val = here & 0xffff;
  23272. if ((here_bits) <= bits) { break; }
  23273. //--- PULLBYTE() ---//
  23274. if (have === 0) { break inf_leave; }
  23275. have--;
  23276. hold += input[next++] << bits;
  23277. bits += 8;
  23278. //---//
  23279. }
  23280. if (here_val < 16) {
  23281. //--- DROPBITS(here.bits) ---//
  23282. hold >>>= here_bits;
  23283. bits -= here_bits;
  23284. //---//
  23285. state.lens[state.have++] = here_val;
  23286. }
  23287. else {
  23288. if (here_val === 16) {
  23289. //=== NEEDBITS(here.bits + 2);
  23290. n = here_bits + 2;
  23291. while (bits < n) {
  23292. if (have === 0) { break inf_leave; }
  23293. have--;
  23294. hold += input[next++] << bits;
  23295. bits += 8;
  23296. }
  23297. //===//
  23298. //--- DROPBITS(here.bits) ---//
  23299. hold >>>= here_bits;
  23300. bits -= here_bits;
  23301. //---//
  23302. if (state.have === 0) {
  23303. strm.msg = 'invalid bit length repeat';
  23304. state.mode = BAD;
  23305. break;
  23306. }
  23307. len = state.lens[state.have - 1];
  23308. copy = 3 + (hold & 0x03);//BITS(2);
  23309. //--- DROPBITS(2) ---//
  23310. hold >>>= 2;
  23311. bits -= 2;
  23312. //---//
  23313. }
  23314. else if (here_val === 17) {
  23315. //=== NEEDBITS(here.bits + 3);
  23316. n = here_bits + 3;
  23317. while (bits < n) {
  23318. if (have === 0) { break inf_leave; }
  23319. have--;
  23320. hold += input[next++] << bits;
  23321. bits += 8;
  23322. }
  23323. //===//
  23324. //--- DROPBITS(here.bits) ---//
  23325. hold >>>= here_bits;
  23326. bits -= here_bits;
  23327. //---//
  23328. len = 0;
  23329. copy = 3 + (hold & 0x07);//BITS(3);
  23330. //--- DROPBITS(3) ---//
  23331. hold >>>= 3;
  23332. bits -= 3;
  23333. //---//
  23334. }
  23335. else {
  23336. //=== NEEDBITS(here.bits + 7);
  23337. n = here_bits + 7;
  23338. while (bits < n) {
  23339. if (have === 0) { break inf_leave; }
  23340. have--;
  23341. hold += input[next++] << bits;
  23342. bits += 8;
  23343. }
  23344. //===//
  23345. //--- DROPBITS(here.bits) ---//
  23346. hold >>>= here_bits;
  23347. bits -= here_bits;
  23348. //---//
  23349. len = 0;
  23350. copy = 11 + (hold & 0x7f);//BITS(7);
  23351. //--- DROPBITS(7) ---//
  23352. hold >>>= 7;
  23353. bits -= 7;
  23354. //---//
  23355. }
  23356. if (state.have + copy > state.nlen + state.ndist) {
  23357. strm.msg = 'invalid bit length repeat';
  23358. state.mode = BAD;
  23359. break;
  23360. }
  23361. while (copy--) {
  23362. state.lens[state.have++] = len;
  23363. }
  23364. }
  23365. }
  23366. /* handle error breaks in while */
  23367. if (state.mode === BAD) { break; }
  23368. /* check for end-of-block code (better have one) */
  23369. if (state.lens[256] === 0) {
  23370. strm.msg = 'invalid code -- missing end-of-block';
  23371. state.mode = BAD;
  23372. break;
  23373. }
  23374. /* build code tables -- note: do not change the lenbits or distbits
  23375. values here (9 and 6) without reading the comments in inftrees.h
  23376. concerning the ENOUGH constants, which depend on those values */
  23377. state.lenbits = 9;
  23378. opts = {bits: state.lenbits};
  23379. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23380. // We have separate tables & no pointers. 2 commented lines below not needed.
  23381. // state.next_index = opts.table_index;
  23382. state.lenbits = opts.bits;
  23383. // state.lencode = state.next;
  23384. if (ret) {
  23385. strm.msg = 'invalid literal/lengths set';
  23386. state.mode = BAD;
  23387. break;
  23388. }
  23389. state.distbits = 6;
  23390. //state.distcode.copy(state.codes);
  23391. // Switch to use dynamic table
  23392. state.distcode = state.distdyn;
  23393. opts = {bits: state.distbits};
  23394. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23395. // We have separate tables & no pointers. 2 commented lines below not needed.
  23396. // state.next_index = opts.table_index;
  23397. state.distbits = opts.bits;
  23398. // state.distcode = state.next;
  23399. if (ret) {
  23400. strm.msg = 'invalid distances set';
  23401. state.mode = BAD;
  23402. break;
  23403. }
  23404. //Tracev((stderr, 'inflate: codes ok\n'));
  23405. state.mode = LEN_;
  23406. if (flush === Z_TREES) { break inf_leave; }
  23407. /* falls through */
  23408. case LEN_:
  23409. state.mode = LEN;
  23410. /* falls through */
  23411. case LEN:
  23412. if (have >= 6 && left >= 258) {
  23413. //--- RESTORE() ---
  23414. strm.next_out = put;
  23415. strm.avail_out = left;
  23416. strm.next_in = next;
  23417. strm.avail_in = have;
  23418. state.hold = hold;
  23419. state.bits = bits;
  23420. //---
  23421. inflate_fast(strm, _out);
  23422. //--- LOAD() ---
  23423. put = strm.next_out;
  23424. output = strm.output;
  23425. left = strm.avail_out;
  23426. next = strm.next_in;
  23427. input = strm.input;
  23428. have = strm.avail_in;
  23429. hold = state.hold;
  23430. bits = state.bits;
  23431. //---
  23432. if (state.mode === TYPE) {
  23433. state.back = -1;
  23434. }
  23435. break;
  23436. }
  23437. state.back = 0;
  23438. for (;;) {
  23439. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23440. here_bits = here >>> 24;
  23441. here_op = (here >>> 16) & 0xff;
  23442. here_val = here & 0xffff;
  23443. if (here_bits <= bits) { break; }
  23444. //--- PULLBYTE() ---//
  23445. if (have === 0) { break inf_leave; }
  23446. have--;
  23447. hold += input[next++] << bits;
  23448. bits += 8;
  23449. //---//
  23450. }
  23451. if (here_op && (here_op & 0xf0) === 0) {
  23452. last_bits = here_bits;
  23453. last_op = here_op;
  23454. last_val = here_val;
  23455. for (;;) {
  23456. here = state.lencode[last_val +
  23457. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23458. here_bits = here >>> 24;
  23459. here_op = (here >>> 16) & 0xff;
  23460. here_val = here & 0xffff;
  23461. if ((last_bits + here_bits) <= bits) { break; }
  23462. //--- PULLBYTE() ---//
  23463. if (have === 0) { break inf_leave; }
  23464. have--;
  23465. hold += input[next++] << bits;
  23466. bits += 8;
  23467. //---//
  23468. }
  23469. //--- DROPBITS(last.bits) ---//
  23470. hold >>>= last_bits;
  23471. bits -= last_bits;
  23472. //---//
  23473. state.back += last_bits;
  23474. }
  23475. //--- DROPBITS(here.bits) ---//
  23476. hold >>>= here_bits;
  23477. bits -= here_bits;
  23478. //---//
  23479. state.back += here_bits;
  23480. state.length = here_val;
  23481. if (here_op === 0) {
  23482. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23483. // "inflate: literal '%c'\n" :
  23484. // "inflate: literal 0x%02x\n", here.val));
  23485. state.mode = LIT;
  23486. break;
  23487. }
  23488. if (here_op & 32) {
  23489. //Tracevv((stderr, "inflate: end of block\n"));
  23490. state.back = -1;
  23491. state.mode = TYPE;
  23492. break;
  23493. }
  23494. if (here_op & 64) {
  23495. strm.msg = 'invalid literal/length code';
  23496. state.mode = BAD;
  23497. break;
  23498. }
  23499. state.extra = here_op & 15;
  23500. state.mode = LENEXT;
  23501. /* falls through */
  23502. case LENEXT:
  23503. if (state.extra) {
  23504. //=== NEEDBITS(state.extra);
  23505. n = state.extra;
  23506. while (bits < n) {
  23507. if (have === 0) { break inf_leave; }
  23508. have--;
  23509. hold += input[next++] << bits;
  23510. bits += 8;
  23511. }
  23512. //===//
  23513. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23514. //--- DROPBITS(state.extra) ---//
  23515. hold >>>= state.extra;
  23516. bits -= state.extra;
  23517. //---//
  23518. state.back += state.extra;
  23519. }
  23520. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23521. state.was = state.length;
  23522. state.mode = DIST;
  23523. /* falls through */
  23524. case DIST:
  23525. for (;;) {
  23526. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23527. here_bits = here >>> 24;
  23528. here_op = (here >>> 16) & 0xff;
  23529. here_val = here & 0xffff;
  23530. if ((here_bits) <= bits) { break; }
  23531. //--- PULLBYTE() ---//
  23532. if (have === 0) { break inf_leave; }
  23533. have--;
  23534. hold += input[next++] << bits;
  23535. bits += 8;
  23536. //---//
  23537. }
  23538. if ((here_op & 0xf0) === 0) {
  23539. last_bits = here_bits;
  23540. last_op = here_op;
  23541. last_val = here_val;
  23542. for (;;) {
  23543. here = state.distcode[last_val +
  23544. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23545. here_bits = here >>> 24;
  23546. here_op = (here >>> 16) & 0xff;
  23547. here_val = here & 0xffff;
  23548. if ((last_bits + here_bits) <= bits) { break; }
  23549. //--- PULLBYTE() ---//
  23550. if (have === 0) { break inf_leave; }
  23551. have--;
  23552. hold += input[next++] << bits;
  23553. bits += 8;
  23554. //---//
  23555. }
  23556. //--- DROPBITS(last.bits) ---//
  23557. hold >>>= last_bits;
  23558. bits -= last_bits;
  23559. //---//
  23560. state.back += last_bits;
  23561. }
  23562. //--- DROPBITS(here.bits) ---//
  23563. hold >>>= here_bits;
  23564. bits -= here_bits;
  23565. //---//
  23566. state.back += here_bits;
  23567. if (here_op & 64) {
  23568. strm.msg = 'invalid distance code';
  23569. state.mode = BAD;
  23570. break;
  23571. }
  23572. state.offset = here_val;
  23573. state.extra = (here_op) & 15;
  23574. state.mode = DISTEXT;
  23575. /* falls through */
  23576. case DISTEXT:
  23577. if (state.extra) {
  23578. //=== NEEDBITS(state.extra);
  23579. n = state.extra;
  23580. while (bits < n) {
  23581. if (have === 0) { break inf_leave; }
  23582. have--;
  23583. hold += input[next++] << bits;
  23584. bits += 8;
  23585. }
  23586. //===//
  23587. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23588. //--- DROPBITS(state.extra) ---//
  23589. hold >>>= state.extra;
  23590. bits -= state.extra;
  23591. //---//
  23592. state.back += state.extra;
  23593. }
  23594. //#ifdef INFLATE_STRICT
  23595. if (state.offset > state.dmax) {
  23596. strm.msg = 'invalid distance too far back';
  23597. state.mode = BAD;
  23598. break;
  23599. }
  23600. //#endif
  23601. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23602. state.mode = MATCH;
  23603. /* falls through */
  23604. case MATCH:
  23605. if (left === 0) { break inf_leave; }
  23606. copy = _out - left;
  23607. if (state.offset > copy) { /* copy from window */
  23608. copy = state.offset - copy;
  23609. if (copy > state.whave) {
  23610. if (state.sane) {
  23611. strm.msg = 'invalid distance too far back';
  23612. state.mode = BAD;
  23613. break;
  23614. }
  23615. // (!) This block is disabled in zlib defailts,
  23616. // don't enable it for binary compatibility
  23617. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23618. // Trace((stderr, "inflate.c too far\n"));
  23619. // copy -= state.whave;
  23620. // if (copy > state.length) { copy = state.length; }
  23621. // if (copy > left) { copy = left; }
  23622. // left -= copy;
  23623. // state.length -= copy;
  23624. // do {
  23625. // output[put++] = 0;
  23626. // } while (--copy);
  23627. // if (state.length === 0) { state.mode = LEN; }
  23628. // break;
  23629. //#endif
  23630. }
  23631. if (copy > state.wnext) {
  23632. copy -= state.wnext;
  23633. from = state.wsize - copy;
  23634. }
  23635. else {
  23636. from = state.wnext - copy;
  23637. }
  23638. if (copy > state.length) { copy = state.length; }
  23639. from_source = state.window;
  23640. }
  23641. else { /* copy from output */
  23642. from_source = output;
  23643. from = put - state.offset;
  23644. copy = state.length;
  23645. }
  23646. if (copy > left) { copy = left; }
  23647. left -= copy;
  23648. state.length -= copy;
  23649. do {
  23650. output[put++] = from_source[from++];
  23651. } while (--copy);
  23652. if (state.length === 0) { state.mode = LEN; }
  23653. break;
  23654. case LIT:
  23655. if (left === 0) { break inf_leave; }
  23656. output[put++] = state.length;
  23657. left--;
  23658. state.mode = LEN;
  23659. break;
  23660. case CHECK:
  23661. if (state.wrap) {
  23662. //=== NEEDBITS(32);
  23663. while (bits < 32) {
  23664. if (have === 0) { break inf_leave; }
  23665. have--;
  23666. // Use '|' insdead of '+' to make sure that result is signed
  23667. hold |= input[next++] << bits;
  23668. bits += 8;
  23669. }
  23670. //===//
  23671. _out -= left;
  23672. strm.total_out += _out;
  23673. state.total += _out;
  23674. if (_out) {
  23675. strm.adler = state.check =
  23676. /*UPDATE(state.check, put - _out, _out);*/
  23677. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23678. }
  23679. _out = left;
  23680. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23681. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23682. strm.msg = 'incorrect data check';
  23683. state.mode = BAD;
  23684. break;
  23685. }
  23686. //=== INITBITS();
  23687. hold = 0;
  23688. bits = 0;
  23689. //===//
  23690. //Tracev((stderr, "inflate: check matches trailer\n"));
  23691. }
  23692. state.mode = LENGTH;
  23693. /* falls through */
  23694. case LENGTH:
  23695. if (state.wrap && state.flags) {
  23696. //=== NEEDBITS(32);
  23697. while (bits < 32) {
  23698. if (have === 0) { break inf_leave; }
  23699. have--;
  23700. hold += input[next++] << bits;
  23701. bits += 8;
  23702. }
  23703. //===//
  23704. if (hold !== (state.total & 0xffffffff)) {
  23705. strm.msg = 'incorrect length check';
  23706. state.mode = BAD;
  23707. break;
  23708. }
  23709. //=== INITBITS();
  23710. hold = 0;
  23711. bits = 0;
  23712. //===//
  23713. //Tracev((stderr, "inflate: length matches trailer\n"));
  23714. }
  23715. state.mode = DONE;
  23716. /* falls through */
  23717. case DONE:
  23718. ret = Z_STREAM_END;
  23719. break inf_leave;
  23720. case BAD:
  23721. ret = Z_DATA_ERROR;
  23722. break inf_leave;
  23723. case MEM:
  23724. return Z_MEM_ERROR;
  23725. case SYNC:
  23726. /* falls through */
  23727. default:
  23728. return Z_STREAM_ERROR;
  23729. }
  23730. }
  23731. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23732. /*
  23733. Return from inflate(), updating the total counts and the check value.
  23734. If there was no progress during the inflate() call, return a buffer
  23735. error. Call updatewindow() to create and/or update the window state.
  23736. Note: a memory error from inflate() is non-recoverable.
  23737. */
  23738. //--- RESTORE() ---
  23739. strm.next_out = put;
  23740. strm.avail_out = left;
  23741. strm.next_in = next;
  23742. strm.avail_in = have;
  23743. state.hold = hold;
  23744. state.bits = bits;
  23745. //---
  23746. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23747. (state.mode < CHECK || flush !== Z_FINISH))) {
  23748. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23749. state.mode = MEM;
  23750. return Z_MEM_ERROR;
  23751. }
  23752. }
  23753. _in -= strm.avail_in;
  23754. _out -= strm.avail_out;
  23755. strm.total_in += _in;
  23756. strm.total_out += _out;
  23757. state.total += _out;
  23758. if (state.wrap && _out) {
  23759. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23760. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23761. }
  23762. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23763. (state.mode === TYPE ? 128 : 0) +
  23764. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23765. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23766. ret = Z_BUF_ERROR;
  23767. }
  23768. return ret;
  23769. }
  23770. function inflateEnd(strm) {
  23771. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23772. return Z_STREAM_ERROR;
  23773. }
  23774. var state = strm.state;
  23775. if (state.window) {
  23776. state.window = null;
  23777. }
  23778. strm.state = null;
  23779. return Z_OK;
  23780. }
  23781. function inflateGetHeader(strm, head) {
  23782. var state;
  23783. /* check state */
  23784. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23785. state = strm.state;
  23786. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23787. /* save header structure */
  23788. state.head = head;
  23789. head.done = false;
  23790. return Z_OK;
  23791. }
  23792. exports.inflateReset = inflateReset;
  23793. exports.inflateReset2 = inflateReset2;
  23794. exports.inflateResetKeep = inflateResetKeep;
  23795. exports.inflateInit = inflateInit;
  23796. exports.inflateInit2 = inflateInit2;
  23797. exports.inflate = inflate;
  23798. exports.inflateEnd = inflateEnd;
  23799. exports.inflateGetHeader = inflateGetHeader;
  23800. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23801. /* Not implemented
  23802. exports.inflateCopy = inflateCopy;
  23803. exports.inflateGetDictionary = inflateGetDictionary;
  23804. exports.inflateMark = inflateMark;
  23805. exports.inflatePrime = inflatePrime;
  23806. exports.inflateSetDictionary = inflateSetDictionary;
  23807. exports.inflateSync = inflateSync;
  23808. exports.inflateSyncPoint = inflateSyncPoint;
  23809. exports.inflateUndermine = inflateUndermine;
  23810. */
  23811. },{"../utils/common":73,"./adler32":75,"./crc32":77,"./inffast":80,"./inftrees":82}],82:[function(require,module,exports){
  23812. 'use strict';
  23813. var utils = require('../utils/common');
  23814. var MAXBITS = 15;
  23815. var ENOUGH_LENS = 852;
  23816. var ENOUGH_DISTS = 592;
  23817. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23818. var CODES = 0;
  23819. var LENS = 1;
  23820. var DISTS = 2;
  23821. var lbase = [ /* Length codes 257..285 base */
  23822. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23823. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23824. ];
  23825. var lext = [ /* Length codes 257..285 extra */
  23826. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23827. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23828. ];
  23829. var dbase = [ /* Distance codes 0..29 base */
  23830. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23831. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23832. 8193, 12289, 16385, 24577, 0, 0
  23833. ];
  23834. var dext = [ /* Distance codes 0..29 extra */
  23835. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23836. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23837. 28, 28, 29, 29, 64, 64
  23838. ];
  23839. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23840. {
  23841. var bits = opts.bits;
  23842. //here = opts.here; /* table entry for duplication */
  23843. var len = 0; /* a code's length in bits */
  23844. var sym = 0; /* index of code symbols */
  23845. var min = 0, max = 0; /* minimum and maximum code lengths */
  23846. var root = 0; /* number of index bits for root table */
  23847. var curr = 0; /* number of index bits for current table */
  23848. var drop = 0; /* code bits to drop for sub-table */
  23849. var left = 0; /* number of prefix codes available */
  23850. var used = 0; /* code entries in table used */
  23851. var huff = 0; /* Huffman code */
  23852. var incr; /* for incrementing code, index */
  23853. var fill; /* index for replicating entries */
  23854. var low; /* low bits for current root entry */
  23855. var mask; /* mask for low root bits */
  23856. var next; /* next available space in table */
  23857. var base = null; /* base value table to use */
  23858. var base_index = 0;
  23859. // var shoextra; /* extra bits table to use */
  23860. var end; /* use base and extra for symbol > end */
  23861. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23862. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23863. var extra = null;
  23864. var extra_index = 0;
  23865. var here_bits, here_op, here_val;
  23866. /*
  23867. Process a set of code lengths to create a canonical Huffman code. The
  23868. code lengths are lens[0..codes-1]. Each length corresponds to the
  23869. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23870. symbols by length from short to long, and retaining the symbol order
  23871. for codes with equal lengths. Then the code starts with all zero bits
  23872. for the first code of the shortest length, and the codes are integer
  23873. increments for the same length, and zeros are appended as the length
  23874. increases. For the deflate format, these bits are stored backwards
  23875. from their more natural integer increment ordering, and so when the
  23876. decoding tables are built in the large loop below, the integer codes
  23877. are incremented backwards.
  23878. This routine assumes, but does not check, that all of the entries in
  23879. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23880. 1..MAXBITS is interpreted as that code length. zero means that that
  23881. symbol does not occur in this code.
  23882. The codes are sorted by computing a count of codes for each length,
  23883. creating from that a table of starting indices for each length in the
  23884. sorted table, and then entering the symbols in order in the sorted
  23885. table. The sorted table is work[], with that space being provided by
  23886. the caller.
  23887. The length counts are used for other purposes as well, i.e. finding
  23888. the minimum and maximum length codes, determining if there are any
  23889. codes at all, checking for a valid set of lengths, and looking ahead
  23890. at length counts to determine sub-table sizes when building the
  23891. decoding tables.
  23892. */
  23893. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23894. for (len = 0; len <= MAXBITS; len++) {
  23895. count[len] = 0;
  23896. }
  23897. for (sym = 0; sym < codes; sym++) {
  23898. count[lens[lens_index + sym]]++;
  23899. }
  23900. /* bound code lengths, force root to be within code lengths */
  23901. root = bits;
  23902. for (max = MAXBITS; max >= 1; max--) {
  23903. if (count[max] !== 0) { break; }
  23904. }
  23905. if (root > max) {
  23906. root = max;
  23907. }
  23908. if (max === 0) { /* no symbols to code at all */
  23909. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23910. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23911. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23912. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23913. //table.op[opts.table_index] = 64;
  23914. //table.bits[opts.table_index] = 1;
  23915. //table.val[opts.table_index++] = 0;
  23916. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23917. opts.bits = 1;
  23918. return 0; /* no symbols, but wait for decoding to report error */
  23919. }
  23920. for (min = 1; min < max; min++) {
  23921. if (count[min] !== 0) { break; }
  23922. }
  23923. if (root < min) {
  23924. root = min;
  23925. }
  23926. /* check for an over-subscribed or incomplete set of lengths */
  23927. left = 1;
  23928. for (len = 1; len <= MAXBITS; len++) {
  23929. left <<= 1;
  23930. left -= count[len];
  23931. if (left < 0) {
  23932. return -1;
  23933. } /* over-subscribed */
  23934. }
  23935. if (left > 0 && (type === CODES || max !== 1)) {
  23936. return -1; /* incomplete set */
  23937. }
  23938. /* generate offsets into symbol table for each length for sorting */
  23939. offs[1] = 0;
  23940. for (len = 1; len < MAXBITS; len++) {
  23941. offs[len + 1] = offs[len] + count[len];
  23942. }
  23943. /* sort symbols by length, by symbol order within each length */
  23944. for (sym = 0; sym < codes; sym++) {
  23945. if (lens[lens_index + sym] !== 0) {
  23946. work[offs[lens[lens_index + sym]]++] = sym;
  23947. }
  23948. }
  23949. /*
  23950. Create and fill in decoding tables. In this loop, the table being
  23951. filled is at next and has curr index bits. The code being used is huff
  23952. with length len. That code is converted to an index by dropping drop
  23953. bits off of the bottom. For codes where len is less than drop + curr,
  23954. those top drop + curr - len bits are incremented through all values to
  23955. fill the table with replicated entries.
  23956. root is the number of index bits for the root table. When len exceeds
  23957. root, sub-tables are created pointed to by the root entry with an index
  23958. of the low root bits of huff. This is saved in low to check for when a
  23959. new sub-table should be started. drop is zero when the root table is
  23960. being filled, and drop is root when sub-tables are being filled.
  23961. When a new sub-table is needed, it is necessary to look ahead in the
  23962. code lengths to determine what size sub-table is needed. The length
  23963. counts are used for this, and so count[] is decremented as codes are
  23964. entered in the tables.
  23965. used keeps track of how many table entries have been allocated from the
  23966. provided *table space. It is checked for LENS and DIST tables against
  23967. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23968. the initial root table size constants. See the comments in inftrees.h
  23969. for more information.
  23970. sym increments through all symbols, and the loop terminates when
  23971. all codes of length max, i.e. all codes, have been processed. This
  23972. routine permits incomplete codes, so another loop after this one fills
  23973. in the rest of the decoding tables with invalid code markers.
  23974. */
  23975. /* set up for code type */
  23976. // poor man optimization - use if-else instead of switch,
  23977. // to avoid deopts in old v8
  23978. if (type === CODES) {
  23979. base = extra = work; /* dummy value--not used */
  23980. end = 19;
  23981. } else if (type === LENS) {
  23982. base = lbase;
  23983. base_index -= 257;
  23984. extra = lext;
  23985. extra_index -= 257;
  23986. end = 256;
  23987. } else { /* DISTS */
  23988. base = dbase;
  23989. extra = dext;
  23990. end = -1;
  23991. }
  23992. /* initialize opts for loop */
  23993. huff = 0; /* starting code */
  23994. sym = 0; /* starting code symbol */
  23995. len = min; /* starting code length */
  23996. next = table_index; /* current table to fill in */
  23997. curr = root; /* current table index bits */
  23998. drop = 0; /* current bits to drop from code for index */
  23999. low = -1; /* trigger new sub-table when len > root */
  24000. used = 1 << root; /* use root table entries */
  24001. mask = used - 1; /* mask for comparing low */
  24002. /* check available table space */
  24003. if ((type === LENS && used > ENOUGH_LENS) ||
  24004. (type === DISTS && used > ENOUGH_DISTS)) {
  24005. return 1;
  24006. }
  24007. var i=0;
  24008. /* process all codes and make table entries */
  24009. for (;;) {
  24010. i++;
  24011. /* create table entry */
  24012. here_bits = len - drop;
  24013. if (work[sym] < end) {
  24014. here_op = 0;
  24015. here_val = work[sym];
  24016. }
  24017. else if (work[sym] > end) {
  24018. here_op = extra[extra_index + work[sym]];
  24019. here_val = base[base_index + work[sym]];
  24020. }
  24021. else {
  24022. here_op = 32 + 64; /* end of block */
  24023. here_val = 0;
  24024. }
  24025. /* replicate for those indices with low len bits equal to huff */
  24026. incr = 1 << (len - drop);
  24027. fill = 1 << curr;
  24028. min = fill; /* save offset to next table */
  24029. do {
  24030. fill -= incr;
  24031. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24032. } while (fill !== 0);
  24033. /* backwards increment the len-bit code huff */
  24034. incr = 1 << (len - 1);
  24035. while (huff & incr) {
  24036. incr >>= 1;
  24037. }
  24038. if (incr !== 0) {
  24039. huff &= incr - 1;
  24040. huff += incr;
  24041. } else {
  24042. huff = 0;
  24043. }
  24044. /* go to next symbol, update count, len */
  24045. sym++;
  24046. if (--count[len] === 0) {
  24047. if (len === max) { break; }
  24048. len = lens[lens_index + work[sym]];
  24049. }
  24050. /* create new sub-table if needed */
  24051. if (len > root && (huff & mask) !== low) {
  24052. /* if first time, transition to sub-tables */
  24053. if (drop === 0) {
  24054. drop = root;
  24055. }
  24056. /* increment past last table */
  24057. next += min; /* here min is 1 << curr */
  24058. /* determine length of next table */
  24059. curr = len - drop;
  24060. left = 1 << curr;
  24061. while (curr + drop < max) {
  24062. left -= count[curr + drop];
  24063. if (left <= 0) { break; }
  24064. curr++;
  24065. left <<= 1;
  24066. }
  24067. /* check for enough space */
  24068. used += 1 << curr;
  24069. if ((type === LENS && used > ENOUGH_LENS) ||
  24070. (type === DISTS && used > ENOUGH_DISTS)) {
  24071. return 1;
  24072. }
  24073. /* point entry in root table to sub-table */
  24074. low = huff & mask;
  24075. /*table.op[low] = curr;
  24076. table.bits[low] = root;
  24077. table.val[low] = next - opts.table_index;*/
  24078. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24079. }
  24080. }
  24081. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24082. at most one remaining entry, since if the code is incomplete, the
  24083. maximum code length that was allowed to get this far is one bit) */
  24084. if (huff !== 0) {
  24085. //table.op[next + huff] = 64; /* invalid code marker */
  24086. //table.bits[next + huff] = len - drop;
  24087. //table.val[next + huff] = 0;
  24088. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24089. }
  24090. /* set return parameters */
  24091. //opts.table_index += used;
  24092. opts.bits = root;
  24093. return 0;
  24094. };
  24095. },{"../utils/common":73}],83:[function(require,module,exports){
  24096. 'use strict';
  24097. module.exports = {
  24098. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24099. '1': 'stream end', /* Z_STREAM_END 1 */
  24100. '0': '', /* Z_OK 0 */
  24101. '-1': 'file error', /* Z_ERRNO (-1) */
  24102. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24103. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24104. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24105. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24106. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24107. };
  24108. },{}],84:[function(require,module,exports){
  24109. 'use strict';
  24110. var utils = require('../utils/common');
  24111. /* Public constants ==========================================================*/
  24112. /* ===========================================================================*/
  24113. //var Z_FILTERED = 1;
  24114. //var Z_HUFFMAN_ONLY = 2;
  24115. //var Z_RLE = 3;
  24116. var Z_FIXED = 4;
  24117. //var Z_DEFAULT_STRATEGY = 0;
  24118. /* Possible values of the data_type field (though see inflate()) */
  24119. var Z_BINARY = 0;
  24120. var Z_TEXT = 1;
  24121. //var Z_ASCII = 1; // = Z_TEXT
  24122. var Z_UNKNOWN = 2;
  24123. /*============================================================================*/
  24124. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24125. // From zutil.h
  24126. var STORED_BLOCK = 0;
  24127. var STATIC_TREES = 1;
  24128. var DYN_TREES = 2;
  24129. /* The three kinds of block type */
  24130. var MIN_MATCH = 3;
  24131. var MAX_MATCH = 258;
  24132. /* The minimum and maximum match lengths */
  24133. // From deflate.h
  24134. /* ===========================================================================
  24135. * Internal compression state.
  24136. */
  24137. var LENGTH_CODES = 29;
  24138. /* number of length codes, not counting the special END_BLOCK code */
  24139. var LITERALS = 256;
  24140. /* number of literal bytes 0..255 */
  24141. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24142. /* number of Literal or Length codes, including the END_BLOCK code */
  24143. var D_CODES = 30;
  24144. /* number of distance codes */
  24145. var BL_CODES = 19;
  24146. /* number of codes used to transfer the bit lengths */
  24147. var HEAP_SIZE = 2*L_CODES + 1;
  24148. /* maximum heap size */
  24149. var MAX_BITS = 15;
  24150. /* All codes must not exceed MAX_BITS bits */
  24151. var Buf_size = 16;
  24152. /* size of bit buffer in bi_buf */
  24153. /* ===========================================================================
  24154. * Constants
  24155. */
  24156. var MAX_BL_BITS = 7;
  24157. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24158. var END_BLOCK = 256;
  24159. /* end of block literal code */
  24160. var REP_3_6 = 16;
  24161. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24162. var REPZ_3_10 = 17;
  24163. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24164. var REPZ_11_138 = 18;
  24165. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24166. var extra_lbits = /* extra bits for each length code */
  24167. [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];
  24168. var extra_dbits = /* extra bits for each distance code */
  24169. [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];
  24170. var extra_blbits = /* extra bits for each bit length code */
  24171. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24172. var bl_order =
  24173. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24174. /* The lengths of the bit length codes are sent in order of decreasing
  24175. * probability, to avoid transmitting the lengths for unused bit length codes.
  24176. */
  24177. /* ===========================================================================
  24178. * Local data. These are initialized only once.
  24179. */
  24180. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24181. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24182. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24183. var static_ltree = new Array((L_CODES+2) * 2);
  24184. zero(static_ltree);
  24185. /* The static literal tree. Since the bit lengths are imposed, there is no
  24186. * need for the L_CODES extra codes used during heap construction. However
  24187. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24188. * below).
  24189. */
  24190. var static_dtree = new Array(D_CODES * 2);
  24191. zero(static_dtree);
  24192. /* The static distance tree. (Actually a trivial tree since all codes use
  24193. * 5 bits.)
  24194. */
  24195. var _dist_code = new Array(DIST_CODE_LEN);
  24196. zero(_dist_code);
  24197. /* Distance codes. The first 256 values correspond to the distances
  24198. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24199. * the 15 bit distances.
  24200. */
  24201. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24202. zero(_length_code);
  24203. /* length code for each normalized match length (0 == MIN_MATCH) */
  24204. var base_length = new Array(LENGTH_CODES);
  24205. zero(base_length);
  24206. /* First normalized length for each code (0 = MIN_MATCH) */
  24207. var base_dist = new Array(D_CODES);
  24208. zero(base_dist);
  24209. /* First normalized distance for each code (0 = distance of 1) */
  24210. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24211. this.static_tree = static_tree; /* static tree or NULL */
  24212. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24213. this.extra_base = extra_base; /* base index for extra_bits */
  24214. this.elems = elems; /* max number of elements in the tree */
  24215. this.max_length = max_length; /* max bit length for the codes */
  24216. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24217. this.has_stree = static_tree && static_tree.length;
  24218. };
  24219. var static_l_desc;
  24220. var static_d_desc;
  24221. var static_bl_desc;
  24222. var TreeDesc = function(dyn_tree, stat_desc) {
  24223. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24224. this.max_code = 0; /* largest code with non zero frequency */
  24225. this.stat_desc = stat_desc; /* the corresponding static tree */
  24226. };
  24227. function d_code(dist) {
  24228. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24229. }
  24230. /* ===========================================================================
  24231. * Output a short LSB first on the stream.
  24232. * IN assertion: there is enough room in pendingBuf.
  24233. */
  24234. function put_short (s, w) {
  24235. // put_byte(s, (uch)((w) & 0xff));
  24236. // put_byte(s, (uch)((ush)(w) >> 8));
  24237. s.pending_buf[s.pending++] = (w) & 0xff;
  24238. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24239. }
  24240. /* ===========================================================================
  24241. * Send a value on a given number of bits.
  24242. * IN assertion: length <= 16 and value fits in length bits.
  24243. */
  24244. function send_bits(s, value, length) {
  24245. if (s.bi_valid > (Buf_size - length)) {
  24246. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24247. put_short(s, s.bi_buf);
  24248. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24249. s.bi_valid += length - Buf_size;
  24250. } else {
  24251. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24252. s.bi_valid += length;
  24253. }
  24254. }
  24255. function send_code(s, c, tree) {
  24256. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24257. }
  24258. /* ===========================================================================
  24259. * Reverse the first len bits of a code, using straightforward code (a faster
  24260. * method would use a table)
  24261. * IN assertion: 1 <= len <= 15
  24262. */
  24263. function bi_reverse(code, len) {
  24264. var res = 0;
  24265. do {
  24266. res |= code & 1;
  24267. code >>>= 1;
  24268. res <<= 1;
  24269. } while (--len > 0);
  24270. return res >>> 1;
  24271. }
  24272. /* ===========================================================================
  24273. * Flush the bit buffer, keeping at most 7 bits in it.
  24274. */
  24275. function bi_flush(s) {
  24276. if (s.bi_valid === 16) {
  24277. put_short(s, s.bi_buf);
  24278. s.bi_buf = 0;
  24279. s.bi_valid = 0;
  24280. } else if (s.bi_valid >= 8) {
  24281. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24282. s.bi_buf >>= 8;
  24283. s.bi_valid -= 8;
  24284. }
  24285. }
  24286. /* ===========================================================================
  24287. * Compute the optimal bit lengths for a tree and update the total bit length
  24288. * for the current block.
  24289. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24290. * above are the tree nodes sorted by increasing frequency.
  24291. * OUT assertions: the field len is set to the optimal bit length, the
  24292. * array bl_count contains the frequencies for each bit length.
  24293. * The length opt_len is updated; static_len is also updated if stree is
  24294. * not null.
  24295. */
  24296. function gen_bitlen(s, desc)
  24297. // deflate_state *s;
  24298. // tree_desc *desc; /* the tree descriptor */
  24299. {
  24300. var tree = desc.dyn_tree;
  24301. var max_code = desc.max_code;
  24302. var stree = desc.stat_desc.static_tree;
  24303. var has_stree = desc.stat_desc.has_stree;
  24304. var extra = desc.stat_desc.extra_bits;
  24305. var base = desc.stat_desc.extra_base;
  24306. var max_length = desc.stat_desc.max_length;
  24307. var h; /* heap index */
  24308. var n, m; /* iterate over the tree elements */
  24309. var bits; /* bit length */
  24310. var xbits; /* extra bits */
  24311. var f; /* frequency */
  24312. var overflow = 0; /* number of elements with bit length too large */
  24313. for (bits = 0; bits <= MAX_BITS; bits++) {
  24314. s.bl_count[bits] = 0;
  24315. }
  24316. /* In a first pass, compute the optimal bit lengths (which may
  24317. * overflow in the case of the bit length tree).
  24318. */
  24319. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24320. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24321. n = s.heap[h];
  24322. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24323. if (bits > max_length) {
  24324. bits = max_length;
  24325. overflow++;
  24326. }
  24327. tree[n*2 + 1]/*.Len*/ = bits;
  24328. /* We overwrite tree[n].Dad which is no longer needed */
  24329. if (n > max_code) { continue; } /* not a leaf node */
  24330. s.bl_count[bits]++;
  24331. xbits = 0;
  24332. if (n >= base) {
  24333. xbits = extra[n-base];
  24334. }
  24335. f = tree[n * 2]/*.Freq*/;
  24336. s.opt_len += f * (bits + xbits);
  24337. if (has_stree) {
  24338. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24339. }
  24340. }
  24341. if (overflow === 0) { return; }
  24342. // Trace((stderr,"\nbit length overflow\n"));
  24343. /* This happens for example on obj2 and pic of the Calgary corpus */
  24344. /* Find the first bit length which could increase: */
  24345. do {
  24346. bits = max_length-1;
  24347. while (s.bl_count[bits] === 0) { bits--; }
  24348. s.bl_count[bits]--; /* move one leaf down the tree */
  24349. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24350. s.bl_count[max_length]--;
  24351. /* The brother of the overflow item also moves one step up,
  24352. * but this does not affect bl_count[max_length]
  24353. */
  24354. overflow -= 2;
  24355. } while (overflow > 0);
  24356. /* Now recompute all bit lengths, scanning in increasing frequency.
  24357. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24358. * lengths instead of fixing only the wrong ones. This idea is taken
  24359. * from 'ar' written by Haruhiko Okumura.)
  24360. */
  24361. for (bits = max_length; bits !== 0; bits--) {
  24362. n = s.bl_count[bits];
  24363. while (n !== 0) {
  24364. m = s.heap[--h];
  24365. if (m > max_code) { continue; }
  24366. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24367. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24368. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24369. tree[m*2 + 1]/*.Len*/ = bits;
  24370. }
  24371. n--;
  24372. }
  24373. }
  24374. }
  24375. /* ===========================================================================
  24376. * Generate the codes for a given tree and bit counts (which need not be
  24377. * optimal).
  24378. * IN assertion: the array bl_count contains the bit length statistics for
  24379. * the given tree and the field len is set for all tree elements.
  24380. * OUT assertion: the field code is set for all tree elements of non
  24381. * zero code length.
  24382. */
  24383. function gen_codes(tree, max_code, bl_count)
  24384. // ct_data *tree; /* the tree to decorate */
  24385. // int max_code; /* largest code with non zero frequency */
  24386. // ushf *bl_count; /* number of codes at each bit length */
  24387. {
  24388. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24389. var code = 0; /* running code value */
  24390. var bits; /* bit index */
  24391. var n; /* code index */
  24392. /* The distribution counts are first used to generate the code values
  24393. * without bit reversal.
  24394. */
  24395. for (bits = 1; bits <= MAX_BITS; bits++) {
  24396. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24397. }
  24398. /* Check that the bit counts in bl_count are consistent. The last code
  24399. * must be all ones.
  24400. */
  24401. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24402. // "inconsistent bit counts");
  24403. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24404. for (n = 0; n <= max_code; n++) {
  24405. var len = tree[n*2 + 1]/*.Len*/;
  24406. if (len === 0) { continue; }
  24407. /* Now reverse the bits */
  24408. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24409. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24410. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24411. }
  24412. }
  24413. /* ===========================================================================
  24414. * Initialize the various 'constant' tables.
  24415. */
  24416. function tr_static_init() {
  24417. var n; /* iterates over tree elements */
  24418. var bits; /* bit counter */
  24419. var length; /* length value */
  24420. var code; /* code value */
  24421. var dist; /* distance index */
  24422. var bl_count = new Array(MAX_BITS+1);
  24423. /* number of codes at each bit length for an optimal tree */
  24424. // do check in _tr_init()
  24425. //if (static_init_done) return;
  24426. /* For some embedded targets, global variables are not initialized: */
  24427. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24428. static_l_desc.static_tree = static_ltree;
  24429. static_l_desc.extra_bits = extra_lbits;
  24430. static_d_desc.static_tree = static_dtree;
  24431. static_d_desc.extra_bits = extra_dbits;
  24432. static_bl_desc.extra_bits = extra_blbits;
  24433. #endif*/
  24434. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24435. length = 0;
  24436. for (code = 0; code < LENGTH_CODES-1; code++) {
  24437. base_length[code] = length;
  24438. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24439. _length_code[length++] = code;
  24440. }
  24441. }
  24442. //Assert (length == 256, "tr_static_init: length != 256");
  24443. /* Note that the length 255 (match length 258) can be represented
  24444. * in two different ways: code 284 + 5 bits or code 285, so we
  24445. * overwrite length_code[255] to use the best encoding:
  24446. */
  24447. _length_code[length-1] = code;
  24448. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24449. dist = 0;
  24450. for (code = 0 ; code < 16; code++) {
  24451. base_dist[code] = dist;
  24452. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24453. _dist_code[dist++] = code;
  24454. }
  24455. }
  24456. //Assert (dist == 256, "tr_static_init: dist != 256");
  24457. dist >>= 7; /* from now on, all distances are divided by 128 */
  24458. for (; code < D_CODES; code++) {
  24459. base_dist[code] = dist << 7;
  24460. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24461. _dist_code[256 + dist++] = code;
  24462. }
  24463. }
  24464. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24465. /* Construct the codes of the static literal tree */
  24466. for (bits = 0; bits <= MAX_BITS; bits++) {
  24467. bl_count[bits] = 0;
  24468. }
  24469. n = 0;
  24470. while (n <= 143) {
  24471. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24472. n++;
  24473. bl_count[8]++;
  24474. }
  24475. while (n <= 255) {
  24476. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24477. n++;
  24478. bl_count[9]++;
  24479. }
  24480. while (n <= 279) {
  24481. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24482. n++;
  24483. bl_count[7]++;
  24484. }
  24485. while (n <= 287) {
  24486. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24487. n++;
  24488. bl_count[8]++;
  24489. }
  24490. /* Codes 286 and 287 do not exist, but we must include them in the
  24491. * tree construction to get a canonical Huffman tree (longest code
  24492. * all ones)
  24493. */
  24494. gen_codes(static_ltree, L_CODES+1, bl_count);
  24495. /* The static distance tree is trivial: */
  24496. for (n = 0; n < D_CODES; n++) {
  24497. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24498. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24499. }
  24500. // Now data ready and we can init static trees
  24501. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24502. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24503. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24504. //static_init_done = true;
  24505. }
  24506. /* ===========================================================================
  24507. * Initialize a new block.
  24508. */
  24509. function init_block(s) {
  24510. var n; /* iterates over tree elements */
  24511. /* Initialize the trees. */
  24512. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24513. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24514. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24515. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24516. s.opt_len = s.static_len = 0;
  24517. s.last_lit = s.matches = 0;
  24518. }
  24519. /* ===========================================================================
  24520. * Flush the bit buffer and align the output on a byte boundary
  24521. */
  24522. function bi_windup(s)
  24523. {
  24524. if (s.bi_valid > 8) {
  24525. put_short(s, s.bi_buf);
  24526. } else if (s.bi_valid > 0) {
  24527. //put_byte(s, (Byte)s->bi_buf);
  24528. s.pending_buf[s.pending++] = s.bi_buf;
  24529. }
  24530. s.bi_buf = 0;
  24531. s.bi_valid = 0;
  24532. }
  24533. /* ===========================================================================
  24534. * Copy a stored block, storing first the length and its
  24535. * one's complement if requested.
  24536. */
  24537. function copy_block(s, buf, len, header)
  24538. //DeflateState *s;
  24539. //charf *buf; /* the input data */
  24540. //unsigned len; /* its length */
  24541. //int header; /* true if block header must be written */
  24542. {
  24543. bi_windup(s); /* align on byte boundary */
  24544. if (header) {
  24545. put_short(s, len);
  24546. put_short(s, ~len);
  24547. }
  24548. // while (len--) {
  24549. // put_byte(s, *buf++);
  24550. // }
  24551. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24552. s.pending += len;
  24553. }
  24554. /* ===========================================================================
  24555. * Compares to subtrees, using the tree depth as tie breaker when
  24556. * the subtrees have equal frequency. This minimizes the worst case length.
  24557. */
  24558. function smaller(tree, n, m, depth) {
  24559. var _n2 = n*2;
  24560. var _m2 = m*2;
  24561. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24562. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24563. }
  24564. /* ===========================================================================
  24565. * Restore the heap property by moving down the tree starting at node k,
  24566. * exchanging a node with the smallest of its two sons if necessary, stopping
  24567. * when the heap property is re-established (each father smaller than its
  24568. * two sons).
  24569. */
  24570. function pqdownheap(s, tree, k)
  24571. // deflate_state *s;
  24572. // ct_data *tree; /* the tree to restore */
  24573. // int k; /* node to move down */
  24574. {
  24575. var v = s.heap[k];
  24576. var j = k << 1; /* left son of k */
  24577. while (j <= s.heap_len) {
  24578. /* Set j to the smallest of the two sons: */
  24579. if (j < s.heap_len &&
  24580. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24581. j++;
  24582. }
  24583. /* Exit if v is smaller than both sons */
  24584. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24585. /* Exchange v with the smallest son */
  24586. s.heap[k] = s.heap[j];
  24587. k = j;
  24588. /* And continue down the tree, setting j to the left son of k */
  24589. j <<= 1;
  24590. }
  24591. s.heap[k] = v;
  24592. }
  24593. // inlined manually
  24594. // var SMALLEST = 1;
  24595. /* ===========================================================================
  24596. * Send the block data compressed using the given Huffman trees
  24597. */
  24598. function compress_block(s, ltree, dtree)
  24599. // deflate_state *s;
  24600. // const ct_data *ltree; /* literal tree */
  24601. // const ct_data *dtree; /* distance tree */
  24602. {
  24603. var dist; /* distance of matched string */
  24604. var lc; /* match length or unmatched char (if dist == 0) */
  24605. var lx = 0; /* running index in l_buf */
  24606. var code; /* the code to send */
  24607. var extra; /* number of extra bits to send */
  24608. if (s.last_lit !== 0) {
  24609. do {
  24610. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24611. lc = s.pending_buf[s.l_buf + lx];
  24612. lx++;
  24613. if (dist === 0) {
  24614. send_code(s, lc, ltree); /* send a literal byte */
  24615. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24616. } else {
  24617. /* Here, lc is the match length - MIN_MATCH */
  24618. code = _length_code[lc];
  24619. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24620. extra = extra_lbits[code];
  24621. if (extra !== 0) {
  24622. lc -= base_length[code];
  24623. send_bits(s, lc, extra); /* send the extra length bits */
  24624. }
  24625. dist--; /* dist is now the match distance - 1 */
  24626. code = d_code(dist);
  24627. //Assert (code < D_CODES, "bad d_code");
  24628. send_code(s, code, dtree); /* send the distance code */
  24629. extra = extra_dbits[code];
  24630. if (extra !== 0) {
  24631. dist -= base_dist[code];
  24632. send_bits(s, dist, extra); /* send the extra distance bits */
  24633. }
  24634. } /* literal or match pair ? */
  24635. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24636. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24637. // "pendingBuf overflow");
  24638. } while (lx < s.last_lit);
  24639. }
  24640. send_code(s, END_BLOCK, ltree);
  24641. }
  24642. /* ===========================================================================
  24643. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24644. * Update the total bit length for the current block.
  24645. * IN assertion: the field freq is set for all tree elements.
  24646. * OUT assertions: the fields len and code are set to the optimal bit length
  24647. * and corresponding code. The length opt_len is updated; static_len is
  24648. * also updated if stree is not null. The field max_code is set.
  24649. */
  24650. function build_tree(s, desc)
  24651. // deflate_state *s;
  24652. // tree_desc *desc; /* the tree descriptor */
  24653. {
  24654. var tree = desc.dyn_tree;
  24655. var stree = desc.stat_desc.static_tree;
  24656. var has_stree = desc.stat_desc.has_stree;
  24657. var elems = desc.stat_desc.elems;
  24658. var n, m; /* iterate over heap elements */
  24659. var max_code = -1; /* largest code with non zero frequency */
  24660. var node; /* new node being created */
  24661. /* Construct the initial heap, with least frequent element in
  24662. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24663. * heap[0] is not used.
  24664. */
  24665. s.heap_len = 0;
  24666. s.heap_max = HEAP_SIZE;
  24667. for (n = 0; n < elems; n++) {
  24668. if (tree[n * 2]/*.Freq*/ !== 0) {
  24669. s.heap[++s.heap_len] = max_code = n;
  24670. s.depth[n] = 0;
  24671. } else {
  24672. tree[n*2 + 1]/*.Len*/ = 0;
  24673. }
  24674. }
  24675. /* The pkzip format requires that at least one distance code exists,
  24676. * and that at least one bit should be sent even if there is only one
  24677. * possible code. So to avoid special checks later on we force at least
  24678. * two codes of non zero frequency.
  24679. */
  24680. while (s.heap_len < 2) {
  24681. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24682. tree[node * 2]/*.Freq*/ = 1;
  24683. s.depth[node] = 0;
  24684. s.opt_len--;
  24685. if (has_stree) {
  24686. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24687. }
  24688. /* node is 0 or 1 so it does not have extra bits */
  24689. }
  24690. desc.max_code = max_code;
  24691. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24692. * establish sub-heaps of increasing lengths:
  24693. */
  24694. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24695. /* Construct the Huffman tree by repeatedly combining the least two
  24696. * frequent nodes.
  24697. */
  24698. node = elems; /* next internal node of the tree */
  24699. do {
  24700. //pqremove(s, tree, n); /* n = node of least frequency */
  24701. /*** pqremove ***/
  24702. n = s.heap[1/*SMALLEST*/];
  24703. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24704. pqdownheap(s, tree, 1/*SMALLEST*/);
  24705. /***/
  24706. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24707. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24708. s.heap[--s.heap_max] = m;
  24709. /* Create a new node father of n and m */
  24710. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24711. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24712. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24713. /* and insert the new node in the heap */
  24714. s.heap[1/*SMALLEST*/] = node++;
  24715. pqdownheap(s, tree, 1/*SMALLEST*/);
  24716. } while (s.heap_len >= 2);
  24717. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24718. /* At this point, the fields freq and dad are set. We can now
  24719. * generate the bit lengths.
  24720. */
  24721. gen_bitlen(s, desc);
  24722. /* The field len is now set, we can generate the bit codes */
  24723. gen_codes(tree, max_code, s.bl_count);
  24724. }
  24725. /* ===========================================================================
  24726. * Scan a literal or distance tree to determine the frequencies of the codes
  24727. * in the bit length tree.
  24728. */
  24729. function scan_tree(s, tree, max_code)
  24730. // deflate_state *s;
  24731. // ct_data *tree; /* the tree to be scanned */
  24732. // int max_code; /* and its largest code of non zero frequency */
  24733. {
  24734. var n; /* iterates over all tree elements */
  24735. var prevlen = -1; /* last emitted length */
  24736. var curlen; /* length of current code */
  24737. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24738. var count = 0; /* repeat count of the current code */
  24739. var max_count = 7; /* max repeat count */
  24740. var min_count = 4; /* min repeat count */
  24741. if (nextlen === 0) {
  24742. max_count = 138;
  24743. min_count = 3;
  24744. }
  24745. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24746. for (n = 0; n <= max_code; n++) {
  24747. curlen = nextlen;
  24748. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24749. if (++count < max_count && curlen === nextlen) {
  24750. continue;
  24751. } else if (count < min_count) {
  24752. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24753. } else if (curlen !== 0) {
  24754. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24755. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24756. } else if (count <= 10) {
  24757. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24758. } else {
  24759. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24760. }
  24761. count = 0;
  24762. prevlen = curlen;
  24763. if (nextlen === 0) {
  24764. max_count = 138;
  24765. min_count = 3;
  24766. } else if (curlen === nextlen) {
  24767. max_count = 6;
  24768. min_count = 3;
  24769. } else {
  24770. max_count = 7;
  24771. min_count = 4;
  24772. }
  24773. }
  24774. }
  24775. /* ===========================================================================
  24776. * Send a literal or distance tree in compressed form, using the codes in
  24777. * bl_tree.
  24778. */
  24779. function send_tree(s, tree, max_code)
  24780. // deflate_state *s;
  24781. // ct_data *tree; /* the tree to be scanned */
  24782. // int max_code; /* and its largest code of non zero frequency */
  24783. {
  24784. var n; /* iterates over all tree elements */
  24785. var prevlen = -1; /* last emitted length */
  24786. var curlen; /* length of current code */
  24787. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24788. var count = 0; /* repeat count of the current code */
  24789. var max_count = 7; /* max repeat count */
  24790. var min_count = 4; /* min repeat count */
  24791. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24792. if (nextlen === 0) {
  24793. max_count = 138;
  24794. min_count = 3;
  24795. }
  24796. for (n = 0; n <= max_code; n++) {
  24797. curlen = nextlen;
  24798. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24799. if (++count < max_count && curlen === nextlen) {
  24800. continue;
  24801. } else if (count < min_count) {
  24802. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24803. } else if (curlen !== 0) {
  24804. if (curlen !== prevlen) {
  24805. send_code(s, curlen, s.bl_tree);
  24806. count--;
  24807. }
  24808. //Assert(count >= 3 && count <= 6, " 3_6?");
  24809. send_code(s, REP_3_6, s.bl_tree);
  24810. send_bits(s, count-3, 2);
  24811. } else if (count <= 10) {
  24812. send_code(s, REPZ_3_10, s.bl_tree);
  24813. send_bits(s, count-3, 3);
  24814. } else {
  24815. send_code(s, REPZ_11_138, s.bl_tree);
  24816. send_bits(s, count-11, 7);
  24817. }
  24818. count = 0;
  24819. prevlen = curlen;
  24820. if (nextlen === 0) {
  24821. max_count = 138;
  24822. min_count = 3;
  24823. } else if (curlen === nextlen) {
  24824. max_count = 6;
  24825. min_count = 3;
  24826. } else {
  24827. max_count = 7;
  24828. min_count = 4;
  24829. }
  24830. }
  24831. }
  24832. /* ===========================================================================
  24833. * Construct the Huffman tree for the bit lengths and return the index in
  24834. * bl_order of the last bit length code to send.
  24835. */
  24836. function build_bl_tree(s) {
  24837. var max_blindex; /* index of last bit length code of non zero freq */
  24838. /* Determine the bit length frequencies for literal and distance trees */
  24839. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24840. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24841. /* Build the bit length tree: */
  24842. build_tree(s, s.bl_desc);
  24843. /* opt_len now includes the length of the tree representations, except
  24844. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24845. */
  24846. /* Determine the number of bit length codes to send. The pkzip format
  24847. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24848. * 3 but the actual value used is 4.)
  24849. */
  24850. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24851. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24852. break;
  24853. }
  24854. }
  24855. /* Update opt_len to include the bit length tree and counts */
  24856. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24857. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24858. // s->opt_len, s->static_len));
  24859. return max_blindex;
  24860. }
  24861. /* ===========================================================================
  24862. * Send the header for a block using dynamic Huffman trees: the counts, the
  24863. * lengths of the bit length codes, the literal tree and the distance tree.
  24864. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24865. */
  24866. function send_all_trees(s, lcodes, dcodes, blcodes)
  24867. // deflate_state *s;
  24868. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24869. {
  24870. var rank; /* index in bl_order */
  24871. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24872. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24873. // "too many codes");
  24874. //Tracev((stderr, "\nbl counts: "));
  24875. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24876. send_bits(s, dcodes-1, 5);
  24877. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24878. for (rank = 0; rank < blcodes; rank++) {
  24879. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24880. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24881. }
  24882. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24883. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24884. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24885. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24886. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24887. }
  24888. /* ===========================================================================
  24889. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24890. * - TEXT if the two conditions below are satisfied:
  24891. * a) There are no non-portable control characters belonging to the
  24892. * "black list" (0..6, 14..25, 28..31).
  24893. * b) There is at least one printable character belonging to the
  24894. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24895. * - BINARY otherwise.
  24896. * - The following partially-portable control characters form a
  24897. * "gray list" that is ignored in this detection algorithm:
  24898. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24899. * IN assertion: the fields Freq of dyn_ltree are set.
  24900. */
  24901. function detect_data_type(s) {
  24902. /* black_mask is the bit mask of black-listed bytes
  24903. * set bits 0..6, 14..25, and 28..31
  24904. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24905. */
  24906. var black_mask = 0xf3ffc07f;
  24907. var n;
  24908. /* Check for non-textual ("black-listed") bytes. */
  24909. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24910. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24911. return Z_BINARY;
  24912. }
  24913. }
  24914. /* Check for textual ("white-listed") bytes. */
  24915. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24916. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24917. return Z_TEXT;
  24918. }
  24919. for (n = 32; n < LITERALS; n++) {
  24920. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24921. return Z_TEXT;
  24922. }
  24923. }
  24924. /* There are no "black-listed" or "white-listed" bytes:
  24925. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24926. */
  24927. return Z_BINARY;
  24928. }
  24929. var static_init_done = false;
  24930. /* ===========================================================================
  24931. * Initialize the tree data structures for a new zlib stream.
  24932. */
  24933. function _tr_init(s)
  24934. {
  24935. if (!static_init_done) {
  24936. tr_static_init();
  24937. static_init_done = true;
  24938. }
  24939. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24940. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24941. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24942. s.bi_buf = 0;
  24943. s.bi_valid = 0;
  24944. /* Initialize the first block of the first file: */
  24945. init_block(s);
  24946. }
  24947. /* ===========================================================================
  24948. * Send a stored block
  24949. */
  24950. function _tr_stored_block(s, buf, stored_len, last)
  24951. //DeflateState *s;
  24952. //charf *buf; /* input block */
  24953. //ulg stored_len; /* length of input block */
  24954. //int last; /* one if this is the last block for a file */
  24955. {
  24956. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24957. copy_block(s, buf, stored_len, true); /* with header */
  24958. }
  24959. /* ===========================================================================
  24960. * Send one empty static block to give enough lookahead for inflate.
  24961. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24962. */
  24963. function _tr_align(s) {
  24964. send_bits(s, STATIC_TREES<<1, 3);
  24965. send_code(s, END_BLOCK, static_ltree);
  24966. bi_flush(s);
  24967. }
  24968. /* ===========================================================================
  24969. * Determine the best encoding for the current block: dynamic trees, static
  24970. * trees or store, and output the encoded block to the zip file.
  24971. */
  24972. function _tr_flush_block(s, buf, stored_len, last)
  24973. //DeflateState *s;
  24974. //charf *buf; /* input block, or NULL if too old */
  24975. //ulg stored_len; /* length of input block */
  24976. //int last; /* one if this is the last block for a file */
  24977. {
  24978. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24979. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24980. /* Build the Huffman trees unless a stored block is forced */
  24981. if (s.level > 0) {
  24982. /* Check if the file is binary or text */
  24983. if (s.strm.data_type === Z_UNKNOWN) {
  24984. s.strm.data_type = detect_data_type(s);
  24985. }
  24986. /* Construct the literal and distance trees */
  24987. build_tree(s, s.l_desc);
  24988. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24989. // s->static_len));
  24990. build_tree(s, s.d_desc);
  24991. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24992. // s->static_len));
  24993. /* At this point, opt_len and static_len are the total bit lengths of
  24994. * the compressed block data, excluding the tree representations.
  24995. */
  24996. /* Build the bit length tree for the above two trees, and get the index
  24997. * in bl_order of the last bit length code to send.
  24998. */
  24999. max_blindex = build_bl_tree(s);
  25000. /* Determine the best encoding. Compute the block lengths in bytes. */
  25001. opt_lenb = (s.opt_len+3+7) >>> 3;
  25002. static_lenb = (s.static_len+3+7) >>> 3;
  25003. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25004. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25005. // s->last_lit));
  25006. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25007. } else {
  25008. // Assert(buf != (char*)0, "lost buf");
  25009. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25010. }
  25011. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25012. /* 4: two words for the lengths */
  25013. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25014. * Otherwise we can't have processed more than WSIZE input bytes since
  25015. * the last block flush, because compression would have been
  25016. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25017. * transform a block into a stored block.
  25018. */
  25019. _tr_stored_block(s, buf, stored_len, last);
  25020. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25021. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25022. compress_block(s, static_ltree, static_dtree);
  25023. } else {
  25024. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25025. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25026. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25027. }
  25028. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25029. /* The above check is made mod 2^32, for files larger than 512 MB
  25030. * and uLong implemented on 32 bits.
  25031. */
  25032. init_block(s);
  25033. if (last) {
  25034. bi_windup(s);
  25035. }
  25036. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25037. // s->compressed_len-7*last));
  25038. }
  25039. /* ===========================================================================
  25040. * Save the match info and tally the frequency counts. Return true if
  25041. * the current block must be flushed.
  25042. */
  25043. function _tr_tally(s, dist, lc)
  25044. // deflate_state *s;
  25045. // unsigned dist; /* distance of matched string */
  25046. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25047. {
  25048. //var out_length, in_length, dcode;
  25049. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25050. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25051. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25052. s.last_lit++;
  25053. if (dist === 0) {
  25054. /* lc is the unmatched char */
  25055. s.dyn_ltree[lc*2]/*.Freq*/++;
  25056. } else {
  25057. s.matches++;
  25058. /* Here, lc is the match length - MIN_MATCH */
  25059. dist--; /* dist = match distance - 1 */
  25060. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25061. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25062. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25063. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25064. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25065. }
  25066. // (!) This block is disabled in zlib defailts,
  25067. // don't enable it for binary compatibility
  25068. //#ifdef TRUNCATE_BLOCK
  25069. // /* Try to guess if it is profitable to stop the current block here */
  25070. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25071. // /* Compute an upper bound for the compressed length */
  25072. // out_length = s.last_lit*8;
  25073. // in_length = s.strstart - s.block_start;
  25074. //
  25075. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25076. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25077. // }
  25078. // out_length >>>= 3;
  25079. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25080. // // s->last_lit, in_length, out_length,
  25081. // // 100L - out_length*100L/in_length));
  25082. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25083. // return true;
  25084. // }
  25085. // }
  25086. //#endif
  25087. return (s.last_lit === s.lit_bufsize-1);
  25088. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25089. * on 16 bit machines and because stored blocks are restricted to
  25090. * 64K-1 bytes.
  25091. */
  25092. }
  25093. exports._tr_init = _tr_init;
  25094. exports._tr_stored_block = _tr_stored_block;
  25095. exports._tr_flush_block = _tr_flush_block;
  25096. exports._tr_tally = _tr_tally;
  25097. exports._tr_align = _tr_align;
  25098. },{"../utils/common":73}],85:[function(require,module,exports){
  25099. 'use strict';
  25100. function ZStream() {
  25101. /* next input byte */
  25102. this.input = null; // JS specific, because we have no pointers
  25103. this.next_in = 0;
  25104. /* number of bytes available at input */
  25105. this.avail_in = 0;
  25106. /* total number of input bytes read so far */
  25107. this.total_in = 0;
  25108. /* next output byte should be put there */
  25109. this.output = null; // JS specific, because we have no pointers
  25110. this.next_out = 0;
  25111. /* remaining free space at output */
  25112. this.avail_out = 0;
  25113. /* total number of bytes output so far */
  25114. this.total_out = 0;
  25115. /* last error message, NULL if no error */
  25116. this.msg = ''/*Z_NULL*/;
  25117. /* not visible by applications */
  25118. this.state = null;
  25119. /* best guess about the data type: binary or text */
  25120. this.data_type = 2/*Z_UNKNOWN*/;
  25121. /* adler32 value of the uncompressed data */
  25122. this.adler = 0;
  25123. }
  25124. module.exports = ZStream;
  25125. },{}],86:[function(require,module,exports){
  25126. module.exports = require('./lib/retry');
  25127. },{"./lib/retry":87}],87:[function(require,module,exports){
  25128. var RetryOperation = require('./retry_operation');
  25129. exports.operation = function(options) {
  25130. var timeouts = exports.timeouts(options);
  25131. return new RetryOperation(timeouts);
  25132. };
  25133. exports.timeouts = function(options) {
  25134. if (options instanceof Array) {
  25135. return [].concat(options);
  25136. }
  25137. var opts = {
  25138. retries: 10,
  25139. factor: 2,
  25140. minTimeout: 1 * 1000,
  25141. maxTimeout: Infinity,
  25142. randomize: false
  25143. };
  25144. for (var key in options) {
  25145. opts[key] = options[key];
  25146. }
  25147. if (opts.minTimeout > opts.maxTimeout) {
  25148. throw new Error('minTimeout is greater than maxTimeout');
  25149. }
  25150. var timeouts = [];
  25151. for (var i = 0; i < opts.retries; i++) {
  25152. timeouts.push(this._createTimeout(i, opts));
  25153. }
  25154. // sort the array numerically ascending
  25155. timeouts.sort(function(a,b) {
  25156. return a - b;
  25157. });
  25158. return timeouts;
  25159. };
  25160. exports._createTimeout = function(attempt, opts) {
  25161. var random = (opts.randomize)
  25162. ? (Math.random() + 1)
  25163. : 1;
  25164. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25165. timeout = Math.min(timeout, opts.maxTimeout);
  25166. return timeout;
  25167. };
  25168. },{"./retry_operation":88}],88:[function(require,module,exports){
  25169. function RetryOperation(timeouts) {
  25170. this._timeouts = timeouts;
  25171. this._fn = null;
  25172. this._errors = [];
  25173. this._attempts = 1;
  25174. this._operationTimeout = null;
  25175. this._operationTimeoutCb = null;
  25176. this._timeout = null;
  25177. }
  25178. module.exports = RetryOperation;
  25179. RetryOperation.prototype.retry = function(err) {
  25180. if (this._timeout) {
  25181. clearTimeout(this._timeout);
  25182. }
  25183. if (!err) {
  25184. return false;
  25185. }
  25186. this._errors.push(err);
  25187. var timeout = this._timeouts.shift();
  25188. if (timeout === undefined) {
  25189. return false;
  25190. }
  25191. this._attempts++;
  25192. var self = this;
  25193. setTimeout(function() {
  25194. self._fn(self._attempts);
  25195. if (self._operationTimeoutCb) {
  25196. self._timeout = setTimeout(function() {
  25197. self._operationTimeoutCb(self._attempts);
  25198. }, self._operationTimeout);
  25199. }
  25200. }, timeout);
  25201. return true;
  25202. };
  25203. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25204. this._fn = fn;
  25205. if (timeoutOps) {
  25206. if (timeoutOps.timeout) {
  25207. this._operationTimeout = timeoutOps.timeout;
  25208. }
  25209. if (timeoutOps.cb) {
  25210. this._operationTimeoutCb = timeoutOps.cb;
  25211. }
  25212. }
  25213. this._fn(this._attempts);
  25214. var self = this;
  25215. if (this._operationTimeoutCb) {
  25216. this._timeout = setTimeout(function() {
  25217. self._operationTimeoutCb();
  25218. }, self._operationTimeout);
  25219. }
  25220. };
  25221. RetryOperation.prototype.try = function(fn) {
  25222. console.log('Using RetryOperation.try() is deprecated');
  25223. this.attempt(fn);
  25224. };
  25225. RetryOperation.prototype.start = function(fn) {
  25226. console.log('Using RetryOperation.start() is deprecated');
  25227. this.attempt(fn);
  25228. };
  25229. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25230. RetryOperation.prototype.errors = function() {
  25231. return this._errors;
  25232. };
  25233. RetryOperation.prototype.attempts = function() {
  25234. return this._attempts;
  25235. };
  25236. RetryOperation.prototype.mainError = function() {
  25237. if (this._errors.length === 0) {
  25238. return null;
  25239. }
  25240. var counts = {};
  25241. var mainError = null;
  25242. var mainErrorCount = 0;
  25243. for (var i = 0; i < this._errors.length; i++) {
  25244. var error = this._errors[i];
  25245. var message = error.message;
  25246. var count = (counts[message] || 0) + 1;
  25247. counts[message] = count;
  25248. if (count >= mainErrorCount) {
  25249. mainError = error;
  25250. mainErrorCount = count;
  25251. }
  25252. }
  25253. return mainError;
  25254. };
  25255. },{}],89:[function(require,module,exports){
  25256. module.exports = function arrayEquals(array) {
  25257. // if the other array is a falsy value, return
  25258. if (!array)
  25259. return false;
  25260. // compare lengths - can save a lot of time
  25261. if (this.length != array.length)
  25262. return false;
  25263. for (var i = 0, l = this.length; i < l; i++) {
  25264. // Check if we have nested arrays
  25265. if (this[i] instanceof Array && array[i] instanceof Array) {
  25266. // recurse into the nested arrays
  25267. if (!arrayEquals.apply(this[i], [array[i]]))
  25268. return false;
  25269. } else if (this[i] != array[i]) {
  25270. // Warning - two different object instances will never be equal:
  25271. // {x:20} != {x:20}
  25272. return false;
  25273. }
  25274. }
  25275. return true;
  25276. }
  25277. },{}],90:[function(require,module,exports){
  25278. exports.Interop = require('./interop');
  25279. },{"./interop":91}],91:[function(require,module,exports){
  25280. "use strict";
  25281. var transform = require('./transform');
  25282. var arrayEquals = require('./array-equals');
  25283. function Interop() {
  25284. /**
  25285. * This map holds the most recent Unified Plan offer/answer SDP that was
  25286. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25287. * the SDP string as values.
  25288. *
  25289. * @type {{}}
  25290. */
  25291. this.cache = {};
  25292. }
  25293. module.exports = Interop;
  25294. /**
  25295. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25296. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25297. * application.
  25298. *
  25299. * @param desc
  25300. * @returns {*}
  25301. */
  25302. Interop.prototype.toPlanB = function(desc) {
  25303. //#region Preliminary input validation.
  25304. if (typeof desc !== 'object' || desc === null ||
  25305. typeof desc.sdp !== 'string') {
  25306. console.warn('An empty description was passed as an argument.');
  25307. return desc;
  25308. }
  25309. // Objectify the SDP for easier manipulation.
  25310. var session = transform.parse(desc.sdp);
  25311. // If the SDP contains no media, there's nothing to transform.
  25312. if (typeof session.media === 'undefined' ||
  25313. !Array.isArray(session.media) || session.media.length === 0) {
  25314. console.warn('The description has no media.');
  25315. return desc;
  25316. }
  25317. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25318. // SDP has a video, an audio and a data "channel" at most.
  25319. if (session.media.length <= 3 && session.media.every(function(m) {
  25320. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25321. })) {
  25322. console.warn('This description does not look like Unified Plan.');
  25323. return desc;
  25324. }
  25325. //#endregion
  25326. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25327. // -> Unified Plan transformation.
  25328. this.cache[desc.type] = desc.sdp;
  25329. //#region Convert from Unified Plan to Plan B.
  25330. // We rebuild the session.media array.
  25331. var media = session.media;
  25332. session.media = [];
  25333. // Associative array that maps channel types to channel objects for fast
  25334. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25335. // obj.
  25336. var type2bl = {};
  25337. // Used to build the group:BUNDLE value after the channels construction
  25338. // loop.
  25339. var types = [];
  25340. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25341. media.forEach(function(unifiedLine) {
  25342. // rtcp-mux is required in the Plan B SDP.
  25343. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25344. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25345. unifiedLine.direction !== 'inactive') {
  25346. throw new Error('Cannot convert to Plan B because m-lines ' +
  25347. 'without the rtcp-mux attribute were found.');
  25348. }
  25349. if (unifiedLine.type === 'application') {
  25350. session.media.push(unifiedLine);
  25351. types.push(unifiedLine.mid);
  25352. return;
  25353. }
  25354. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25355. // as the channel basis.
  25356. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25357. type2bl[unifiedLine.type] = unifiedLine;
  25358. }
  25359. // Add sources to the channel and handle a=msid.
  25360. if (typeof unifiedLine.sources === 'object') {
  25361. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25362. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25363. type2bl[unifiedLine.type].sources = {};
  25364. // Assign the sources to the channel.
  25365. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25366. if (typeof unifiedLine.msid !== 'undefined') {
  25367. // In Plan B the msid is an SSRC attribute. Also, we don't
  25368. // care about the obsolete label and mslabel attributes.
  25369. //
  25370. // Note that it is not guaranteed that the unifiedLine will have
  25371. // an msid. recvonly channels in particular don't have one.
  25372. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25373. }
  25374. // NOTE ssrcs in ssrc groups will share msids, as
  25375. // draft-uberti-rtcweb-plan-00 mandates.
  25376. });
  25377. }
  25378. // Add ssrc groups to the channel.
  25379. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25380. Array.isArray(unifiedLine.ssrcGroups)) {
  25381. // Create the ssrcGroups array, if it's not defined.
  25382. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25383. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25384. type2bl[unifiedLine.type].ssrcGroups = [];
  25385. }
  25386. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25387. }
  25388. if (type2bl[unifiedLine.type] === unifiedLine) {
  25389. // Copy ICE related stuff from the principal media line.
  25390. unifiedLine.candidates = media[0].candidates;
  25391. unifiedLine.iceUfrag = media[0].iceUfrag;
  25392. unifiedLine.icePwd = media[0].icePwd;
  25393. unifiedLine.fingerprint = media[0].fingerprint;
  25394. // Plan B mids are in ['audio', 'video', 'data']
  25395. unifiedLine.mid = unifiedLine.type;
  25396. // Plan B doesn't support/need the bundle-only attribute.
  25397. delete unifiedLine.bundleOnly;
  25398. // In Plan B the msid is an SSRC attribute.
  25399. delete unifiedLine.msid;
  25400. // Used to build the group:BUNDLE value after this loop.
  25401. types.push(unifiedLine.type);
  25402. // Add the channel to the new media array.
  25403. session.media.push(unifiedLine);
  25404. }
  25405. });
  25406. // We regenerate the BUNDLE group with the new mids.
  25407. session.groups.some(function(group) {
  25408. if (group.type === 'BUNDLE') {
  25409. group.mids = types.join(' ');
  25410. return true;
  25411. }
  25412. });
  25413. // msid semantic
  25414. session.msidSemantic = {
  25415. semantic: 'WMS',
  25416. token: '*'
  25417. };
  25418. var resStr = transform.write(session);
  25419. return new RTCSessionDescription({
  25420. type: desc.type,
  25421. sdp: resStr
  25422. });
  25423. //#endregion
  25424. };
  25425. /**
  25426. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25427. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25428. * to FF.
  25429. *
  25430. * @param desc
  25431. * @returns {*}
  25432. */
  25433. Interop.prototype.toUnifiedPlan = function(desc) {
  25434. //#region Preliminary input validation.
  25435. if (typeof desc !== 'object' || desc === null ||
  25436. typeof desc.sdp !== 'string') {
  25437. console.warn('An empty description was passed as an argument.');
  25438. return desc;
  25439. }
  25440. var session = transform.parse(desc.sdp);
  25441. // If the SDP contains no media, there's nothing to transform.
  25442. if (typeof session.media === 'undefined' ||
  25443. !Array.isArray(session.media) || session.media.length === 0) {
  25444. console.warn('The description has no media.');
  25445. return desc;
  25446. }
  25447. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25448. // a video, an audio and a data "channel" at most.
  25449. if (session.media.length > 3 || !session.media.every(function(m) {
  25450. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25451. })) {
  25452. console.warn('This description does not look like Plan B.');
  25453. return desc;
  25454. }
  25455. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25456. var mids = [];
  25457. session.media.forEach(function(m) {
  25458. mids.push(m.mid);
  25459. });
  25460. var hasBundle = false;
  25461. if (typeof session.groups !== 'undefined' &&
  25462. Array.isArray(session.groups)) {
  25463. hasBundle = session.groups.every(function(g) {
  25464. return g.type !== 'BUNDLE' ||
  25465. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25466. });
  25467. }
  25468. if (!hasBundle) {
  25469. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25470. " are not bundled were found.");
  25471. }
  25472. //#endregion
  25473. //#region Convert from Plan B to Unified Plan.
  25474. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25475. // rebuild an equivalent Unified Plan offer/answer.
  25476. //
  25477. // For example, if this is a local answer (in Unified Plan style) that we
  25478. // convert to Plan B prior to handing it over to the application (the
  25479. // PeerConnection wrapper called us, for instance, after a successful
  25480. // createAnswer), we want to remember the m-line at which we've seen the
  25481. // (local) SSRC. That's because when the application wants to do call the
  25482. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25483. // Unified Plan), we need to know to which m-line to assign the (local)
  25484. // SSRC. We also need to know all the other m-lines that the original
  25485. // answer had and include them in the transformed answer as well.
  25486. //
  25487. // Another example is if this is a remote offer that we convert to Plan B
  25488. // prior to giving it to the application, we want to remember the mid at
  25489. // which we've seen the (remote) SSRC.
  25490. //
  25491. // In the iteration that follows, we use the cached Unified Plan (if it
  25492. // exists) to assign mids to ssrcs.
  25493. var cached;
  25494. if (typeof this.cache[desc.type] !== 'undefined') {
  25495. cached = transform.parse(this.cache[desc.type]);
  25496. }
  25497. // A helper map that sends mids to m-line objects. We use it later to
  25498. // rebuild the Unified Plan style session.media array.
  25499. var mid2ul = {};
  25500. session.media.forEach(function(bLine) {
  25501. if ((typeof bLine.rtcpMux !== 'string' ||
  25502. bLine.rtcpMux !== 'rtcp-mux') &&
  25503. bLine.direction !== 'inactive') {
  25504. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25505. "without the rtcp-mux attribute were found.");
  25506. }
  25507. if (bLine.type === 'application') {
  25508. mid2ul[bLine.mid] = bLine;
  25509. return;
  25510. }
  25511. // With rtcp-mux and bundle all the channels should have the same ICE
  25512. // stuff.
  25513. var sources = bLine.sources;
  25514. var ssrcGroups = bLine.ssrcGroups;
  25515. var candidates = bLine.candidates;
  25516. var iceUfrag = bLine.iceUfrag;
  25517. var icePwd = bLine.icePwd;
  25518. var fingerprint = bLine.fingerprint;
  25519. var port = bLine.port;
  25520. // We'll use the "bLine" object as a prototype for each new "mLine"
  25521. // that we create, but first we need to clean it up a bit.
  25522. delete bLine.sources;
  25523. delete bLine.ssrcGroups;
  25524. delete bLine.candidates;
  25525. delete bLine.iceUfrag;
  25526. delete bLine.icePwd;
  25527. delete bLine.fingerprint;
  25528. delete bLine.port;
  25529. delete bLine.mid;
  25530. // inverted ssrc group map
  25531. var ssrc2group = {};
  25532. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25533. ssrcGroups.forEach(function (ssrcGroup) {
  25534. // TODO(gp) find out how to receive simulcast with FF. For the
  25535. // time being, hide it.
  25536. if (ssrcGroup.semantics === 'SIM') {
  25537. return;
  25538. }
  25539. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25540. Array.isArray(ssrcGroup.ssrcs)) {
  25541. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25542. if (typeof ssrc2group[ssrc] === 'undefined') {
  25543. ssrc2group[ssrc] = [];
  25544. }
  25545. ssrc2group[ssrc].push(ssrcGroup);
  25546. });
  25547. }
  25548. });
  25549. }
  25550. // ssrc to m-line index.
  25551. var ssrc2ml = {};
  25552. if (typeof sources === 'object') {
  25553. // Explode the Plan B channel sources with one m-line per source.
  25554. Object.keys(sources).forEach(function(ssrc) {
  25555. // The (unified) m-line for this SSRC. We either create it from
  25556. // scratch or, if it's a grouped SSRC, we re-use a related
  25557. // mline. In other words, if the source is grouped with another
  25558. // source, put the two together in the same m-line.
  25559. var unifiedLine;
  25560. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25561. Array.isArray(ssrc2group[ssrc])) {
  25562. ssrc2group[ssrc].some(function (ssrcGroup) {
  25563. // ssrcGroup.ssrcs *is* an Array, no need to check
  25564. // again here.
  25565. return ssrcGroup.ssrcs.some(function (related) {
  25566. if (typeof ssrc2ml[related] === 'object') {
  25567. unifiedLine = ssrc2ml[related];
  25568. return true;
  25569. }
  25570. });
  25571. });
  25572. }
  25573. if (typeof unifiedLine === 'object') {
  25574. // the m-line already exists. Just add the source.
  25575. unifiedLine.sources[ssrc] = sources[ssrc];
  25576. delete sources[ssrc].msid;
  25577. } else {
  25578. // Use the "bLine" as a prototype for the "unifiedLine".
  25579. unifiedLine = Object.create(bLine);
  25580. ssrc2ml[ssrc] = unifiedLine;
  25581. if (typeof sources[ssrc].msid !== 'undefined') {
  25582. // Assign the msid of the source to the m-line. Note
  25583. // that it is not guaranteed that the source will have
  25584. // msid. In particular "recvonly" sources don't have an
  25585. // msid. Note that "recvonly" is a term only defined
  25586. // for m-lines.
  25587. unifiedLine.msid = sources[ssrc].msid;
  25588. delete sources[ssrc].msid;
  25589. }
  25590. // We assign one SSRC per media line.
  25591. unifiedLine.sources = {};
  25592. unifiedLine.sources[ssrc] = sources[ssrc];
  25593. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25594. // Use the cached Unified Plan SDP (if it exists) to assign
  25595. // SSRCs to mids.
  25596. if (typeof cached !== 'undefined' &&
  25597. typeof cached.media !== 'undefined' &&
  25598. Array.isArray(cached.media)) {
  25599. cached.media.forEach(function (m) {
  25600. if (typeof m.sources === 'object') {
  25601. Object.keys(m.sources).forEach(function (s) {
  25602. if (s === ssrc) {
  25603. unifiedLine.mid = m.mid;
  25604. }
  25605. });
  25606. }
  25607. });
  25608. }
  25609. if (typeof unifiedLine.mid === 'undefined') {
  25610. // If this is an SSRC that we see for the first time
  25611. // assign it a new mid. This is typically the case when
  25612. // this method is called to transform a remote
  25613. // description for the first time or when there is a
  25614. // new SSRC in the remote description because a new
  25615. // peer has joined the conference. Local SSRCs should
  25616. // have already been added to the map in the toPlanB
  25617. // method.
  25618. //
  25619. // Because FF generates answers in Unified Plan style,
  25620. // we MUST already have a cached answer with all the
  25621. // local SSRCs mapped to some m-line/mid.
  25622. if (desc.type === 'answer') {
  25623. throw new Error("An unmapped SSRC was found.");
  25624. }
  25625. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25626. }
  25627. // Include the candidates in the 1st media line.
  25628. unifiedLine.candidates = candidates;
  25629. unifiedLine.iceUfrag = iceUfrag;
  25630. unifiedLine.icePwd = icePwd;
  25631. unifiedLine.fingerprint = fingerprint;
  25632. unifiedLine.port = port;
  25633. mid2ul[unifiedLine.mid] = unifiedLine;
  25634. }
  25635. });
  25636. }
  25637. });
  25638. // Rebuild the media array in the right order and add the missing mLines
  25639. // (missing from the Plan B SDP).
  25640. session.media = [];
  25641. mids = []; // reuse
  25642. if (desc.type === 'answer') {
  25643. // The media lines in the answer must match the media lines in the
  25644. // offer. The order is important too. Here we assume that Firefox is the
  25645. // answerer, so we merely have to use the reconstructed (unified) answer
  25646. // to update the cached (unified) answer accordingly.
  25647. //
  25648. // In the general case, one would have to use the cached (unified) offer
  25649. // to find the m-lines that are missing from the reconstructed answer,
  25650. // potentially grabbing them from the cached (unified) answer. One has
  25651. // to be carefull with this approach because inactive m-lines do not
  25652. // always have an mid, making it tricky (impossible?) to find where
  25653. // exactly and which m-lines are missing from the reconstructed answer.
  25654. for (var i = 0; i < cached.media.length; i++) {
  25655. var unifiedLine = cached.media[i];
  25656. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25657. // The mid isn't in the reconstructed (unified) answer.
  25658. // This is either a (unified) m-line containing a remote
  25659. // track only, or a (unified) m-line containing a remote
  25660. // track and a local track that has been removed.
  25661. // In either case, it MUST exist in the cached
  25662. // (unified) answer.
  25663. //
  25664. // In case this is a removed local track, clean-up
  25665. // the (unified) m-line and make sure it's 'recvonly' or
  25666. // 'inactive'.
  25667. delete unifiedLine.msid;
  25668. delete unifiedLine.sources;
  25669. delete unifiedLine.ssrcGroups;
  25670. if (!unifiedLine.direction
  25671. || unifiedLine.direction === 'sendrecv')
  25672. unifiedLine.direction = 'recvonly';
  25673. if (!unifiedLine.direction
  25674. || unifiedLine.direction === 'sendonly')
  25675. unifiedLine.direction = 'inactive';
  25676. } else {
  25677. // This is an (unified) m-line/channel that contains a local
  25678. // track (sendrecv or sendonly channel) or it's a unified
  25679. // recvonly m-line/channel. In either case, since we're
  25680. // going from PlanB -> Unified Plan this m-line MUST
  25681. // exist in the cached answer.
  25682. }
  25683. session.media.push(unifiedLine);
  25684. if (typeof unifiedLine.mid === 'string') {
  25685. // inactive lines don't/may not have an mid.
  25686. mids.push(unifiedLine.mid);
  25687. }
  25688. }
  25689. } else {
  25690. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25691. // under any circumstances. If we are no longer interested in sending a
  25692. // track, we just remove the msid and ssrc attributes and set it to
  25693. // either a=recvonly (as the reofferer, we must use recvonly if the
  25694. // other side was previously sending on the m-section, but we can also
  25695. // leave the possibility open if it wasn't previously in use), or
  25696. // a=inacive.
  25697. if (typeof cached !== 'undefined' &&
  25698. typeof cached.media !== 'undefined' &&
  25699. Array.isArray(cached.media)) {
  25700. cached.media.forEach(function(unifiedLine) {
  25701. mids.push(unifiedLine.mid);
  25702. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25703. session.media.push(mid2ul[unifiedLine.mid]);
  25704. } else {
  25705. delete unifiedLine.msid;
  25706. delete unifiedLine.sources;
  25707. delete unifiedLine.ssrcGroups;
  25708. if (!unifiedLine.direction
  25709. || unifiedLine.direction === 'sendrecv')
  25710. unifiedLine.direction = 'recvonly';
  25711. if (!unifiedLine.direction
  25712. || unifiedLine.direction === 'sendonly')
  25713. unifiedLine.direction = 'inactive';
  25714. session.media.push(unifiedLine);
  25715. }
  25716. });
  25717. }
  25718. // Add all the remaining (new) m-lines of the transformed SDP.
  25719. Object.keys(mid2ul).forEach(function(mid) {
  25720. if (mids.indexOf(mid) === -1) {
  25721. mids.push(mid);
  25722. if (typeof mid2ul[mid].direction === 'recvonly') {
  25723. // This is a remote recvonly channel. Add its SSRC to the
  25724. // appropriate sendrecv or sendonly channel.
  25725. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25726. session.media.some(function (unifiedLine) {
  25727. if ((unifiedLine.direction === 'sendrecv' ||
  25728. unifiedLine.direction === 'sendonly') &&
  25729. unifiedLine.type === mid2ul[mid].type) {
  25730. // mid2ul[mid] shouldn't have any ssrc-groups
  25731. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25732. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25733. });
  25734. return true;
  25735. }
  25736. });
  25737. } else {
  25738. session.media.push(mid2ul[mid]);
  25739. }
  25740. }
  25741. });
  25742. }
  25743. // We regenerate the BUNDLE group (since we regenerated the mids)
  25744. session.groups.some(function(group) {
  25745. if (group.type === 'BUNDLE') {
  25746. group.mids = mids.join(' ');
  25747. return true;
  25748. }
  25749. });
  25750. // msid semantic
  25751. session.msidSemantic = {
  25752. semantic: 'WMS',
  25753. token: '*'
  25754. };
  25755. var resStr = transform.write(session);
  25756. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25757. // function.
  25758. this.cache[desc.type] = resStr;
  25759. return new RTCSessionDescription({
  25760. type: desc.type,
  25761. sdp: resStr
  25762. });
  25763. //#endregion
  25764. };
  25765. },{"./array-equals":89,"./transform":92}],92:[function(require,module,exports){
  25766. var transform = require('sdp-transform');
  25767. exports.write = function(session, opts) {
  25768. if (typeof session !== 'undefined' &&
  25769. typeof session.media !== 'undefined' &&
  25770. Array.isArray(session.media)) {
  25771. session.media.forEach(function (mLine) {
  25772. // expand sources to ssrcs
  25773. if (typeof mLine.sources !== 'undefined' &&
  25774. Object.keys(mLine.sources).length !== 0) {
  25775. mLine.ssrcs = [];
  25776. Object.keys(mLine.sources).forEach(function (ssrc) {
  25777. var source = mLine.sources[ssrc];
  25778. Object.keys(source).forEach(function (attribute) {
  25779. mLine.ssrcs.push({
  25780. id: ssrc,
  25781. attribute: attribute,
  25782. value: source[attribute]
  25783. });
  25784. });
  25785. });
  25786. delete mLine.sources;
  25787. }
  25788. // join ssrcs in ssrc groups
  25789. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25790. Array.isArray(mLine.ssrcGroups)) {
  25791. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25792. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25793. Array.isArray(ssrcGroup.ssrcs)) {
  25794. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25795. }
  25796. });
  25797. }
  25798. });
  25799. }
  25800. // join group mids
  25801. if (typeof session !== 'undefined' &&
  25802. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25803. session.groups.forEach(function (g) {
  25804. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25805. g.mids = g.mids.join(' ');
  25806. }
  25807. });
  25808. }
  25809. return transform.write(session, opts);
  25810. };
  25811. exports.parse = function(sdp) {
  25812. var session = transform.parse(sdp);
  25813. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25814. Array.isArray(session.media)) {
  25815. session.media.forEach(function (mLine) {
  25816. // group sources attributes by ssrc
  25817. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25818. mLine.sources = {};
  25819. mLine.ssrcs.forEach(function (ssrc) {
  25820. if (!mLine.sources[ssrc.id])
  25821. mLine.sources[ssrc.id] = {};
  25822. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25823. });
  25824. delete mLine.ssrcs;
  25825. }
  25826. // split ssrcs in ssrc groups
  25827. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25828. Array.isArray(mLine.ssrcGroups)) {
  25829. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25830. if (typeof ssrcGroup.ssrcs === 'string') {
  25831. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25832. }
  25833. });
  25834. }
  25835. });
  25836. }
  25837. // split group mids
  25838. if (typeof session !== 'undefined' &&
  25839. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25840. session.groups.forEach(function (g) {
  25841. if (typeof g.mids === 'string') {
  25842. g.mids = g.mids.split(' ');
  25843. }
  25844. });
  25845. }
  25846. return session;
  25847. };
  25848. },{"sdp-transform":94}],93:[function(require,module,exports){
  25849. var grammar = module.exports = {
  25850. v: [{
  25851. name: 'version',
  25852. reg: /^(\d*)$/
  25853. }],
  25854. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25855. // NB: sessionId will be a String in most cases because it is huge
  25856. name: 'origin',
  25857. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25858. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25859. format: "%s %s %d %s IP%d %s"
  25860. }],
  25861. // default parsing of these only (though some of these feel outdated)
  25862. s: [{ name: 'name' }],
  25863. i: [{ name: 'description' }],
  25864. u: [{ name: 'uri' }],
  25865. e: [{ name: 'email' }],
  25866. p: [{ name: 'phone' }],
  25867. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25868. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25869. //k: [{}], // outdated thing ignored
  25870. t: [{ //t=0 0
  25871. name: 'timing',
  25872. reg: /^(\d*) (\d*)/,
  25873. names: ['start', 'stop'],
  25874. format: "%d %d"
  25875. }],
  25876. c: [{ //c=IN IP4 10.47.197.26
  25877. name: 'connection',
  25878. reg: /^IN IP(\d) (\S*)/,
  25879. names: ['version', 'ip'],
  25880. format: "IN IP%d %s"
  25881. }],
  25882. b: [{ //b=AS:4000
  25883. push: 'bandwidth',
  25884. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25885. names: ['type', 'limit'],
  25886. format: "%s:%s"
  25887. }],
  25888. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25889. // NB: special - pushes to session
  25890. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25891. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25892. names: ['type', 'port', 'protocol', 'payloads'],
  25893. format: "%s %d %s %s"
  25894. }],
  25895. a: [
  25896. { //a=rtpmap:110 opus/48000/2
  25897. push: 'rtp',
  25898. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25899. names: ['payload', 'codec', 'rate', 'encoding'],
  25900. format: function (o) {
  25901. return (o.encoding) ?
  25902. "rtpmap:%d %s/%s/%s":
  25903. "rtpmap:%d %s/%s";
  25904. }
  25905. },
  25906. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25907. push: 'fmtp',
  25908. reg: /^fmtp:(\d*) (\S*)/,
  25909. names: ['payload', 'config'],
  25910. format: "fmtp:%d %s"
  25911. },
  25912. { //a=control:streamid=0
  25913. name: 'control',
  25914. reg: /^control:(.*)/,
  25915. format: "control:%s"
  25916. },
  25917. { //a=rtcp:65179 IN IP4 193.84.77.194
  25918. name: 'rtcp',
  25919. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25920. names: ['port', 'netType', 'ipVer', 'address'],
  25921. format: function (o) {
  25922. return (o.address != null) ?
  25923. "rtcp:%d %s IP%d %s":
  25924. "rtcp:%d";
  25925. }
  25926. },
  25927. { //a=rtcp-fb:98 trr-int 100
  25928. push: 'rtcpFbTrrInt',
  25929. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25930. names: ['payload', 'value'],
  25931. format: "rtcp-fb:%d trr-int %d"
  25932. },
  25933. { //a=rtcp-fb:98 nack rpsi
  25934. push: 'rtcpFb',
  25935. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25936. names: ['payload', 'type', 'subtype'],
  25937. format: function (o) {
  25938. return (o.subtype != null) ?
  25939. "rtcp-fb:%s %s %s":
  25940. "rtcp-fb:%s %s";
  25941. }
  25942. },
  25943. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25944. //a=extmap:1/recvonly URI-gps-string
  25945. push: 'ext',
  25946. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25947. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25948. format: function (o) {
  25949. return (o.config != null) ?
  25950. "extmap:%s %s %s":
  25951. "extmap:%s %s";
  25952. }
  25953. },
  25954. {
  25955. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25956. push: 'crypto',
  25957. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25958. names: ['id', 'suite', 'config', 'sessionConfig'],
  25959. format: function (o) {
  25960. return (o.sessionConfig != null) ?
  25961. "crypto:%d %s %s %s":
  25962. "crypto:%d %s %s";
  25963. }
  25964. },
  25965. { //a=setup:actpass
  25966. name: 'setup',
  25967. reg: /^setup:(\w*)/,
  25968. format: "setup:%s"
  25969. },
  25970. { //a=mid:1
  25971. name: 'mid',
  25972. reg: /^mid:([^\s]*)/,
  25973. format: "mid:%s"
  25974. },
  25975. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25976. name: 'msid',
  25977. reg: /^msid:(.*)/,
  25978. format: "msid:%s"
  25979. },
  25980. { //a=ptime:20
  25981. name: 'ptime',
  25982. reg: /^ptime:(\d*)/,
  25983. format: "ptime:%d"
  25984. },
  25985. { //a=maxptime:60
  25986. name: 'maxptime',
  25987. reg: /^maxptime:(\d*)/,
  25988. format: "maxptime:%d"
  25989. },
  25990. { //a=sendrecv
  25991. name: 'direction',
  25992. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25993. },
  25994. { //a=ice-lite
  25995. name: 'icelite',
  25996. reg: /^(ice-lite)/
  25997. },
  25998. { //a=ice-ufrag:F7gI
  25999. name: 'iceUfrag',
  26000. reg: /^ice-ufrag:(\S*)/,
  26001. format: "ice-ufrag:%s"
  26002. },
  26003. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26004. name: 'icePwd',
  26005. reg: /^ice-pwd:(\S*)/,
  26006. format: "ice-pwd:%s"
  26007. },
  26008. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26009. name: 'fingerprint',
  26010. reg: /^fingerprint:(\S*) (\S*)/,
  26011. names: ['type', 'hash'],
  26012. format: "fingerprint:%s %s"
  26013. },
  26014. {
  26015. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26016. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26017. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26018. push:'candidates',
  26019. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26020. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26021. format: function (o) {
  26022. var str = "candidate:%s %d %s %d %s %d typ %s";
  26023. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26024. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26025. if (o.generation != null) {
  26026. str += " generation %d";
  26027. }
  26028. return str;
  26029. }
  26030. },
  26031. { //a=end-of-candidates (keep after the candidates line for readability)
  26032. name: 'endOfCandidates',
  26033. reg: /^(end-of-candidates)/
  26034. },
  26035. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26036. name: 'remoteCandidates',
  26037. reg: /^remote-candidates:(.*)/,
  26038. format: "remote-candidates:%s"
  26039. },
  26040. { //a=ice-options:google-ice
  26041. name: 'iceOptions',
  26042. reg: /^ice-options:(\S*)/,
  26043. format: "ice-options:%s"
  26044. },
  26045. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26046. push: "ssrcs",
  26047. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26048. names: ['id', 'attribute', 'value'],
  26049. format: "ssrc:%d %s:%s"
  26050. },
  26051. { //a=ssrc-group:FEC 1 2
  26052. push: "ssrcGroups",
  26053. reg: /^ssrc-group:(\w*) (.*)/,
  26054. names: ['semantics', 'ssrcs'],
  26055. format: "ssrc-group:%s %s"
  26056. },
  26057. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26058. name: "msidSemantic",
  26059. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26060. names: ['semantic', 'token'],
  26061. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26062. },
  26063. { //a=group:BUNDLE audio video
  26064. push: 'groups',
  26065. reg: /^group:(\w*) (.*)/,
  26066. names: ['type', 'mids'],
  26067. format: "group:%s %s"
  26068. },
  26069. { //a=rtcp-mux
  26070. name: 'rtcpMux',
  26071. reg: /^(rtcp-mux)/
  26072. },
  26073. { //a=rtcp-rsize
  26074. name: 'rtcpRsize',
  26075. reg: /^(rtcp-rsize)/
  26076. },
  26077. { // any a= that we don't understand is kepts verbatim on media.invalid
  26078. push: 'invalid',
  26079. names: ["value"]
  26080. }
  26081. ]
  26082. };
  26083. // set sensible defaults to avoid polluting the grammar with boring details
  26084. Object.keys(grammar).forEach(function (key) {
  26085. var objs = grammar[key];
  26086. objs.forEach(function (obj) {
  26087. if (!obj.reg) {
  26088. obj.reg = /(.*)/;
  26089. }
  26090. if (!obj.format) {
  26091. obj.format = "%s";
  26092. }
  26093. });
  26094. });
  26095. },{}],94:[function(require,module,exports){
  26096. var parser = require('./parser');
  26097. var writer = require('./writer');
  26098. exports.write = writer;
  26099. exports.parse = parser.parse;
  26100. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26101. exports.parsePayloads = parser.parsePayloads;
  26102. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26103. },{"./parser":95,"./writer":96}],95:[function(require,module,exports){
  26104. var toIntIfInt = function (v) {
  26105. return String(Number(v)) === v ? Number(v) : v;
  26106. };
  26107. var attachProperties = function (match, location, names, rawName) {
  26108. if (rawName && !names) {
  26109. location[rawName] = toIntIfInt(match[1]);
  26110. }
  26111. else {
  26112. for (var i = 0; i < names.length; i += 1) {
  26113. if (match[i+1] != null) {
  26114. location[names[i]] = toIntIfInt(match[i+1]);
  26115. }
  26116. }
  26117. }
  26118. };
  26119. var parseReg = function (obj, location, content) {
  26120. var needsBlank = obj.name && obj.names;
  26121. if (obj.push && !location[obj.push]) {
  26122. location[obj.push] = [];
  26123. }
  26124. else if (needsBlank && !location[obj.name]) {
  26125. location[obj.name] = {};
  26126. }
  26127. var keyLocation = obj.push ?
  26128. {} : // blank object that will be pushed
  26129. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26130. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26131. if (obj.push) {
  26132. location[obj.push].push(keyLocation);
  26133. }
  26134. };
  26135. var grammar = require('./grammar');
  26136. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26137. exports.parse = function (sdp) {
  26138. var session = {}
  26139. , media = []
  26140. , location = session; // points at where properties go under (one of the above)
  26141. // parse lines we understand
  26142. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26143. var type = l[0];
  26144. var content = l.slice(2);
  26145. if (type === 'm') {
  26146. media.push({rtp: [], fmtp: []});
  26147. location = media[media.length-1]; // point at latest media line
  26148. }
  26149. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26150. var obj = grammar[type][j];
  26151. if (obj.reg.test(content)) {
  26152. return parseReg(obj, location, content);
  26153. }
  26154. }
  26155. });
  26156. session.media = media; // link it up
  26157. return session;
  26158. };
  26159. var fmtpReducer = function (acc, expr) {
  26160. var s = expr.split('=');
  26161. if (s.length === 2) {
  26162. acc[s[0]] = toIntIfInt(s[1]);
  26163. }
  26164. return acc;
  26165. };
  26166. exports.parseFmtpConfig = function (str) {
  26167. return str.split(';').reduce(fmtpReducer, {});
  26168. };
  26169. exports.parsePayloads = function (str) {
  26170. return str.split(' ').map(Number);
  26171. };
  26172. exports.parseRemoteCandidates = function (str) {
  26173. var candidates = [];
  26174. var parts = str.split(' ').map(toIntIfInt);
  26175. for (var i = 0; i < parts.length; i += 3) {
  26176. candidates.push({
  26177. component: parts[i],
  26178. ip: parts[i + 1],
  26179. port: parts[i + 2]
  26180. });
  26181. }
  26182. return candidates;
  26183. };
  26184. },{"./grammar":93}],96:[function(require,module,exports){
  26185. var grammar = require('./grammar');
  26186. // customized util.format - discards excess arguments and can void middle ones
  26187. var formatRegExp = /%[sdv%]/g;
  26188. var format = function (formatStr) {
  26189. var i = 1;
  26190. var args = arguments;
  26191. var len = args.length;
  26192. return formatStr.replace(formatRegExp, function (x) {
  26193. if (i >= len) {
  26194. return x; // missing argument
  26195. }
  26196. var arg = args[i];
  26197. i += 1;
  26198. switch (x) {
  26199. case '%%':
  26200. return '%';
  26201. case '%s':
  26202. return String(arg);
  26203. case '%d':
  26204. return Number(arg);
  26205. case '%v':
  26206. return '';
  26207. }
  26208. });
  26209. // NB: we discard excess arguments - they are typically undefined from makeLine
  26210. };
  26211. var makeLine = function (type, obj, location) {
  26212. var str = obj.format instanceof Function ?
  26213. (obj.format(obj.push ? location : location[obj.name])) :
  26214. obj.format;
  26215. var args = [type + '=' + str];
  26216. if (obj.names) {
  26217. for (var i = 0; i < obj.names.length; i += 1) {
  26218. var n = obj.names[i];
  26219. if (obj.name) {
  26220. args.push(location[obj.name][n]);
  26221. }
  26222. else { // for mLine and push attributes
  26223. args.push(location[obj.names[i]]);
  26224. }
  26225. }
  26226. }
  26227. else {
  26228. args.push(location[obj.name]);
  26229. }
  26230. return format.apply(null, args);
  26231. };
  26232. // RFC specified order
  26233. // TODO: extend this with all the rest
  26234. var defaultOuterOrder = [
  26235. 'v', 'o', 's', 'i',
  26236. 'u', 'e', 'p', 'c',
  26237. 'b', 't', 'r', 'z', 'a'
  26238. ];
  26239. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26240. module.exports = function (session, opts) {
  26241. opts = opts || {};
  26242. // ensure certain properties exist
  26243. if (session.version == null) {
  26244. session.version = 0; // "v=0" must be there (only defined version atm)
  26245. }
  26246. if (session.name == null) {
  26247. session.name = " "; // "s= " must be there if no meaningful name set
  26248. }
  26249. session.media.forEach(function (mLine) {
  26250. if (mLine.payloads == null) {
  26251. mLine.payloads = "";
  26252. }
  26253. });
  26254. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26255. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26256. var sdp = [];
  26257. // loop through outerOrder for matching properties on session
  26258. outerOrder.forEach(function (type) {
  26259. grammar[type].forEach(function (obj) {
  26260. if (obj.name in session && session[obj.name] != null) {
  26261. sdp.push(makeLine(type, obj, session));
  26262. }
  26263. else if (obj.push in session && session[obj.push] != null) {
  26264. session[obj.push].forEach(function (el) {
  26265. sdp.push(makeLine(type, obj, el));
  26266. });
  26267. }
  26268. });
  26269. });
  26270. // then for each media line, follow the innerOrder
  26271. session.media.forEach(function (mLine) {
  26272. sdp.push(makeLine('m', grammar.m[0], mLine));
  26273. innerOrder.forEach(function (type) {
  26274. grammar[type].forEach(function (obj) {
  26275. if (obj.name in mLine && mLine[obj.name] != null) {
  26276. sdp.push(makeLine(type, obj, mLine));
  26277. }
  26278. else if (obj.push in mLine && mLine[obj.push] != null) {
  26279. mLine[obj.push].forEach(function (el) {
  26280. sdp.push(makeLine(type, obj, el));
  26281. });
  26282. }
  26283. });
  26284. });
  26285. });
  26286. return sdp.join('\r\n') + '\r\n';
  26287. };
  26288. },{"./grammar":93}],97:[function(require,module,exports){
  26289. var transform = require('sdp-transform');
  26290. var transformUtils = require('./transform-utils');
  26291. var parseSsrcs = transformUtils.parseSsrcs;
  26292. var writeSsrcs = transformUtils.writeSsrcs;
  26293. //region Constants
  26294. var DEFAULT_NUM_OF_LAYERS = 3;
  26295. //endregion
  26296. //region Ctor
  26297. function Simulcast(options) {
  26298. this.options = options ? options : {};
  26299. if (!this.options.numOfLayers) {
  26300. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26301. }
  26302. this.layers = [];
  26303. }
  26304. //endregion
  26305. //region Stateless private utility functions
  26306. /**
  26307. * Returns a random integer between min (included) and max (excluded)
  26308. * Using Math.round() gives a non-uniform distribution!
  26309. * @returns {number}
  26310. */
  26311. function generateSSRC() {
  26312. var min = 0, max = 0xffffffff;
  26313. return Math.floor(Math.random() * (max - min)) + min;
  26314. };
  26315. function processVideo(session, action) {
  26316. if (session == null || !Array.isArray(session.media)) {
  26317. return;
  26318. }
  26319. session.media.forEach(function (mLine) {
  26320. if (mLine.type === 'video') {
  26321. action(mLine);
  26322. }
  26323. });
  26324. }
  26325. function validateDescription(desc)
  26326. {
  26327. return desc && desc != null
  26328. && desc.type && desc.type != ''
  26329. && desc.sdp && desc.sdp != '';
  26330. }
  26331. function explodeRemoteSimulcast(mLine) {
  26332. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26333. return;
  26334. }
  26335. var sources = parseSsrcs(mLine);
  26336. var order = [];
  26337. // Find the SIM group and explode its sources.
  26338. var j = mLine.ssrcGroups.length;
  26339. while (j--) {
  26340. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26341. continue;
  26342. }
  26343. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26344. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26345. var ssrc = simulcastSsrcs[i];
  26346. order.push(ssrc);
  26347. var parts = sources[ssrc].msid.split(' ');
  26348. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26349. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26350. // Remove all the groups that this SSRC participates in.
  26351. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26352. if (relatedGroup.semantics === 'SIM') {
  26353. return;
  26354. }
  26355. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26356. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26357. return;
  26358. }
  26359. // Nuke all the related SSRCs.
  26360. relatedSsrcs.forEach(function (relatedSSRC) {
  26361. sources[relatedSSRC].msid = sources[ssrc].msid;
  26362. sources[relatedSSRC].cname = sources[ssrc].cname;
  26363. if (relatedSSRC !== ssrc) {
  26364. order.push(relatedSSRC);
  26365. }
  26366. });
  26367. // Schedule the related group for nuking.
  26368. })
  26369. }
  26370. mLine.ssrcs = writeSsrcs(sources, order);
  26371. mLine.ssrcGroups.splice(j, 1);
  26372. };
  26373. }
  26374. function squeezeRemoteSimulcast(mLine) {
  26375. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26376. return;
  26377. }
  26378. var sources = parseSsrcs(mLine);
  26379. // Find the SIM group and nuke it.
  26380. mLine.ssrcGroups.some(function (simulcastGroup) {
  26381. if (simulcastGroup.semantics !== 'SIM') {
  26382. return false;
  26383. }
  26384. // Schedule the SIM group for nuking.
  26385. simulcastGroup.nuke = true;
  26386. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26387. // Nuke all the higher layer SSRCs.
  26388. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26389. var ssrc = simulcastSsrcs[i];
  26390. delete sources[ssrc];
  26391. // Remove all the groups that this SSRC participates in.
  26392. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26393. if (relatedGroup.semantics === 'SIM') {
  26394. return;
  26395. }
  26396. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26397. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26398. return;
  26399. }
  26400. // Nuke all the related SSRCs.
  26401. relatedSsrcs.forEach(function (relatedSSRC) {
  26402. delete sources[relatedSSRC];
  26403. });
  26404. // Schedule the related group for nuking.
  26405. relatedGroup.nuke = true;
  26406. })
  26407. }
  26408. return true;
  26409. });
  26410. mLine.ssrcs = writeSsrcs(sources);
  26411. // Nuke all the scheduled groups.
  26412. var i = mLine.ssrcGroups.length;
  26413. while (i--) {
  26414. if (mLine.ssrcGroups[i].nuke) {
  26415. mLine.ssrcGroups.splice(i, 1);
  26416. }
  26417. }
  26418. }
  26419. function removeGoogConference(mLine) {
  26420. if (!mLine || !Array.isArray(mLine.invalid)) {
  26421. return;
  26422. }
  26423. var i = mLine.invalid.length;
  26424. while (i--) {
  26425. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26426. mLine.invalid.splice(i, 1);
  26427. }
  26428. }
  26429. }
  26430. function assertGoogConference(mLine) {
  26431. if (!mLine) {
  26432. return;
  26433. }
  26434. if (!Array.isArray(mLine.invalid)) {
  26435. mLine.invalid = [];
  26436. }
  26437. if (!mLine.invalid.some(
  26438. function (i) { return i.value === 'x-google-flag:conference' })) {
  26439. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26440. }
  26441. }
  26442. //endregion
  26443. //region "Private" functions
  26444. /**
  26445. *
  26446. * @param mLine
  26447. * @private
  26448. */
  26449. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26450. if (!mLine || mLine.type !== 'video') {
  26451. return;
  26452. }
  26453. var sources = parseSsrcs(mLine);
  26454. if (Object.keys(sources).length === 0) {
  26455. // no sources, disable simulcast.
  26456. if (this.layers.length !== 0) {
  26457. this.layers = [];
  26458. }
  26459. return;
  26460. }
  26461. // find the base layer (we'll reuse its msid and cname).
  26462. var baseLayerSSRC = Object.keys(sources)[0];
  26463. var baseLayer = sources[baseLayerSSRC];
  26464. // todo(gp) handle screen sharing.
  26465. // check if base CNAME has changed and reinitialise layers.
  26466. if (this.layers.length > 0
  26467. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26468. this.layers = [];
  26469. }
  26470. // (re)initialise layers
  26471. if (this.layers.length < 1) {
  26472. // first push the base layer.
  26473. this.layers.push({
  26474. ssrc: baseLayerSSRC,
  26475. msid: baseLayer.msid,
  26476. cname: baseLayer.cname
  26477. });
  26478. var rtx = false; // RFC 4588
  26479. if (Array.isArray(mLine.rtp)) {
  26480. rtx = mLine.rtp.some(
  26481. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26482. }
  26483. if (rtx) {
  26484. this.layers[0].rtx = generateSSRC();
  26485. }
  26486. // now push additional layers.
  26487. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26488. var layer = { ssrc: generateSSRC() };
  26489. if (rtx) {
  26490. layer.rtx = generateSSRC();
  26491. }
  26492. this.layers.push(layer);
  26493. }
  26494. }
  26495. };
  26496. /**
  26497. *
  26498. * @param mLine
  26499. * @private
  26500. */
  26501. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26502. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26503. var sources = {};
  26504. var msid = this.layers[0].msid;
  26505. var cname = this.layers[0].cname;
  26506. var simulcastSsrcs = [];
  26507. var ssrcGroups = [];
  26508. for (var i = 0; i < this.layers.length; i++) {
  26509. var layer = this.layers[i];
  26510. sources[layer.ssrc] = { msid: msid, cname: cname };
  26511. simulcastSsrcs.push(layer.ssrc);
  26512. if (layer.rtx) {
  26513. sources[layer.rtx] = {
  26514. msid: msid,
  26515. cname: cname
  26516. }
  26517. ssrcGroups.push({
  26518. semantics: 'FID',
  26519. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26520. });
  26521. }
  26522. }
  26523. ssrcGroups.push({
  26524. semantics: 'SIM',
  26525. ssrcs: simulcastSsrcs.join(' ')
  26526. });
  26527. mLine.ssrcGroups = ssrcGroups;
  26528. mLine.ssrcs = writeSsrcs(sources);
  26529. }
  26530. }
  26531. //endregion
  26532. //region "Public" functions
  26533. Simulcast.prototype.isSupported = function () {
  26534. return window.chrome;
  26535. // TODO this needs improvements. For example I doubt that Chrome in Android
  26536. // has simulcast support. Also, only recent versions of Chromium have native
  26537. // simulcast support.
  26538. }
  26539. /**
  26540. *
  26541. * @param desc
  26542. * @returns {RTCSessionDescription}
  26543. */
  26544. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26545. if (!validateDescription(desc)) {
  26546. return desc;
  26547. }
  26548. var session = transform.parse(desc.sdp);
  26549. var self = this;
  26550. processVideo(session, function (mLine) {
  26551. // Handle simulcast reception.
  26552. if (self.options.explodeRemoteSimulcast) {
  26553. explodeRemoteSimulcast(mLine);
  26554. } else {
  26555. squeezeRemoteSimulcast(mLine);
  26556. }
  26557. // If native simulcast is enabled, we must append the x-goog-conference
  26558. // attribute to the SDP.
  26559. if (self.layers.length < 1) {
  26560. removeGoogConference(mLine);
  26561. } else {
  26562. assertGoogConference(mLine);
  26563. }
  26564. });
  26565. return new RTCSessionDescription({
  26566. type: desc.type,
  26567. sdp: transform.write(session)
  26568. });
  26569. };
  26570. /**
  26571. *
  26572. * @param desc
  26573. * @returns {RTCSessionDescription}
  26574. */
  26575. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26576. if (!validateDescription(desc) || !this.isSupported()) {
  26577. return desc;
  26578. }
  26579. var session = transform.parse(desc.sdp);
  26580. var self = this;
  26581. processVideo(session, function (mLine) {
  26582. // Initialize native simulcast layers, if not already done.
  26583. self._maybeInitializeLayers(mLine);
  26584. // Update the SDP with the simulcast layers.
  26585. self._restoreSimulcastView(mLine);
  26586. });
  26587. return new RTCSessionDescription({
  26588. type: desc.type,
  26589. sdp: transform.write(session)
  26590. });
  26591. };
  26592. //endregion
  26593. module.exports = Simulcast;
  26594. },{"./transform-utils":98,"sdp-transform":100}],98:[function(require,module,exports){
  26595. exports.writeSsrcs = function(sources, order) {
  26596. var ssrcs = [];
  26597. // expand sources to ssrcs
  26598. if (typeof sources !== 'undefined' &&
  26599. Object.keys(sources).length !== 0) {
  26600. if (Array.isArray(order)) {
  26601. for (var i = 0; i < order.length; i++) {
  26602. var ssrc = order[i];
  26603. var source = sources[ssrc];
  26604. Object.keys(source).forEach(function (attribute) {
  26605. ssrcs.push({
  26606. id: ssrc,
  26607. attribute: attribute,
  26608. value: source[attribute]
  26609. });
  26610. });
  26611. }
  26612. } else {
  26613. Object.keys(sources).forEach(function (ssrc) {
  26614. var source = sources[ssrc];
  26615. Object.keys(source).forEach(function (attribute) {
  26616. ssrcs.push({
  26617. id: ssrc,
  26618. attribute: attribute,
  26619. value: source[attribute]
  26620. });
  26621. });
  26622. });
  26623. }
  26624. }
  26625. return ssrcs;
  26626. };
  26627. exports.parseSsrcs = function (mLine) {
  26628. var sources = {};
  26629. // group sources attributes by ssrc.
  26630. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26631. mLine.ssrcs.forEach(function (ssrc) {
  26632. if (!sources[ssrc.id])
  26633. sources[ssrc.id] = {};
  26634. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26635. });
  26636. }
  26637. return sources;
  26638. };
  26639. },{}],99:[function(require,module,exports){
  26640. arguments[4][93][0].apply(exports,arguments)
  26641. },{"dup":93}],100:[function(require,module,exports){
  26642. arguments[4][94][0].apply(exports,arguments)
  26643. },{"./parser":101,"./writer":102,"dup":94}],101:[function(require,module,exports){
  26644. arguments[4][95][0].apply(exports,arguments)
  26645. },{"./grammar":99,"dup":95}],102:[function(require,module,exports){
  26646. arguments[4][96][0].apply(exports,arguments)
  26647. },{"./grammar":99,"dup":96}],103:[function(require,module,exports){
  26648. var MediaStreamType = {
  26649. VIDEO_TYPE: "Video",
  26650. AUDIO_TYPE: "Audio"
  26651. };
  26652. module.exports = MediaStreamType;
  26653. },{}],104:[function(require,module,exports){
  26654. var RTCEvents = {
  26655. RTC_READY: "rtc.ready",
  26656. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  26657. LASTN_CHANGED: "rtc.lastn_changed",
  26658. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26659. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26660. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26661. AUDIO_MUTE: "rtc.audio_mute",
  26662. VIDEO_MUTE: "rtc.video_mute"
  26663. };
  26664. module.exports = RTCEvents;
  26665. },{}],105:[function(require,module,exports){
  26666. var Resolutions = {
  26667. "1080": {
  26668. width: 1920,
  26669. height: 1080,
  26670. order: 7
  26671. },
  26672. "fullhd": {
  26673. width: 1920,
  26674. height: 1080,
  26675. order: 7
  26676. },
  26677. "720": {
  26678. width: 1280,
  26679. height: 720,
  26680. order: 6
  26681. },
  26682. "hd": {
  26683. width: 1280,
  26684. height: 720,
  26685. order: 6
  26686. },
  26687. "960": {
  26688. width: 960,
  26689. height: 720,
  26690. order: 5
  26691. },
  26692. "640": {
  26693. width: 640,
  26694. height: 480,
  26695. order: 4
  26696. },
  26697. "vga": {
  26698. width: 640,
  26699. height: 480,
  26700. order: 4
  26701. },
  26702. "360": {
  26703. width: 640,
  26704. height: 360,
  26705. order: 3
  26706. },
  26707. "320": {
  26708. width: 320,
  26709. height: 240,
  26710. order: 2
  26711. },
  26712. "180": {
  26713. width: 320,
  26714. height: 180,
  26715. order: 1
  26716. }
  26717. };
  26718. module.exports = Resolutions;
  26719. },{}],106:[function(require,module,exports){
  26720. var StreamEventTypes = {
  26721. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26722. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26723. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26724. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26725. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  26726. };
  26727. module.exports = StreamEventTypes;
  26728. },{}],107:[function(require,module,exports){
  26729. var UIEvents = {
  26730. NICKNAME_CHANGED: "UI.nickname_changed",
  26731. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26732. PINNED_ENDPOINT: "UI.pinned_endpoint",
  26733. LARGEVIDEO_INIT: "UI.largevideo_init"
  26734. };
  26735. module.exports = UIEvents;
  26736. },{}],108:[function(require,module,exports){
  26737. var AuthenticationEvents = {
  26738. /**
  26739. * Event callback arguments:
  26740. * function(authenticationEnabled, userIdentity)
  26741. * authenticationEnabled - indicates whether authentication has been enabled
  26742. * in this session
  26743. * userIdentity - if user has been logged in then it contains user name. If
  26744. * contains 'null' or 'undefined' then user is not logged in.
  26745. */
  26746. IDENTITY_UPDATED: "authentication.identity_updated"
  26747. };
  26748. module.exports = AuthenticationEvents;
  26749. },{}],109:[function(require,module,exports){
  26750. var CQEvents = {
  26751. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26752. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26753. STOP: "cq.stop"
  26754. };
  26755. module.exports = CQEvents;
  26756. },{}],110:[function(require,module,exports){
  26757. var DesktopSharingEventTypes = {
  26758. INIT: "ds.init",
  26759. SWITCHING_DONE: "ds.switching_done",
  26760. NEW_STREAM_CREATED: "ds.new_stream_created"
  26761. };
  26762. module.exports = DesktopSharingEventTypes;
  26763. },{}],111:[function(require,module,exports){
  26764. var Events = {
  26765. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26766. };
  26767. module.exports = Events;
  26768. },{}],112:[function(require,module,exports){
  26769. module.exports = {
  26770. getLanguages : function () {
  26771. var languages = [];
  26772. for(var lang in this)
  26773. {
  26774. if(typeof this[lang] === "string")
  26775. languages.push(this[lang]);
  26776. }
  26777. return languages;
  26778. },
  26779. EN: "en",
  26780. BG: "bg",
  26781. DE: "de",
  26782. TR: "tr",
  26783. FR: "fr"
  26784. }
  26785. },{}],113:[function(require,module,exports){
  26786. var XMPPEvents = {
  26787. CONNECTION_FAILED: "xmpp.connection.failed",
  26788. // Indicates an interrupted connection event.
  26789. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  26790. // Indicates a restored connection event.
  26791. CONNECTION_RESTORED: "xmpp.connection.restored",
  26792. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26793. CALL_INCOMING: "xmpp.callincoming.jingle",
  26794. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26795. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26796. KICKED: "xmpp.kicked",
  26797. BRIDGE_DOWN: "xmpp.bridge_down",
  26798. USER_ID_CHANGED: "xmpp.user_id_changed",
  26799. // We joined the MUC
  26800. MUC_JOINED: "xmpp.muc_joined",
  26801. // A member joined the MUC
  26802. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26803. // A member left the MUC
  26804. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26805. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26806. MUC_DESTROYED: "xmpp.muc_destroyed",
  26807. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26808. REMOTE_STATS: "xmpp.remote_stats",
  26809. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26810. PRESENCE_STATUS: "xmpp.presence_status",
  26811. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26812. SUBJECT_CHANGED: "xmpp.subject_changed",
  26813. MESSAGE_RECEIVED: "xmpp.message_received",
  26814. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26815. PASSWORD_REQUIRED: "xmpp.password_required",
  26816. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26817. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26818. ETHERPAD: "xmpp.etherpad",
  26819. DEVICE_AVAILABLE: "xmpp.device_available",
  26820. VIDEO_TYPE: "xmpp.video_type",
  26821. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  26822. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  26823. AUDIO_MUTED: "xmpp.audio_muted",
  26824. VIDEO_MUTED: "xmpp.video_muted",
  26825. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  26826. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  26827. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  26828. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  26829. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  26830. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  26831. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  26832. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  26833. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  26834. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  26835. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  26836. // xmpp is connected and obtained user media
  26837. READY_TO_JOIN: 'xmpp.ready_to_join'
  26838. };
  26839. module.exports = XMPPEvents;
  26840. },{}],114:[function(require,module,exports){
  26841. // Copyright Joyent, Inc. and other Node contributors.
  26842. //
  26843. // Permission is hereby granted, free of charge, to any person obtaining a
  26844. // copy of this software and associated documentation files (the
  26845. // "Software"), to deal in the Software without restriction, including
  26846. // without limitation the rights to use, copy, modify, merge, publish,
  26847. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26848. // persons to whom the Software is furnished to do so, subject to the
  26849. // following conditions:
  26850. //
  26851. // The above copyright notice and this permission notice shall be included
  26852. // in all copies or substantial portions of the Software.
  26853. //
  26854. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26855. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26856. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26857. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26858. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26859. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26860. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26861. function EventEmitter() {
  26862. this._events = this._events || {};
  26863. this._maxListeners = this._maxListeners || undefined;
  26864. }
  26865. module.exports = EventEmitter;
  26866. // Backwards-compat with node 0.10.x
  26867. EventEmitter.EventEmitter = EventEmitter;
  26868. EventEmitter.prototype._events = undefined;
  26869. EventEmitter.prototype._maxListeners = undefined;
  26870. // By default EventEmitters will print a warning if more than 10 listeners are
  26871. // added to it. This is a useful default which helps finding memory leaks.
  26872. EventEmitter.defaultMaxListeners = 10;
  26873. // Obviously not all Emitters should be limited to 10. This function allows
  26874. // that to be increased. Set to zero for unlimited.
  26875. EventEmitter.prototype.setMaxListeners = function(n) {
  26876. if (!isNumber(n) || n < 0 || isNaN(n))
  26877. throw TypeError('n must be a positive number');
  26878. this._maxListeners = n;
  26879. return this;
  26880. };
  26881. EventEmitter.prototype.emit = function(type) {
  26882. var er, handler, len, args, i, listeners;
  26883. if (!this._events)
  26884. this._events = {};
  26885. // If there is no 'error' event listener then throw.
  26886. if (type === 'error') {
  26887. if (!this._events.error ||
  26888. (isObject(this._events.error) && !this._events.error.length)) {
  26889. er = arguments[1];
  26890. if (er instanceof Error) {
  26891. throw er; // Unhandled 'error' event
  26892. }
  26893. throw TypeError('Uncaught, unspecified "error" event.');
  26894. }
  26895. }
  26896. handler = this._events[type];
  26897. if (isUndefined(handler))
  26898. return false;
  26899. if (isFunction(handler)) {
  26900. switch (arguments.length) {
  26901. // fast cases
  26902. case 1:
  26903. handler.call(this);
  26904. break;
  26905. case 2:
  26906. handler.call(this, arguments[1]);
  26907. break;
  26908. case 3:
  26909. handler.call(this, arguments[1], arguments[2]);
  26910. break;
  26911. // slower
  26912. default:
  26913. len = arguments.length;
  26914. args = new Array(len - 1);
  26915. for (i = 1; i < len; i++)
  26916. args[i - 1] = arguments[i];
  26917. handler.apply(this, args);
  26918. }
  26919. } else if (isObject(handler)) {
  26920. len = arguments.length;
  26921. args = new Array(len - 1);
  26922. for (i = 1; i < len; i++)
  26923. args[i - 1] = arguments[i];
  26924. listeners = handler.slice();
  26925. len = listeners.length;
  26926. for (i = 0; i < len; i++)
  26927. listeners[i].apply(this, args);
  26928. }
  26929. return true;
  26930. };
  26931. EventEmitter.prototype.addListener = function(type, listener) {
  26932. var m;
  26933. if (!isFunction(listener))
  26934. throw TypeError('listener must be a function');
  26935. if (!this._events)
  26936. this._events = {};
  26937. // To avoid recursion in the case that type === "newListener"! Before
  26938. // adding it to the listeners, first emit "newListener".
  26939. if (this._events.newListener)
  26940. this.emit('newListener', type,
  26941. isFunction(listener.listener) ?
  26942. listener.listener : listener);
  26943. if (!this._events[type])
  26944. // Optimize the case of one listener. Don't need the extra array object.
  26945. this._events[type] = listener;
  26946. else if (isObject(this._events[type]))
  26947. // If we've already got an array, just append.
  26948. this._events[type].push(listener);
  26949. else
  26950. // Adding the second element, need to change to array.
  26951. this._events[type] = [this._events[type], listener];
  26952. // Check for listener leak
  26953. if (isObject(this._events[type]) && !this._events[type].warned) {
  26954. var m;
  26955. if (!isUndefined(this._maxListeners)) {
  26956. m = this._maxListeners;
  26957. } else {
  26958. m = EventEmitter.defaultMaxListeners;
  26959. }
  26960. if (m && m > 0 && this._events[type].length > m) {
  26961. this._events[type].warned = true;
  26962. console.error('(node) warning: possible EventEmitter memory ' +
  26963. 'leak detected. %d listeners added. ' +
  26964. 'Use emitter.setMaxListeners() to increase limit.',
  26965. this._events[type].length);
  26966. if (typeof console.trace === 'function') {
  26967. // not supported in IE 10
  26968. console.trace();
  26969. }
  26970. }
  26971. }
  26972. return this;
  26973. };
  26974. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  26975. EventEmitter.prototype.once = function(type, listener) {
  26976. if (!isFunction(listener))
  26977. throw TypeError('listener must be a function');
  26978. var fired = false;
  26979. function g() {
  26980. this.removeListener(type, g);
  26981. if (!fired) {
  26982. fired = true;
  26983. listener.apply(this, arguments);
  26984. }
  26985. }
  26986. g.listener = listener;
  26987. this.on(type, g);
  26988. return this;
  26989. };
  26990. // emits a 'removeListener' event iff the listener was removed
  26991. EventEmitter.prototype.removeListener = function(type, listener) {
  26992. var list, position, length, i;
  26993. if (!isFunction(listener))
  26994. throw TypeError('listener must be a function');
  26995. if (!this._events || !this._events[type])
  26996. return this;
  26997. list = this._events[type];
  26998. length = list.length;
  26999. position = -1;
  27000. if (list === listener ||
  27001. (isFunction(list.listener) && list.listener === listener)) {
  27002. delete this._events[type];
  27003. if (this._events.removeListener)
  27004. this.emit('removeListener', type, listener);
  27005. } else if (isObject(list)) {
  27006. for (i = length; i-- > 0;) {
  27007. if (list[i] === listener ||
  27008. (list[i].listener && list[i].listener === listener)) {
  27009. position = i;
  27010. break;
  27011. }
  27012. }
  27013. if (position < 0)
  27014. return this;
  27015. if (list.length === 1) {
  27016. list.length = 0;
  27017. delete this._events[type];
  27018. } else {
  27019. list.splice(position, 1);
  27020. }
  27021. if (this._events.removeListener)
  27022. this.emit('removeListener', type, listener);
  27023. }
  27024. return this;
  27025. };
  27026. EventEmitter.prototype.removeAllListeners = function(type) {
  27027. var key, listeners;
  27028. if (!this._events)
  27029. return this;
  27030. // not listening for removeListener, no need to emit
  27031. if (!this._events.removeListener) {
  27032. if (arguments.length === 0)
  27033. this._events = {};
  27034. else if (this._events[type])
  27035. delete this._events[type];
  27036. return this;
  27037. }
  27038. // emit removeListener for all listeners on all events
  27039. if (arguments.length === 0) {
  27040. for (key in this._events) {
  27041. if (key === 'removeListener') continue;
  27042. this.removeAllListeners(key);
  27043. }
  27044. this.removeAllListeners('removeListener');
  27045. this._events = {};
  27046. return this;
  27047. }
  27048. listeners = this._events[type];
  27049. if (isFunction(listeners)) {
  27050. this.removeListener(type, listeners);
  27051. } else {
  27052. // LIFO order
  27053. while (listeners.length)
  27054. this.removeListener(type, listeners[listeners.length - 1]);
  27055. }
  27056. delete this._events[type];
  27057. return this;
  27058. };
  27059. EventEmitter.prototype.listeners = function(type) {
  27060. var ret;
  27061. if (!this._events || !this._events[type])
  27062. ret = [];
  27063. else if (isFunction(this._events[type]))
  27064. ret = [this._events[type]];
  27065. else
  27066. ret = this._events[type].slice();
  27067. return ret;
  27068. };
  27069. EventEmitter.listenerCount = function(emitter, type) {
  27070. var ret;
  27071. if (!emitter._events || !emitter._events[type])
  27072. ret = 0;
  27073. else if (isFunction(emitter._events[type]))
  27074. ret = 1;
  27075. else
  27076. ret = emitter._events[type].length;
  27077. return ret;
  27078. };
  27079. function isFunction(arg) {
  27080. return typeof arg === 'function';
  27081. }
  27082. function isNumber(arg) {
  27083. return typeof arg === 'number';
  27084. }
  27085. function isObject(arg) {
  27086. return typeof arg === 'object' && arg !== null;
  27087. }
  27088. function isUndefined(arg) {
  27089. return arg === void 0;
  27090. }
  27091. },{}],115:[function(require,module,exports){
  27092. // shim for using process in browser
  27093. var process = module.exports = {};
  27094. var queue = [];
  27095. var draining = false;
  27096. function drainQueue() {
  27097. if (draining) {
  27098. return;
  27099. }
  27100. draining = true;
  27101. var currentQueue;
  27102. var len = queue.length;
  27103. while(len) {
  27104. currentQueue = queue;
  27105. queue = [];
  27106. var i = -1;
  27107. while (++i < len) {
  27108. currentQueue[i]();
  27109. }
  27110. len = queue.length;
  27111. }
  27112. draining = false;
  27113. }
  27114. process.nextTick = function (fun) {
  27115. queue.push(fun);
  27116. if (!draining) {
  27117. setTimeout(drainQueue, 0);
  27118. }
  27119. };
  27120. process.title = 'browser';
  27121. process.browser = true;
  27122. process.env = {};
  27123. process.argv = [];
  27124. process.version = ''; // empty string to avoid regexp issues
  27125. function noop() {}
  27126. process.on = noop;
  27127. process.addListener = noop;
  27128. process.once = noop;
  27129. process.off = noop;
  27130. process.removeListener = noop;
  27131. process.removeAllListeners = noop;
  27132. process.emit = noop;
  27133. process.binding = function (name) {
  27134. throw new Error('process.binding is not supported');
  27135. };
  27136. // TODO(shtylman)
  27137. process.cwd = function () { return '/' };
  27138. process.chdir = function (dir) {
  27139. throw new Error('process.chdir is not supported');
  27140. };
  27141. process.umask = function() { return 0; };
  27142. },{}]},{},[1])(1)
  27143. });