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

app.bundle.js 992KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  13. this.xmpp = require("./modules/xmpp/xmpp");
  14. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  15. this.translation = require("./modules/translation/translation");
  16. this.settings = require("./modules/settings/Settings");
  17. this.DTMF = require("./modules/DTMF/DTMF");
  18. this.members = require("./modules/members/MemberList");
  19. }
  20. };
  21. function init() {
  22. APP.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":66}],2:[function(require,module,exports){
  45. /**
  46. * Implements API class that communicates with external api class
  47. * and provides interface to access Jitsi Meet features by external
  48. * applications that embed Jitsi Meet
  49. */
  50. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  51. /**
  52. * List of the available commands.
  53. * @type {{
  54. * displayName: inputDisplayNameHandler,
  55. * muteAudio: toggleAudio,
  56. * muteVideo: toggleVideo,
  57. * filmStrip: toggleFilmStrip
  58. * }}
  59. */
  60. var commands = {};
  61. function initCommands() {
  62. commands =
  63. {
  64. displayName: APP.UI.inputDisplayNameHandler,
  65. muteAudio: APP.UI.toggleAudio,
  66. muteVideo: APP.UI.toggleVideo,
  67. toggleFilmStrip: APP.UI.toggleFilmStrip,
  68. toggleChat: APP.UI.toggleChat,
  69. toggleContactList: APP.UI.toggleContactList
  70. };
  71. }
  72. /**
  73. * Maps the supported events and their status
  74. * (true it the event is enabled and false if it is disabled)
  75. * @type {{
  76. * incomingMessage: boolean,
  77. * outgoingMessage: boolean,
  78. * displayNameChange: boolean,
  79. * participantJoined: boolean,
  80. * participantLeft: boolean
  81. * }}
  82. */
  83. var events =
  84. {
  85. incomingMessage: false,
  86. outgoingMessage:false,
  87. displayNameChange: false,
  88. participantJoined: false,
  89. participantLeft: false
  90. };
  91. var displayName = {};
  92. /**
  93. * Processes commands from external applicaiton.
  94. * @param message the object with the command
  95. */
  96. function processCommand(message)
  97. {
  98. if(message.action != "execute")
  99. {
  100. console.error("Unknown action of the message");
  101. return;
  102. }
  103. for(var key in message)
  104. {
  105. if(commands[key])
  106. commands[key].apply(null, message[key]);
  107. }
  108. }
  109. /**
  110. * Processes events objects from external applications
  111. * @param event the event
  112. */
  113. function processEvent(event) {
  114. if(!event.action)
  115. {
  116. console.error("Event with no action is received.");
  117. return;
  118. }
  119. var i = 0;
  120. switch(event.action)
  121. {
  122. case "add":
  123. for(; i < event.events.length; i++)
  124. {
  125. events[event.events[i]] = true;
  126. }
  127. break;
  128. case "remove":
  129. for(; i < event.events.length; i++)
  130. {
  131. events[event.events[i]] = false;
  132. }
  133. break;
  134. default:
  135. console.error("Unknown action for event.");
  136. }
  137. }
  138. /**
  139. * Sends message to the external application.
  140. * @param object
  141. */
  142. function sendMessage(object) {
  143. window.parent.postMessage(JSON.stringify(object), "*");
  144. }
  145. /**
  146. * Processes a message event from the external application
  147. * @param event the message event
  148. */
  149. function processMessage(event)
  150. {
  151. var message;
  152. try {
  153. message = JSON.parse(event.data);
  154. } catch (e) {}
  155. if(!message.type)
  156. return;
  157. switch (message.type)
  158. {
  159. case "command":
  160. processCommand(message);
  161. break;
  162. case "event":
  163. processEvent(message);
  164. break;
  165. default:
  166. console.error("Unknown type of the message");
  167. return;
  168. }
  169. }
  170. function setupListeners() {
  171. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  172. API.triggerEvent("participantJoined", {jid: from});
  173. });
  174. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  175. if (from != myjid)
  176. API.triggerEvent("incomingMessage",
  177. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  178. });
  179. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  180. API.triggerEvent("participantLeft", {jid: jid});
  181. });
  182. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  183. name = displayName[jid];
  184. if(!name || name != newDisplayName) {
  185. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  186. displayName[jid] = newDisplayName;
  187. }
  188. });
  189. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  190. APP.API.triggerEvent("outgoingMessage", {"message": body});
  191. });
  192. }
  193. var API = {
  194. /**
  195. * Check whether the API should be enabled or not.
  196. * @returns {boolean}
  197. */
  198. isEnabled: function () {
  199. var hash = location.hash;
  200. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  201. return true;
  202. return false;
  203. },
  204. /**
  205. * Initializes the APIConnector. Setups message event listeners that will
  206. * receive information from external applications that embed Jitsi Meet.
  207. * It also sends a message to the external application that APIConnector
  208. * is initialized.
  209. */
  210. init: function () {
  211. initCommands();
  212. if (window.addEventListener)
  213. {
  214. window.addEventListener('message',
  215. processMessage, false);
  216. }
  217. else
  218. {
  219. window.attachEvent('onmessage', processMessage);
  220. }
  221. sendMessage({type: "system", loaded: true});
  222. setupListeners();
  223. },
  224. /**
  225. * Checks whether the event is enabled ot not.
  226. * @param name the name of the event.
  227. * @returns {*}
  228. */
  229. isEventEnabled: function (name) {
  230. return events[name];
  231. },
  232. /**
  233. * Sends event object to the external application that has been subscribed
  234. * for that event.
  235. * @param name the name event
  236. * @param object data associated with the event
  237. */
  238. triggerEvent: function (name, object) {
  239. if(this.isEnabled() && this.isEventEnabled(name))
  240. sendMessage({
  241. type: "event", action: "result", event: name, result: object});
  242. },
  243. /**
  244. * Removes the listeners.
  245. */
  246. dispose: function () {
  247. if(window.removeEventListener)
  248. {
  249. window.removeEventListener("message",
  250. processMessage, false);
  251. }
  252. else
  253. {
  254. window.detachEvent('onmessage', processMessage);
  255. }
  256. }
  257. };
  258. module.exports = API;
  259. },{"../../service/xmpp/XMPPEvents":108}],3:[function(require,module,exports){
  260. /* global APP */
  261. /**
  262. * A module for sending DTMF tones.
  263. */
  264. var DTMFSender;
  265. var initDtmfSender = function() {
  266. // TODO: This needs to reset this if the peerconnection changes
  267. // (e.g. the call is re-made)
  268. if (DTMFSender)
  269. return;
  270. var localAudio = APP.RTC.localAudio;
  271. if (localAudio && localAudio.getTracks().length > 0)
  272. {
  273. var peerconnection
  274. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  275. if (peerconnection) {
  276. DTMFSender =
  277. peerconnection.peerconnection
  278. .createDTMFSender(localAudio.getTracks()[0]);
  279. console.log("Initialized DTMFSender");
  280. }
  281. else {
  282. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  283. }
  284. }
  285. else {
  286. console.log("Failed to initialize DTMFSender: no audio track.");
  287. }
  288. };
  289. var DTMF = {
  290. sendTones: function (tones, duration, pause) {
  291. if (!DTMFSender)
  292. initDtmfSender();
  293. if (DTMFSender){
  294. DTMFSender.insertDTMF(tones,
  295. (duration || 200),
  296. (pause || 200));
  297. }
  298. }
  299. };
  300. module.exports = DTMF;
  301. },{}],4:[function(require,module,exports){
  302. /* global Strophe, focusedVideoSrc*/
  303. // cache datachannels to avoid garbage collection
  304. // https://code.google.com/p/chromium/issues/detail?id=405545
  305. var RTCEvents = require("../../service/RTC/RTCEvents");
  306. var _dataChannels = [];
  307. var eventEmitter = null;
  308. var DataChannels =
  309. {
  310. /**
  311. * Callback triggered by PeerConnection when new data channel is opened
  312. * on the bridge.
  313. * @param event the event info object.
  314. */
  315. onDataChannel: function (event)
  316. {
  317. var dataChannel = event.channel;
  318. dataChannel.onopen = function () {
  319. console.info("Data channel opened by the Videobridge!", dataChannel);
  320. // Code sample for sending string and/or binary data
  321. // Sends String message to the bridge
  322. //dataChannel.send("Hello bridge!");
  323. // Sends 12 bytes binary message to the bridge
  324. //dataChannel.send(new ArrayBuffer(12));
  325. // when the data channel becomes available, tell the bridge about video
  326. // selections so that it can do adaptive simulcast,
  327. // we want the notification to trigger even if userJid is undefined,
  328. // or null.
  329. var userJid = APP.UI.getLargeVideoJid();
  330. // we want the notification to trigger even if userJid is undefined,
  331. // or null.
  332. onSelectedEndpointChanged(userJid);
  333. };
  334. dataChannel.onerror = function (error) {
  335. console.error("Data Channel Error:", error, dataChannel);
  336. };
  337. dataChannel.onmessage = function (event) {
  338. var data = event.data;
  339. // JSON
  340. var obj;
  341. try {
  342. obj = JSON.parse(data);
  343. }
  344. catch (e) {
  345. console.error(
  346. "Failed to parse data channel message as JSON: ",
  347. data,
  348. dataChannel);
  349. }
  350. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  351. var colibriClass = obj.colibriClass;
  352. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  353. // Endpoint ID from the Videobridge.
  354. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  355. console.info(
  356. "Data channel new dominant speaker event: ",
  357. dominantSpeakerEndpoint);
  358. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  359. }
  360. else if ("InLastNChangeEvent" === colibriClass)
  361. {
  362. var oldValue = obj.oldValue;
  363. var newValue = obj.newValue;
  364. // Make sure that oldValue and newValue are of type boolean.
  365. var type;
  366. if ((type = typeof oldValue) !== 'boolean') {
  367. if (type === 'string') {
  368. oldValue = (oldValue == "true");
  369. } else {
  370. oldValue = new Boolean(oldValue).valueOf();
  371. }
  372. }
  373. if ((type = typeof newValue) !== 'boolean') {
  374. if (type === 'string') {
  375. newValue = (newValue == "true");
  376. } else {
  377. newValue = new Boolean(newValue).valueOf();
  378. }
  379. }
  380. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  381. }
  382. else if ("LastNEndpointsChangeEvent" === colibriClass)
  383. {
  384. // The new/latest list of last-n endpoint IDs.
  385. var lastNEndpoints = obj.lastNEndpoints;
  386. // The list of endpoint IDs which are entering the list of
  387. // last-n at this time i.e. were not in the old list of last-n
  388. // endpoint IDs.
  389. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  390. var stream = obj.stream;
  391. console.log(
  392. "Data channel new last-n event: ",
  393. lastNEndpoints, endpointsEnteringLastN, obj);
  394. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  395. lastNEndpoints, endpointsEnteringLastN, obj);
  396. }
  397. else
  398. {
  399. console.debug("Data channel JSON-formatted message: ", obj);
  400. }
  401. }
  402. };
  403. dataChannel.onclose = function ()
  404. {
  405. console.info("The Data Channel closed", dataChannel);
  406. var idx = _dataChannels.indexOf(dataChannel);
  407. if (idx > -1)
  408. _dataChannels = _dataChannels.splice(idx, 1);
  409. };
  410. _dataChannels.push(dataChannel);
  411. },
  412. /**
  413. * Binds "ondatachannel" event listener to given PeerConnection instance.
  414. * @param peerConnection WebRTC peer connection instance.
  415. */
  416. init: function (peerConnection, emitter) {
  417. if(!config.openSctp)
  418. return;
  419. peerConnection.ondatachannel = this.onDataChannel;
  420. eventEmitter = emitter;
  421. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  422. // Although it's not a requirement to open separate channels from both bridge
  423. // and peer as single channel can be used for sending and receiving data.
  424. // So either channel opened by the bridge or the one opened here is enough
  425. // for communication with the bridge.
  426. /*var dataChannelOptions =
  427. {
  428. reliable: true
  429. };
  430. var dataChannel
  431. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  432. // Can be used only when is in open state
  433. dataChannel.onopen = function ()
  434. {
  435. dataChannel.send("My channel !!!");
  436. };
  437. dataChannel.onmessage = function (event)
  438. {
  439. var msgData = event.data;
  440. console.info("Got My Data Channel Message:", msgData, dataChannel);
  441. };*/
  442. },
  443. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  444. handlePinnedEndpointEvent: onPinnedEndpointChanged
  445. };
  446. function onSelectedEndpointChanged(userResource)
  447. {
  448. console.log('selected endpoint changed: ', userResource);
  449. if (_dataChannels && _dataChannels.length != 0)
  450. {
  451. _dataChannels.some(function (dataChannel) {
  452. if (dataChannel.readyState == 'open')
  453. {
  454. console.log('sending selected endpoint changed '
  455. + 'notification to the bridge: ', userResource);
  456. dataChannel.send(JSON.stringify({
  457. 'colibriClass': 'SelectedEndpointChangedEvent',
  458. 'selectedEndpoint':
  459. (!userResource || userResource === null)?
  460. null : userResource
  461. }));
  462. return true;
  463. }
  464. });
  465. }
  466. }
  467. function onPinnedEndpointChanged(userResource)
  468. {
  469. console.log('pinned endpoint changed: ', userResource);
  470. if (_dataChannels && _dataChannels.length != 0)
  471. {
  472. _dataChannels.some(function (dataChannel) {
  473. if (dataChannel.readyState == 'open')
  474. {
  475. dataChannel.send(JSON.stringify({
  476. 'colibriClass': 'PinnedEndpointChangedEvent',
  477. 'pinnedEndpoint':
  478. (!userResource || userResource == null)?
  479. null : userResource
  480. }));
  481. return true;
  482. }
  483. });
  484. }
  485. }
  486. module.exports = DataChannels;
  487. },{"../../service/RTC/RTCEvents":99}],5:[function(require,module,exports){
  488. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  489. var RTCEvents = require("../../service/RTC/RTCEvents");
  490. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  491. {
  492. this.stream = stream;
  493. this.eventEmitter = eventEmitter;
  494. this.type = type;
  495. this.videoType = videoType;
  496. this.isGUMStream = true;
  497. if(isGUMStream === false)
  498. this.isGUMStream = isGUMStream;
  499. var self = this;
  500. if(type == "audio")
  501. {
  502. this.getTracks = function () {
  503. return self.stream.getAudioTracks();
  504. };
  505. }
  506. else
  507. {
  508. this.getTracks = function () {
  509. return self.stream.getVideoTracks();
  510. };
  511. }
  512. this.stream.onended = function()
  513. {
  514. self.streamEnded();
  515. };
  516. }
  517. LocalStream.prototype.streamEnded = function () {
  518. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  519. }
  520. LocalStream.prototype.getOriginalStream = function()
  521. {
  522. return this.stream;
  523. }
  524. LocalStream.prototype.isAudioStream = function () {
  525. return this.type === "audio";
  526. };
  527. LocalStream.prototype.setMute = function(mute)
  528. {
  529. if((window.location.protocol != "https:" && this.isGUMStream) ||
  530. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  531. {
  532. var tracks = this.getTracks();
  533. for (var idx = 0; idx < tracks.length; idx++) {
  534. tracks[idx].enabled = mute;
  535. }
  536. this.eventEmitter.emit(
  537. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  538. !mute);
  539. }
  540. else
  541. {
  542. if(mute === false) {
  543. APP.xmpp.removeStream(this.stream);
  544. this.stream.stop();
  545. this.eventEmitter.emit(
  546. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  547. true);
  548. }
  549. else
  550. {
  551. var self = this;
  552. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  553. (this.isAudioStream() ? ["audio"] : ["video"]),
  554. function (stream) {
  555. if(self.isAudioStream())
  556. {
  557. APP.RTC.changeLocalAudio(stream,
  558. function () {
  559. self.eventEmitter.emit(
  560. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  561. true);
  562. });
  563. }
  564. else
  565. {
  566. APP.RTC.changeLocalVideo(stream, false,
  567. function () {
  568. self.eventEmitter.emit(
  569. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  570. true);
  571. });
  572. }
  573. });
  574. }
  575. }
  576. };
  577. LocalStream.prototype.isMuted = function () {
  578. var tracks = [];
  579. if(this.type == "audio")
  580. {
  581. tracks = this.stream.getAudioTracks();
  582. }
  583. else
  584. {
  585. if(this.stream.ended)
  586. return true;
  587. tracks = this.stream.getVideoTracks();
  588. }
  589. for (var idx = 0; idx < tracks.length; idx++) {
  590. if(tracks[idx].enabled)
  591. return false;
  592. }
  593. return true;
  594. }
  595. LocalStream.prototype.getId = function () {
  596. return this.stream.getTracks()[0].id;
  597. }
  598. module.exports = LocalStream;
  599. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes.js":101}],6:[function(require,module,exports){
  600. ////These lines should be uncommented when require works in app.js
  601. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  602. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  603. /**
  604. * Creates a MediaStream object for the given data, session id and ssrc.
  605. * It is a wrapper class for the MediaStream.
  606. *
  607. * @param data the data object from which we obtain the stream,
  608. * the peerjid, etc.
  609. * @param sid the session id
  610. * @param ssrc the ssrc corresponding to this MediaStream
  611. *
  612. * @constructor
  613. */
  614. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  615. // XXX(gp) to minimize headaches in the future, we should build our
  616. // abstractions around tracks and not streams. ORTC is track based API.
  617. // Mozilla expects m-lines to represent media tracks.
  618. //
  619. // Practically, what I'm saying is that we should have a MediaTrack class
  620. // and not a MediaStream class.
  621. //
  622. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  623. // a track might have an associated RTX and FEC sources.
  624. this.sid = sid;
  625. this.stream = data.stream;
  626. this.peerjid = data.peerjid;
  627. this.videoType = data.videoType;
  628. this.ssrc = ssrc;
  629. this.type = (this.stream.getVideoTracks().length > 0)?
  630. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  631. this.muted = false;
  632. this.eventEmitter = eventEmitter;
  633. }
  634. MediaStream.prototype.getOriginalStream = function()
  635. {
  636. return this.stream;
  637. };
  638. MediaStream.prototype.setMute = function (value)
  639. {
  640. this.stream.muted = value;
  641. this.muted = value;
  642. };
  643. module.exports = MediaStream;
  644. },{"../../service/RTC/MediaStreamTypes":98,"../../service/RTC/StreamEventTypes":101}],7:[function(require,module,exports){
  645. var EventEmitter = require("events");
  646. var RTCBrowserType = require("./RTCBrowserType");
  647. var RTCUtils = require("./RTCUtils.js");
  648. var LocalStream = require("./LocalStream.js");
  649. var DataChannels = require("./DataChannels");
  650. var MediaStream = require("./MediaStream.js");
  651. var DesktopSharingEventTypes
  652. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  653. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  654. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  655. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  656. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  657. var UIEvents = require("../../service/UI/UIEvents");
  658. var eventEmitter = new EventEmitter();
  659. function getMediaStreamUsage()
  660. {
  661. var result = {
  662. audio: true,
  663. video: true
  664. };
  665. /** There are some issues with the desktop sharing
  666. * when this property is enabled.
  667. * WARNING: We must change the implementation to start video/audio if we
  668. * receive from the focus that the peer is not muted.
  669. var isSecureConnection = window.location.protocol == "https:";
  670. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  671. {
  672. result = {
  673. audio: false,
  674. video: false
  675. };
  676. }
  677. **/
  678. return result;
  679. }
  680. var RTC = {
  681. rtcUtils: null,
  682. devices: {
  683. audio: true,
  684. video: true
  685. },
  686. localStreams: [],
  687. remoteStreams: {},
  688. localAudio: null,
  689. localVideo: null,
  690. addStreamListener: function (listener, eventType) {
  691. eventEmitter.on(eventType, listener);
  692. },
  693. addListener: function (type, listener) {
  694. eventEmitter.on(type, listener);
  695. },
  696. removeStreamListener: function (listener, eventType) {
  697. if(!(eventType instanceof StreamEventTypes))
  698. throw "Illegal argument";
  699. eventEmitter.removeListener(eventType, listener);
  700. },
  701. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  702. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  703. //in firefox we have only one stream object
  704. if(this.localStreams.length == 0 ||
  705. this.localStreams[0].getOriginalStream() != stream)
  706. this.localStreams.push(localStream);
  707. if(isMuted === true)
  708. localStream.setMute(false);
  709. if(type == "audio")
  710. {
  711. this.localAudio = localStream;
  712. }
  713. else
  714. {
  715. this.localVideo = localStream;
  716. }
  717. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  718. if(change)
  719. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  720. eventEmitter.emit(eventType, localStream, isMuted);
  721. return localStream;
  722. },
  723. removeLocalStream: function (stream) {
  724. for(var i = 0; i < this.localStreams.length; i++)
  725. {
  726. if(this.localStreams[i].getOriginalStream() === stream) {
  727. delete this.localStreams[i];
  728. return;
  729. }
  730. }
  731. },
  732. createRemoteStream: function (data, sid, thessrc) {
  733. var remoteStream = new MediaStream(data, sid, thessrc,
  734. RTCBrowserType.getBrowserType(), eventEmitter);
  735. var jid = data.peerjid || APP.xmpp.myJid();
  736. if(!this.remoteStreams[jid]) {
  737. this.remoteStreams[jid] = {};
  738. }
  739. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  740. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  741. return remoteStream;
  742. },
  743. getPCConstraints: function () {
  744. return this.rtcUtils.pc_constraints;
  745. },
  746. getUserMediaWithConstraints:function(um, success_callback,
  747. failure_callback, resolution,
  748. bandwidth, fps, desktopStream)
  749. {
  750. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  751. failure_callback, resolution, bandwidth, fps, desktopStream);
  752. },
  753. attachMediaStream: function (elSelector, stream) {
  754. this.rtcUtils.attachMediaStream(elSelector, stream);
  755. },
  756. getStreamID: function (stream) {
  757. return this.rtcUtils.getStreamID(stream);
  758. },
  759. getVideoSrc: function (element) {
  760. return this.rtcUtils.getVideoSrc(element);
  761. },
  762. setVideoSrc: function (element, src) {
  763. this.rtcUtils.setVideoSrc(element, src);
  764. },
  765. getVideoElementName: function () {
  766. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  767. },
  768. dispose: function() {
  769. if (this.rtcUtils) {
  770. this.rtcUtils = null;
  771. }
  772. },
  773. stop: function () {
  774. this.dispose();
  775. },
  776. start: function () {
  777. var self = this;
  778. APP.desktopsharing.addListener(
  779. function (stream, isUsingScreenStream, callback) {
  780. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  781. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  782. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  783. DataChannels.init(event.peerconnection, eventEmitter);
  784. });
  785. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  786. DataChannels.handleSelectedEndpointEvent);
  787. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  788. DataChannels.handlePinnedEndpointEvent);
  789. // In case of IE we continue from 'onReady' callback
  790. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  791. // once it is initialized.
  792. var onReady = function () {
  793. eventEmitter.emit(RTCEvents.RTC_READY, true);
  794. self.rtcUtils.obtainAudioAndVideoPermissions(
  795. null, null, getMediaStreamUsage());
  796. };
  797. this.rtcUtils = new RTCUtils(this, onReady);
  798. // Call onReady() if Temasys plugin is not used
  799. if (!RTCBrowserType.isTemasysPluginUsed()) {
  800. onReady();
  801. }
  802. },
  803. muteRemoteVideoStream: function (jid, value) {
  804. var stream;
  805. if(this.remoteStreams[jid] &&
  806. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  807. {
  808. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  809. }
  810. if(!stream)
  811. return true;
  812. if (value != stream.muted) {
  813. stream.setMute(value);
  814. return true;
  815. }
  816. return false;
  817. },
  818. switchVideoStreams: function (new_stream) {
  819. this.localVideo.stream = new_stream;
  820. this.localStreams = [];
  821. //in firefox we have only one stream object
  822. if (this.localAudio.getOriginalStream() != new_stream)
  823. this.localStreams.push(this.localAudio);
  824. this.localStreams.push(this.localVideo);
  825. },
  826. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  827. var oldStream = this.localVideo.getOriginalStream();
  828. var type = (isUsingScreenStream? "screen" : "video");
  829. var localCallback = callback;
  830. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  831. {
  832. localCallback = function() {
  833. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  834. callback();
  835. };
  836. }
  837. // FIXME: Workaround for FF/IE/Safari
  838. if (stream && stream.videoStream) {
  839. stream = stream.videoStream;
  840. }
  841. var videoStream = this.rtcUtils.createStream(stream, true);
  842. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  843. // Stop the stream to trigger onended event for old stream
  844. oldStream.stop();
  845. this.switchVideoStreams(videoStream, oldStream);
  846. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  847. },
  848. changeLocalAudio: function (stream, callback) {
  849. var oldStream = this.localAudio.getOriginalStream();
  850. var newStream = this.rtcUtils.createStream(stream);
  851. this.localAudio = this.createLocalStream(newStream, "audio", true);
  852. // Stop the stream to trigger onended event for old stream
  853. oldStream.stop();
  854. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  855. },
  856. isVideoMuted: function (jid) {
  857. if (jid === APP.xmpp.myJid()) {
  858. var localVideo = APP.RTC.localVideo;
  859. return (!localVideo || localVideo.isMuted());
  860. }
  861. else
  862. {
  863. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  864. return null;
  865. }
  866. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  867. }
  868. },
  869. /**
  870. * Checks if video identified by given src is desktop stream.
  871. * @param videoSrc eg.
  872. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  873. * @returns {boolean}
  874. */
  875. isVideoSrcDesktop: function (jid) {
  876. if(!jid)
  877. return false;
  878. var isDesktop = false;
  879. var stream = null;
  880. if (APP.xmpp.myJid() === jid) {
  881. // local video
  882. stream = this.localVideo;
  883. } else {
  884. var peerStreams = this.remoteStreams[jid];
  885. if(!peerStreams)
  886. return false;
  887. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  888. }
  889. if(stream)
  890. isDesktop = (stream.videoType === "screen");
  891. return isDesktop;
  892. },
  893. setVideoMute: function(mute, callback, options) {
  894. if(!this.localVideo)
  895. return;
  896. if (mute == APP.RTC.localVideo.isMuted())
  897. {
  898. APP.xmpp.sendVideoInfoPresence(mute);
  899. if(callback)
  900. callback(mute);
  901. }
  902. else
  903. {
  904. APP.RTC.localVideo.setMute(!mute);
  905. APP.xmpp.setVideoMute(
  906. mute,
  907. callback,
  908. options);
  909. }
  910. },
  911. setDeviceAvailability: function (devices) {
  912. if(!devices)
  913. return;
  914. if(devices.audio === true || devices.audio === false)
  915. this.devices.audio = devices.audio;
  916. if(devices.video === true || devices.video === false)
  917. this.devices.video = devices.video;
  918. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  919. }
  920. };
  921. module.exports = RTC;
  922. },{"../../service/RTC/MediaStreamTypes":98,"../../service/RTC/RTCEvents.js":99,"../../service/RTC/StreamEventTypes.js":101,"../../service/UI/UIEvents":102,"../../service/desktopsharing/DesktopSharingEventTypes":105,"../../service/xmpp/XMPPEvents":108,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":109}],8:[function(require,module,exports){
  923. var currentBrowser;
  924. var browserVersion;
  925. var RTCBrowserType = {
  926. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  927. RTC_BROWSER_OPERA: "rtc_browser.opera",
  928. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  929. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  930. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  931. getBrowserType: function () {
  932. return currentBrowser;
  933. },
  934. isChrome: function () {
  935. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  936. },
  937. isOpera: function () {
  938. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  939. },
  940. isFirefox: function () {
  941. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  942. },
  943. isIExplorer: function () {
  944. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  945. },
  946. isSafari: function () {
  947. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  948. },
  949. isTemasysPluginUsed: function () {
  950. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  951. },
  952. getFirefoxVersion: function () {
  953. return RTCBrowserType.isFirefox() ? browserVersion : null;
  954. },
  955. getChromeVersion: function () {
  956. return RTCBrowserType.isChrome() ? browserVersion : null;
  957. }
  958. // Add version getters for other browsers when needed
  959. };
  960. // detectOpera() must be called before detectChrome() !!!
  961. // otherwise Opera wil be detected as Chrome
  962. function detectChrome() {
  963. if (navigator.webkitGetUserMedia) {
  964. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  965. var userAgent = navigator.userAgent.toLowerCase();
  966. // We can assume that user agent is chrome, because it's
  967. // enforced when 'ext' streaming method is set
  968. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  969. console.log("This appears to be Chrome, ver: " + ver);
  970. return ver;
  971. }
  972. return null;
  973. }
  974. function detectOpera() {
  975. var userAgent = navigator.userAgent;
  976. if (userAgent.match(/Opera|OPR/)) {
  977. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  978. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  979. console.info("This appears to be Opera, ver: " + version);
  980. return version;
  981. }
  982. return null;
  983. }
  984. function detectFirefox() {
  985. if (navigator.mozGetUserMedia) {
  986. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  987. var version = parseInt(
  988. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  989. console.log('This appears to be Firefox, ver: ' + version);
  990. return version;
  991. }
  992. return null;
  993. }
  994. function detectSafari() {
  995. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  996. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  997. console.info("This appears to be Safari");
  998. // FIXME detect Safari version when needed
  999. return 1;
  1000. }
  1001. return null;
  1002. }
  1003. function detectIE() {
  1004. var version;
  1005. var ua = window.navigator.userAgent;
  1006. var msie = ua.indexOf('MSIE ');
  1007. if (msie > 0) {
  1008. // IE 10 or older => return version number
  1009. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1010. }
  1011. var trident = ua.indexOf('Trident/');
  1012. if (!version && trident > 0) {
  1013. // IE 11 => return version number
  1014. var rv = ua.indexOf('rv:');
  1015. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1016. }
  1017. var edge = ua.indexOf('Edge/');
  1018. if (!version && edge > 0) {
  1019. // IE 12 => return version number
  1020. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1021. }
  1022. if (version) {
  1023. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1024. console.info("This appears to be IExplorer, ver: " + version);
  1025. }
  1026. return version;
  1027. }
  1028. function detectBrowser() {
  1029. var version;
  1030. var detectors = [
  1031. detectOpera,
  1032. detectChrome,
  1033. detectFirefox,
  1034. detectIE,
  1035. detectSafari
  1036. ];
  1037. // Try all browser detectors
  1038. for (var i = 0; i < detectors.length; i++) {
  1039. version = detectors[i]();
  1040. if (version)
  1041. return version;
  1042. }
  1043. console.error("Failed to detect browser type");
  1044. return undefined;
  1045. }
  1046. browserVersion = detectBrowser();
  1047. module.exports = RTCBrowserType;
  1048. },{}],9:[function(require,module,exports){
  1049. var RTCBrowserType = require("./RTCBrowserType");
  1050. var Resolutions = require("../../service/RTC/Resolutions");
  1051. var AdapterJS = require("./adapter.screenshare");
  1052. var SDPUtil = require("../xmpp/SDPUtil");
  1053. var currentResolution = null;
  1054. function getPreviousResolution(resolution) {
  1055. if(!Resolutions[resolution])
  1056. return null;
  1057. var order = Resolutions[resolution].order;
  1058. var res = null;
  1059. var resName = null;
  1060. for(var i in Resolutions)
  1061. {
  1062. var tmp = Resolutions[i];
  1063. if(res == null || (res.order < tmp.order && tmp.order < order))
  1064. {
  1065. resName = i;
  1066. res = tmp;
  1067. }
  1068. }
  1069. return resName;
  1070. }
  1071. function setResolutionConstraints(constraints, resolution, isAndroid)
  1072. {
  1073. if (resolution && !constraints.video || isAndroid) {
  1074. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1075. }
  1076. if(Resolutions[resolution])
  1077. {
  1078. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1079. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1080. }
  1081. else
  1082. {
  1083. if (isAndroid) {
  1084. constraints.video.mandatory.minWidth = 320;
  1085. constraints.video.mandatory.minHeight = 240;
  1086. constraints.video.mandatory.maxFrameRate = 15;
  1087. }
  1088. }
  1089. if (constraints.video.mandatory.minWidth)
  1090. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1091. if (constraints.video.mandatory.minHeight)
  1092. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1093. }
  1094. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1095. {
  1096. var constraints = {audio: false, video: false};
  1097. if (um.indexOf('video') >= 0) {
  1098. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1099. }
  1100. if (um.indexOf('audio') >= 0) {
  1101. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1102. }
  1103. if (um.indexOf('screen') >= 0) {
  1104. if (RTCBrowserType.isChrome()) {
  1105. constraints.video = {
  1106. mandatory: {
  1107. chromeMediaSource: "screen",
  1108. googLeakyBucket: true,
  1109. maxWidth: window.screen.width,
  1110. maxHeight: window.screen.height,
  1111. maxFrameRate: 3
  1112. },
  1113. optional: []
  1114. };
  1115. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1116. constraints.video = {
  1117. optional: [
  1118. {
  1119. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1120. }
  1121. ]
  1122. };
  1123. } else {
  1124. console.error(
  1125. "'screen' WebRTC media source is supported only in Chrome" +
  1126. " and with Temasys plugin");
  1127. }
  1128. }
  1129. if (um.indexOf('desktop') >= 0) {
  1130. constraints.video = {
  1131. mandatory: {
  1132. chromeMediaSource: "desktop",
  1133. chromeMediaSourceId: desktopStream,
  1134. googLeakyBucket: true,
  1135. maxWidth: window.screen.width,
  1136. maxHeight: window.screen.height,
  1137. maxFrameRate: 3
  1138. },
  1139. optional: []
  1140. };
  1141. }
  1142. if (constraints.audio) {
  1143. // if it is good enough for hangouts...
  1144. constraints.audio.optional.push(
  1145. {googEchoCancellation: true},
  1146. {googAutoGainControl: true},
  1147. {googNoiseSupression: true},
  1148. {googHighpassFilter: true},
  1149. {googNoisesuppression2: true},
  1150. {googEchoCancellation2: true},
  1151. {googAutoGainControl2: true}
  1152. );
  1153. }
  1154. if (constraints.video) {
  1155. constraints.video.optional.push(
  1156. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1157. );
  1158. if (um.indexOf('video') >= 0) {
  1159. constraints.video.optional.push(
  1160. {googLeakyBucket: true}
  1161. );
  1162. }
  1163. }
  1164. if (um.indexOf('video') >= 0) {
  1165. setResolutionConstraints(constraints, resolution, isAndroid);
  1166. }
  1167. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1168. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1169. constraints.video.optional.push({bandwidth: bandwidth});
  1170. }
  1171. if (fps) { // for some cameras it might be necessary to request 30fps
  1172. // so they choose 30fps mjpg over 10fps yuy2
  1173. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1174. constraints.video.mandatory.minFrameRate = fps;
  1175. }
  1176. return constraints;
  1177. }
  1178. function RTCUtils(RTCService, onTemasysPluginReady)
  1179. {
  1180. var self = this;
  1181. this.service = RTCService;
  1182. if (RTCBrowserType.isFirefox()) {
  1183. var FFversion = RTCBrowserType.getFirefoxVersion();
  1184. if (FFversion >= 40 && config.useBundle && config.useRtcpMux) {
  1185. this.peerconnection = mozRTCPeerConnection;
  1186. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1187. this.pc_constraints = {};
  1188. this.attachMediaStream = function (element, stream) {
  1189. // srcObject is being standardized and FF will eventually
  1190. // support that unprefixed. FF also supports the
  1191. // "element.src = URL.createObjectURL(...)" combo, but that
  1192. // will be deprecated in favour of srcObject.
  1193. //
  1194. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1195. // https://github.com/webrtc/samples/issues/302
  1196. if(!element[0])
  1197. return;
  1198. element[0].mozSrcObject = stream;
  1199. element[0].play();
  1200. };
  1201. this.getStreamID = function (stream) {
  1202. var tracks = stream.getVideoTracks();
  1203. if(!tracks || tracks.length == 0)
  1204. {
  1205. tracks = stream.getAudioTracks();
  1206. }
  1207. return SDPUtil.filter_special_chars(tracks[0].id);
  1208. };
  1209. this.getVideoSrc = function (element) {
  1210. if(!element)
  1211. return null;
  1212. return element.mozSrcObject;
  1213. };
  1214. this.setVideoSrc = function (element, src) {
  1215. if(element)
  1216. element.mozSrcObject = src;
  1217. };
  1218. RTCSessionDescription = mozRTCSessionDescription;
  1219. RTCIceCandidate = mozRTCIceCandidate;
  1220. } else {
  1221. console.error(
  1222. "Firefox requirements not met, ver: " + FFversion +
  1223. ", bundle: " + config.useBundle +
  1224. ", rtcp-mux: " + config.useRtcpMux);
  1225. window.location.href = 'unsupported_browser.html';
  1226. return;
  1227. }
  1228. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1229. this.peerconnection = webkitRTCPeerConnection;
  1230. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1231. this.attachMediaStream = function (element, stream) {
  1232. element.attr('src', webkitURL.createObjectURL(stream));
  1233. };
  1234. this.getStreamID = function (stream) {
  1235. // streams from FF endpoints have the characters '{' and '}'
  1236. // that make jQuery choke.
  1237. return SDPUtil.filter_special_chars(stream.id);
  1238. };
  1239. this.getVideoSrc = function (element) {
  1240. if(!element)
  1241. return null;
  1242. return element.getAttribute("src");
  1243. };
  1244. this.setVideoSrc = function (element, src) {
  1245. if(element)
  1246. element.setAttribute("src", src);
  1247. };
  1248. // DTLS should now be enabled by default but..
  1249. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1250. if (navigator.userAgent.indexOf('Android') != -1) {
  1251. this.pc_constraints = {}; // disable DTLS on Android
  1252. }
  1253. if (!webkitMediaStream.prototype.getVideoTracks) {
  1254. webkitMediaStream.prototype.getVideoTracks = function () {
  1255. return this.videoTracks;
  1256. };
  1257. }
  1258. if (!webkitMediaStream.prototype.getAudioTracks) {
  1259. webkitMediaStream.prototype.getAudioTracks = function () {
  1260. return this.audioTracks;
  1261. };
  1262. }
  1263. }
  1264. // Detect IE/Safari
  1265. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1266. AdapterJS.WebRTCPlugin.setLogLevel(
  1267. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1268. AdapterJS.webRTCReady(function (isPlugin) {
  1269. self.peerconnection = RTCPeerConnection;
  1270. self.getUserMedia = getUserMedia;
  1271. self.attachMediaStream = function (elSel, stream) {
  1272. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1273. return;
  1274. }
  1275. attachMediaStream(elSel[0], stream);
  1276. };
  1277. self.getStreamID = function (stream) {
  1278. var id = SDPUtil.filter_special_chars(stream.label);
  1279. return id;
  1280. };
  1281. self.getVideoSrc = function (element) {
  1282. if (!element) {
  1283. console.warn("Attempt to get video SRC of null element");
  1284. return null;
  1285. }
  1286. var src = null;
  1287. var children = element.children;
  1288. for (var i = 0; i !== children.length; ++i) {
  1289. if (children[i].name === 'streamId') {
  1290. return children[i].value;
  1291. }
  1292. }
  1293. //console.info(element.id + " SRC: " + src);
  1294. return null;
  1295. };
  1296. self.setVideoSrc = function (element, src) {
  1297. //console.info("Set video src: ", element, src);
  1298. if (!src) {
  1299. console.warn("Not attaching video stream, 'src' is null");
  1300. return;
  1301. }
  1302. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1303. var stream = AdapterJS.WebRTCPlugin.plugin
  1304. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1305. attachMediaStream(element, stream);
  1306. };
  1307. onTemasysPluginReady(isPlugin);
  1308. });
  1309. } else {
  1310. try {
  1311. console.log('Browser does not appear to be WebRTC-capable');
  1312. } catch (e) { }
  1313. window.location.href = 'unsupported_browser.html';
  1314. }
  1315. }
  1316. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1317. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1318. desktopStream)
  1319. {
  1320. currentResolution = resolution;
  1321. // Check if we are running on Android device
  1322. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1323. var constraints = getConstraints(
  1324. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1325. console.info("Get media constraints", constraints);
  1326. var self = this;
  1327. try {
  1328. this.getUserMedia(constraints,
  1329. function (stream) {
  1330. console.log('onUserMediaSuccess');
  1331. self.setAvailableDevices(um, true);
  1332. success_callback(stream);
  1333. },
  1334. function (error) {
  1335. self.setAvailableDevices(um, false);
  1336. console.warn('Failed to get access to local media. Error ',
  1337. error, constraints);
  1338. if (failure_callback) {
  1339. failure_callback(error);
  1340. }
  1341. });
  1342. } catch (e) {
  1343. console.error('GUM failed: ', e);
  1344. if(failure_callback) {
  1345. failure_callback(e);
  1346. }
  1347. }
  1348. };
  1349. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1350. var devices = {};
  1351. if(um.indexOf("video") != -1)
  1352. {
  1353. devices.video = available;
  1354. }
  1355. if(um.indexOf("audio") != -1)
  1356. {
  1357. devices.audio = available;
  1358. }
  1359. this.service.setDeviceAvailability(devices);
  1360. }
  1361. /**
  1362. * We ask for audio and video combined stream in order to get permissions and
  1363. * not to ask twice.
  1364. */
  1365. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1366. function(devices, callback, usageOptions)
  1367. {
  1368. var self = this;
  1369. // Get AV
  1370. var successCallback = function (stream) {
  1371. if(callback)
  1372. callback(stream, usageOptions);
  1373. else
  1374. self.successCallback(stream, usageOptions);
  1375. };
  1376. if(!devices)
  1377. devices = ['audio', 'video'];
  1378. var newDevices = [];
  1379. if(usageOptions)
  1380. for(var i = 0; i < devices.length; i++)
  1381. {
  1382. var device = devices[i];
  1383. if(usageOptions[device] === true)
  1384. newDevices.push(device);
  1385. }
  1386. else
  1387. newDevices = devices;
  1388. if(newDevices.length === 0)
  1389. {
  1390. successCallback();
  1391. return;
  1392. }
  1393. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1394. // With FF/IE we can't split the stream into audio and video because FF
  1395. // doesn't support media stream constructors. So, we need to get the
  1396. // audio stream separately from the video stream using two distinct GUM
  1397. // calls. Not very user friendly :-( but we don't have many other
  1398. // options neither.
  1399. //
  1400. // Note that we pack those 2 streams in a single object and pass it to
  1401. // the successCallback method.
  1402. var obtainVideo = function (audioStream) {
  1403. self.getUserMediaWithConstraints(
  1404. ['video'],
  1405. function (videoStream) {
  1406. return successCallback({
  1407. audioStream: audioStream,
  1408. videoStream: videoStream
  1409. });
  1410. },
  1411. function (error) {
  1412. console.error(
  1413. 'failed to obtain video stream - stop', error);
  1414. self.errorCallback(error);
  1415. },
  1416. config.resolution || '360');
  1417. };
  1418. var obtainAudio = function () {
  1419. self.getUserMediaWithConstraints(
  1420. ['audio'],
  1421. function (audioStream) {
  1422. if (newDevices.indexOf('video') !== -1)
  1423. obtainVideo(audioStream);
  1424. },
  1425. function (error) {
  1426. console.error(
  1427. 'failed to obtain audio stream - stop', error);
  1428. self.errorCallback(error);
  1429. }
  1430. );
  1431. };
  1432. if (newDevices.indexOf('audio') !== -1) {
  1433. obtainAudio();
  1434. } else {
  1435. obtainVideo(null);
  1436. }
  1437. } else {
  1438. this.getUserMediaWithConstraints(
  1439. newDevices,
  1440. function (stream) {
  1441. successCallback(stream);
  1442. },
  1443. function (error) {
  1444. self.errorCallback(error);
  1445. },
  1446. config.resolution || '360');
  1447. }
  1448. };
  1449. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1450. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1451. // it's an object with two properties: audioStream, videoStream.
  1452. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1453. console.log('got', stream, stream.getAudioTracks().length,
  1454. stream.getVideoTracks().length);
  1455. this.handleLocalStream(stream, usageOptions);
  1456. };
  1457. RTCUtils.prototype.errorCallback = function (error) {
  1458. var self = this;
  1459. console.error('failed to obtain audio/video stream - trying audio only', error);
  1460. var resolution = getPreviousResolution(currentResolution);
  1461. if(typeof error == "object" && error.constraintName && error.name
  1462. && (error.name == "ConstraintNotSatisfiedError" ||
  1463. error.name == "OverconstrainedError") &&
  1464. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1465. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1466. && resolution != null)
  1467. {
  1468. self.getUserMediaWithConstraints(['audio', 'video'],
  1469. function (stream) {
  1470. return self.successCallback(stream);
  1471. }, function (error) {
  1472. return self.errorCallback(error);
  1473. }, resolution);
  1474. }
  1475. else
  1476. {
  1477. self.getUserMediaWithConstraints(
  1478. ['audio'],
  1479. function (stream) {
  1480. return self.successCallback(stream);
  1481. },
  1482. function (error) {
  1483. console.error('failed to obtain audio/video stream - stop',
  1484. error);
  1485. return self.successCallback(null);
  1486. }
  1487. );
  1488. }
  1489. }
  1490. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1491. {
  1492. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1493. // an object with two properties: audioStream, videoStream.
  1494. var audioStream, videoStream;
  1495. if(window.webkitMediaStream)
  1496. {
  1497. audioStream = new webkitMediaStream();
  1498. videoStream = new webkitMediaStream();
  1499. if(stream) {
  1500. var audioTracks = stream.getAudioTracks();
  1501. for (var i = 0; i < audioTracks.length; i++) {
  1502. audioStream.addTrack(audioTracks[i]);
  1503. }
  1504. var videoTracks = stream.getVideoTracks();
  1505. for (i = 0; i < videoTracks.length; i++) {
  1506. videoStream.addTrack(videoTracks[i]);
  1507. }
  1508. }
  1509. }
  1510. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1511. { // Firefox and Temasys plugin
  1512. if (stream && stream.audioStream)
  1513. audioStream = stream.audioStream;
  1514. else
  1515. audioStream = new DummyMediaStream("dummyAudio");
  1516. if (stream && stream.videoStream)
  1517. videoStream = stream.videoStream;
  1518. else
  1519. videoStream = new DummyMediaStream("dummyVideo");
  1520. }
  1521. var audioMuted = (usageOptions && usageOptions.audio === false),
  1522. videoMuted = (usageOptions && usageOptions.video === false);
  1523. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1524. videoGUM = (!usageOptions || usageOptions.video !== false);
  1525. this.service.createLocalStream(audioStream, "audio", null, null,
  1526. audioMuted, audioGUM);
  1527. this.service.createLocalStream(videoStream, "video", null, null,
  1528. videoMuted, videoGUM);
  1529. };
  1530. function DummyMediaStream(id) {
  1531. this.id = id;
  1532. this.label = id;
  1533. this.stop = function() { };
  1534. this.getAudioTracks = function() { return []; }
  1535. this.getVideoTracks = function() { return []; }
  1536. }
  1537. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1538. var newStream = null;
  1539. if (window.webkitMediaStream) {
  1540. newStream = new webkitMediaStream();
  1541. if (newStream) {
  1542. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1543. for (i = 0; i < tracks.length; i++) {
  1544. newStream.addTrack(tracks[i]);
  1545. }
  1546. }
  1547. }
  1548. else {
  1549. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1550. if (stream) {
  1551. newStream = stream;
  1552. } else {
  1553. newStream = new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1554. }
  1555. }
  1556. return newStream;
  1557. };
  1558. module.exports = RTCUtils;
  1559. },{"../../service/RTC/Resolutions":100,"../xmpp/SDPUtil":56,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1560. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1561. // Adapter's interface.
  1562. var AdapterJS = AdapterJS || {};
  1563. // Browserify compatibility
  1564. if(typeof exports !== 'undefined') {
  1565. module.exports = AdapterJS;
  1566. }
  1567. AdapterJS.options = AdapterJS.options || {};
  1568. // uncomment to get virtual webcams
  1569. // AdapterJS.options.getAllCams = true;
  1570. // uncomment to prevent the install prompt when the plugin in not yet installed
  1571. // AdapterJS.options.hidePluginInstallPrompt = true;
  1572. // AdapterJS version
  1573. AdapterJS.VERSION = '0.11.0';
  1574. // This function will be called when the WebRTC API is ready to be used
  1575. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1576. // the plugin
  1577. // You may Override this function to synchronise the start of your application
  1578. // with the WebRTC API being ready.
  1579. // If you decide not to override use this synchronisation, it may result in
  1580. // an extensive CPU usage on the plugin start (once per tab loaded)
  1581. // Params:
  1582. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1583. //
  1584. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1585. // The WebRTC API is ready.
  1586. // Override me and do whatever you want here
  1587. };
  1588. // Sets a callback function to be called when the WebRTC interface is ready.
  1589. // The first argument is the function to callback.\
  1590. // Throws an error if the first argument is not a function
  1591. AdapterJS.webRTCReady = function (callback) {
  1592. if (typeof callback !== 'function') {
  1593. throw new Error('Callback provided is not a function');
  1594. }
  1595. if (true === AdapterJS.onwebrtcreadyDone) {
  1596. // All WebRTC interfaces are ready, just call the callback
  1597. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1598. } else {
  1599. // will be triggered automatically when your browser/plugin is ready.
  1600. AdapterJS.onwebrtcready = callback;
  1601. }
  1602. };
  1603. // Plugin namespace
  1604. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1605. // The object to store plugin information
  1606. AdapterJS.WebRTCPlugin.pluginInfo = {
  1607. prefix : 'Tem',
  1608. plugName : 'TemWebRTCPlugin',
  1609. pluginId : 'plugin0',
  1610. type : 'application/x-temwebrtcplugin',
  1611. onload : '__TemWebRTCReady0',
  1612. portalLink : 'http://skylink.io/plugin/',
  1613. downloadLink : null, //set below
  1614. companyName: 'Temasys'
  1615. };
  1616. if(!!navigator.platform.match(/^Mac/i)) {
  1617. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1618. }
  1619. else if(!!navigator.platform.match(/^Win/i)) {
  1620. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1621. }
  1622. // Unique identifier of each opened page
  1623. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1624. // Use this whenever you want to call the plugin.
  1625. AdapterJS.WebRTCPlugin.plugin = null;
  1626. // Set log level for the plugin once it is ready.
  1627. // The different values are
  1628. // This is an asynchronous function that will run when the plugin is ready
  1629. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1630. // Defines webrtc's JS interface according to the plugin's implementation.
  1631. // Define plugin Browsers as WebRTC Interface.
  1632. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1633. // This function detects whether or not a plugin is installed.
  1634. // Checks if Not IE (firefox, for example), else if it's IE,
  1635. // we're running IE and do something. If not it is not supported.
  1636. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1637. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1638. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1639. // Inject the HTML DOM object element into the page.
  1640. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1641. // States of readiness that the plugin goes through when
  1642. // being injected and stated
  1643. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1644. NONE : 0, // no plugin use
  1645. INITIALIZING : 1, // Detected need for plugin
  1646. INJECTING : 2, // Injecting plugin
  1647. INJECTED: 3, // Plugin element injected but not usable yet
  1648. READY: 4 // Plugin ready to be used
  1649. };
  1650. // Current state of the plugin. You cannot use the plugin before this is
  1651. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1652. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1653. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1654. // Used to make sure AdapterJS.onwebrtcready is only called once
  1655. AdapterJS.onwebrtcreadyDone = false;
  1656. // Log levels for the plugin.
  1657. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1658. /*
  1659. Log outputs are prefixed in some cases.
  1660. INFO: Information reported by the plugin.
  1661. ERROR: Errors originating from within the plugin.
  1662. WEBRTC: Error originating from within the libWebRTC library
  1663. */
  1664. // From the least verbose to the most verbose
  1665. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1666. NONE : 'NONE',
  1667. ERROR : 'ERROR',
  1668. WARNING : 'WARNING',
  1669. INFO: 'INFO',
  1670. VERBOSE: 'VERBOSE',
  1671. SENSITIVE: 'SENSITIVE'
  1672. };
  1673. // Does a waiting check before proceeding to load the plugin.
  1674. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1675. // This methid will use an interval to wait for the plugin to be ready.
  1676. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1677. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1678. // This function will be called when plugin is ready. It sends necessary
  1679. // details to the plugin.
  1680. // The function will wait for the document to be ready and the set the
  1681. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1682. // indicating that it can start being requested.
  1683. // This function is not in the IE/Safari condition brackets so that
  1684. // TemPluginLoaded function might be called on Chrome/Firefox.
  1685. // This function is the only private function that is not encapsulated to
  1686. // allow the plugin method to be called.
  1687. __TemWebRTCReady0 = function () {
  1688. if (document.readyState === 'complete') {
  1689. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1690. AdapterJS.maybeThroughWebRTCReady();
  1691. } else {
  1692. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1693. if (document.readyState === 'complete') {
  1694. // TODO: update comments, we wait for the document to be ready
  1695. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1696. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1697. AdapterJS.maybeThroughWebRTCReady();
  1698. }
  1699. }, 100);
  1700. }
  1701. };
  1702. AdapterJS.maybeThroughWebRTCReady = function() {
  1703. if (!AdapterJS.onwebrtcreadyDone) {
  1704. AdapterJS.onwebrtcreadyDone = true;
  1705. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1706. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1707. }
  1708. }
  1709. };
  1710. // Text namespace
  1711. AdapterJS.TEXT = {
  1712. PLUGIN: {
  1713. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1714. 'to work on this browser.',
  1715. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1716. BUTTON: 'Install Now'
  1717. },
  1718. REFRESH: {
  1719. REQUIRE_REFRESH: 'Please refresh page',
  1720. BUTTON: 'Refresh Page'
  1721. }
  1722. };
  1723. // The result of ice connection states.
  1724. // - starting: Ice connection is starting.
  1725. // - checking: Ice connection is checking.
  1726. // - connected Ice connection is connected.
  1727. // - completed Ice connection is connected.
  1728. // - done Ice connection has been completed.
  1729. // - disconnected Ice connection has been disconnected.
  1730. // - failed Ice connection has failed.
  1731. // - closed Ice connection is closed.
  1732. AdapterJS._iceConnectionStates = {
  1733. starting : 'starting',
  1734. checking : 'checking',
  1735. connected : 'connected',
  1736. completed : 'connected',
  1737. done : 'completed',
  1738. disconnected : 'disconnected',
  1739. failed : 'failed',
  1740. closed : 'closed'
  1741. };
  1742. //The IceConnection states that has been fired for each peer.
  1743. AdapterJS._iceConnectionFiredStates = [];
  1744. // Check if WebRTC Interface is defined.
  1745. AdapterJS.isDefined = null;
  1746. // This function helps to retrieve the webrtc detected browser information.
  1747. // This sets:
  1748. // - webrtcDetectedBrowser: The browser agent name.
  1749. // - webrtcDetectedVersion: The browser version.
  1750. // - webrtcDetectedType: The types of webRTC support.
  1751. // - 'moz': Mozilla implementation of webRTC.
  1752. // - 'webkit': WebKit implementation of webRTC.
  1753. // - 'plugin': Using the plugin implementation.
  1754. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1755. var hasMatch, checkMatch = navigator.userAgent.match(
  1756. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1757. if (/trident/i.test(checkMatch[1])) {
  1758. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1759. webrtcDetectedBrowser = 'IE';
  1760. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1761. } else if (checkMatch[1] === 'Chrome') {
  1762. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1763. if (hasMatch !== null) {
  1764. webrtcDetectedBrowser = 'opera';
  1765. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1766. }
  1767. }
  1768. if (navigator.userAgent.indexOf('Safari')) {
  1769. if (typeof InstallTrigger !== 'undefined') {
  1770. webrtcDetectedBrowser = 'firefox';
  1771. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1772. webrtcDetectedBrowser = 'IE';
  1773. } else if (
  1774. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1775. webrtcDetectedBrowser = 'safari';
  1776. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1777. webrtcDetectedBrowser = 'opera';
  1778. } else if (!!window.chrome) {
  1779. webrtcDetectedBrowser = 'chrome';
  1780. }
  1781. }
  1782. if (!webrtcDetectedBrowser) {
  1783. webrtcDetectedVersion = checkMatch[1];
  1784. }
  1785. if (!webrtcDetectedVersion) {
  1786. try {
  1787. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1788. [navigator.appName, navigator.appVersion, '-?'];
  1789. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1790. checkMatch.splice(1, 1, hasMatch[1]);
  1791. }
  1792. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1793. } catch (error) { }
  1794. }
  1795. };
  1796. // To fix configuration as some browsers does not support
  1797. // the 'urls' attribute.
  1798. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1799. if (pcConfig === null) {
  1800. return;
  1801. }
  1802. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1803. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1804. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1805. delete pcConfig.iceServers[i].urls;
  1806. }
  1807. }
  1808. };
  1809. AdapterJS.addEvent = function(elem, evnt, func) {
  1810. if (elem.addEventListener) { // W3C DOM
  1811. elem.addEventListener(evnt, func, false);
  1812. } else if (elem.attachEvent) {// OLD IE DOM
  1813. elem.attachEvent('on'+evnt, func);
  1814. } else { // No much to do
  1815. elem[evnt] = func;
  1816. }
  1817. };
  1818. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1819. // only inject once the page is ready
  1820. if (document.readyState !== 'complete') {
  1821. return;
  1822. }
  1823. var w = window;
  1824. var i = document.createElement('iframe');
  1825. i.style.position = 'fixed';
  1826. i.style.top = '-41px';
  1827. i.style.left = 0;
  1828. i.style.right = 0;
  1829. i.style.width = '100%';
  1830. i.style.height = '40px';
  1831. i.style.backgroundColor = '#ffffe1';
  1832. i.style.border = 'none';
  1833. i.style.borderBottom = '1px solid #888888';
  1834. i.style.zIndex = '9999999';
  1835. if(typeof i.style.webkitTransition === 'string') {
  1836. i.style.webkitTransition = 'all .5s ease-out';
  1837. } else if(typeof i.style.transition === 'string') {
  1838. i.style.transition = 'all .5s ease-out';
  1839. }
  1840. document.body.appendChild(i);
  1841. c = (i.contentWindow) ? i.contentWindow :
  1842. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1843. c.document.open();
  1844. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1845. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1846. 'middle; cursor: default;">' + text + '</span>');
  1847. if(buttonText && buttonLink) {
  1848. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1849. c.document.close();
  1850. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1851. if (!!displayRefreshBar) {
  1852. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1853. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1854. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1855. }
  1856. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1857. e.preventDefault();
  1858. try {
  1859. event.cancelBubble = true;
  1860. } catch(error) { }
  1861. });
  1862. }
  1863. else {
  1864. c.document.close();
  1865. }
  1866. AdapterJS.addEvent(c.document, 'click', function() {
  1867. w.document.body.removeChild(i);
  1868. });
  1869. setTimeout(function() {
  1870. if(typeof i.style.webkitTransform === 'string') {
  1871. i.style.webkitTransform = 'translateY(40px)';
  1872. } else if(typeof i.style.transform === 'string') {
  1873. i.style.transform = 'translateY(40px)';
  1874. } else {
  1875. i.style.top = '0px';
  1876. }
  1877. }, 300);
  1878. };
  1879. // -----------------------------------------------------------
  1880. // Detected webrtc implementation. Types are:
  1881. // - 'moz': Mozilla implementation of webRTC.
  1882. // - 'webkit': WebKit implementation of webRTC.
  1883. // - 'plugin': Using the plugin implementation.
  1884. webrtcDetectedType = null;
  1885. // Detected webrtc datachannel support. Types are:
  1886. // - 'SCTP': SCTP datachannel support.
  1887. // - 'RTP': RTP datachannel support.
  1888. webrtcDetectedDCSupport = null;
  1889. // Set the settings for creating DataChannels, MediaStream for
  1890. // Cross-browser compability.
  1891. // - This is only for SCTP based support browsers.
  1892. // the 'urls' attribute.
  1893. checkMediaDataChannelSettings =
  1894. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1895. if (typeof callback !== 'function') {
  1896. return;
  1897. }
  1898. var beOfferer = true;
  1899. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1900. // Nightly version does not require MozDontOfferDataChannel for interop
  1901. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1902. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1903. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1904. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1905. // Resends an updated version of constraints for MozDataChannel to work
  1906. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1907. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1908. try {
  1909. delete constraints.mandatory.MozDontOfferDataChannel;
  1910. } catch (error) {
  1911. console.error('Failed deleting MozDontOfferDataChannel');
  1912. console.error(error);
  1913. }
  1914. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1915. constraints.mandatory.MozDontOfferDataChannel = true;
  1916. }
  1917. if (!isLocalFirefox) {
  1918. // temporary measure to remove Moz* constraints in non Firefox browsers
  1919. for (var prop in constraints.mandatory) {
  1920. if (constraints.mandatory.hasOwnProperty(prop)) {
  1921. if (prop.indexOf('Moz') !== -1) {
  1922. delete constraints.mandatory[prop];
  1923. }
  1924. }
  1925. }
  1926. }
  1927. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1928. // interopability of the media stream
  1929. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1930. beOfferer = false;
  1931. }
  1932. callback(beOfferer, constraints);
  1933. };
  1934. // Handles the differences for all browsers ice connection state output.
  1935. // - Tested outcomes are:
  1936. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1937. // - Chrome (answerer) : 'checking' > 'connected'
  1938. // - Firefox (offerer) : 'checking' > 'connected'
  1939. // - Firefox (answerer): 'checking' > 'connected'
  1940. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1941. if (typeof callback !== 'function') {
  1942. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1943. return;
  1944. }
  1945. peerId = (peerId) ? peerId : 'peer';
  1946. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1947. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1948. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1949. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1950. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1951. }
  1952. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1953. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1954. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1955. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1956. setTimeout(function () {
  1957. AdapterJS._iceConnectionFiredStates[peerId]
  1958. .push(AdapterJS._iceConnectionStates.done);
  1959. callback(AdapterJS._iceConnectionStates.done);
  1960. }, 1000);
  1961. }
  1962. callback(iceConnectionState);
  1963. }
  1964. return;
  1965. };
  1966. // Firefox:
  1967. // - Creates iceServer from the url for Firefox.
  1968. // - Create iceServer with stun url.
  1969. // - Create iceServer with turn url.
  1970. // - Ignore the transport parameter from TURN url for FF version <=27.
  1971. // - Return null for createIceServer if transport=tcp.
  1972. // - FF 27 and above supports transport parameters in TURN url,
  1973. // - So passing in the full url to create iceServer.
  1974. // Chrome:
  1975. // - Creates iceServer from the url for Chrome M33 and earlier.
  1976. // - Create iceServer with stun url.
  1977. // - Chrome M28 & above uses below TURN format.
  1978. // Plugin:
  1979. // - Creates Ice Server for Plugin Browsers
  1980. // - If Stun - Create iceServer with stun url.
  1981. // - Else - Create iceServer with turn url
  1982. // - This is a WebRTC Function
  1983. createIceServer = null;
  1984. // Firefox:
  1985. // - Creates IceServers for Firefox
  1986. // - Use .url for FireFox.
  1987. // - Multiple Urls support
  1988. // Chrome:
  1989. // - Creates iceServers from the urls for Chrome M34 and above.
  1990. // - .urls is supported since Chrome M34.
  1991. // - Multiple Urls support
  1992. // Plugin:
  1993. // - Creates Ice Servers for Plugin Browsers
  1994. // - Multiple Urls support
  1995. // - This is a WebRTC Function
  1996. createIceServers = null;
  1997. //------------------------------------------------------------
  1998. //The RTCPeerConnection object.
  1999. RTCPeerConnection = null;
  2000. // Creates RTCSessionDescription object for Plugin Browsers
  2001. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2002. RTCSessionDescription : null;
  2003. // Creates RTCIceCandidate object for Plugin Browsers
  2004. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2005. RTCIceCandidate : null;
  2006. // Get UserMedia (only difference is the prefix).
  2007. // Code from Adam Barth.
  2008. getUserMedia = null;
  2009. // Attach a media stream to an element.
  2010. attachMediaStream = null;
  2011. // Re-attach a media stream to an element.
  2012. reattachMediaStream = null;
  2013. // Detected browser agent name. Types are:
  2014. // - 'firefox': Firefox browser.
  2015. // - 'chrome': Chrome browser.
  2016. // - 'opera': Opera browser.
  2017. // - 'safari': Safari browser.
  2018. // - 'IE' - Internet Explorer browser.
  2019. webrtcDetectedBrowser = null;
  2020. // Detected browser version.
  2021. webrtcDetectedVersion = null;
  2022. // Check for browser types and react accordingly
  2023. if (navigator.mozGetUserMedia) {
  2024. webrtcDetectedBrowser = 'firefox';
  2025. webrtcDetectedVersion = parseInt(navigator
  2026. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2027. webrtcDetectedType = 'moz';
  2028. webrtcDetectedDCSupport = 'SCTP';
  2029. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2030. AdapterJS.maybeFixConfiguration(pcConfig);
  2031. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2032. };
  2033. // The RTCSessionDescription object.
  2034. RTCSessionDescription = mozRTCSessionDescription;
  2035. window.RTCSessionDescription = RTCSessionDescription;
  2036. // The RTCIceCandidate object.
  2037. RTCIceCandidate = mozRTCIceCandidate;
  2038. window.RTCIceCandidate = RTCIceCandidate;
  2039. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2040. navigator.getUserMedia = window.getUserMedia;
  2041. // Shim for MediaStreamTrack.getSources.
  2042. MediaStreamTrack.getSources = function(successCb) {
  2043. setTimeout(function() {
  2044. var infos = [
  2045. { kind: 'audio', id: 'default', label:'', facing:'' },
  2046. { kind: 'video', id: 'default', label:'', facing:'' }
  2047. ];
  2048. successCb(infos);
  2049. }, 0);
  2050. };
  2051. createIceServer = function (url, username, password) {
  2052. var iceServer = null;
  2053. var url_parts = url.split(':');
  2054. if (url_parts[0].indexOf('stun') === 0) {
  2055. iceServer = { url : url };
  2056. } else if (url_parts[0].indexOf('turn') === 0) {
  2057. if (webrtcDetectedVersion < 27) {
  2058. var turn_url_parts = url.split('?');
  2059. if (turn_url_parts.length === 1 ||
  2060. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2061. iceServer = {
  2062. url : turn_url_parts[0],
  2063. credential : password,
  2064. username : username
  2065. };
  2066. }
  2067. } else {
  2068. iceServer = {
  2069. url : url,
  2070. credential : password,
  2071. username : username
  2072. };
  2073. }
  2074. }
  2075. return iceServer;
  2076. };
  2077. createIceServers = function (urls, username, password) {
  2078. var iceServers = [];
  2079. for (i = 0; i < urls.length; i++) {
  2080. var iceServer = createIceServer(urls[i], username, password);
  2081. if (iceServer !== null) {
  2082. iceServers.push(iceServer);
  2083. }
  2084. }
  2085. return iceServers;
  2086. };
  2087. attachMediaStream = function (element, stream) {
  2088. element.mozSrcObject = stream;
  2089. if (stream !== null)
  2090. element.play();
  2091. return element;
  2092. };
  2093. reattachMediaStream = function (to, from) {
  2094. to.mozSrcObject = from.mozSrcObject;
  2095. to.play();
  2096. return to;
  2097. };
  2098. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2099. if (!callback) {
  2100. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2101. ': 1 argument required, but only 0 present.');
  2102. }
  2103. return callback([]);
  2104. };
  2105. // Fake get{Video,Audio}Tracks
  2106. if (!MediaStream.prototype.getVideoTracks) {
  2107. MediaStream.prototype.getVideoTracks = function () {
  2108. return [];
  2109. };
  2110. }
  2111. if (!MediaStream.prototype.getAudioTracks) {
  2112. MediaStream.prototype.getAudioTracks = function () {
  2113. return [];
  2114. };
  2115. }
  2116. AdapterJS.maybeThroughWebRTCReady();
  2117. } else if (navigator.webkitGetUserMedia) {
  2118. webrtcDetectedBrowser = 'chrome';
  2119. webrtcDetectedType = 'webkit';
  2120. webrtcDetectedVersion = parseInt(navigator
  2121. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2122. // check if browser is opera 20+
  2123. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2124. if (checkIfOpera !== null) {
  2125. webrtcDetectedBrowser = 'opera';
  2126. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2127. }
  2128. // check browser datachannel support
  2129. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2130. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2131. webrtcDetectedDCSupport = 'SCTP';
  2132. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2133. webrtcDetectedVersion > 24) {
  2134. webrtcDetectedDCSupport = 'RTP';
  2135. } else {
  2136. webrtcDetectedDCSupport = '';
  2137. }
  2138. createIceServer = function (url, username, password) {
  2139. var iceServer = null;
  2140. var url_parts = url.split(':');
  2141. if (url_parts[0].indexOf('stun') === 0) {
  2142. iceServer = { 'url' : url };
  2143. } else if (url_parts[0].indexOf('turn') === 0) {
  2144. iceServer = {
  2145. 'url' : url,
  2146. 'credential' : password,
  2147. 'username' : username
  2148. };
  2149. }
  2150. return iceServer;
  2151. };
  2152. createIceServers = function (urls, username, password) {
  2153. var iceServers = [];
  2154. if (webrtcDetectedVersion >= 34) {
  2155. iceServers = {
  2156. 'urls' : urls,
  2157. 'credential' : password,
  2158. 'username' : username
  2159. };
  2160. } else {
  2161. for (i = 0; i < urls.length; i++) {
  2162. var iceServer = createIceServer(urls[i], username, password);
  2163. if (iceServer !== null) {
  2164. iceServers.push(iceServer);
  2165. }
  2166. }
  2167. }
  2168. return iceServers;
  2169. };
  2170. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2171. if (webrtcDetectedVersion < 34) {
  2172. AdapterJS.maybeFixConfiguration(pcConfig);
  2173. }
  2174. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2175. };
  2176. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2177. navigator.getUserMedia = window.getUserMedia;
  2178. attachMediaStream = function (element, stream) {
  2179. if (typeof element.srcObject !== 'undefined') {
  2180. element.srcObject = stream;
  2181. } else if (typeof element.mozSrcObject !== 'undefined') {
  2182. element.mozSrcObject = stream;
  2183. } else if (typeof element.src !== 'undefined') {
  2184. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2185. } else {
  2186. console.log('Error attaching stream to element.');
  2187. }
  2188. return element;
  2189. };
  2190. reattachMediaStream = function (to, from) {
  2191. to.src = from.src;
  2192. return to;
  2193. };
  2194. AdapterJS.maybeThroughWebRTCReady();
  2195. } else { // TRY TO USE PLUGIN
  2196. // IE 9 is not offering an implementation of console.log until you open a console
  2197. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2198. /* jshint -W020 */
  2199. console = {} || console;
  2200. // Implemented based on console specs from MDN
  2201. // You may override these functions
  2202. console.log = function (arg) {};
  2203. console.info = function (arg) {};
  2204. console.error = function (arg) {};
  2205. console.dir = function (arg) {};
  2206. console.exception = function (arg) {};
  2207. console.trace = function (arg) {};
  2208. console.warn = function (arg) {};
  2209. console.count = function (arg) {};
  2210. console.debug = function (arg) {};
  2211. console.count = function (arg) {};
  2212. console.time = function (arg) {};
  2213. console.timeEnd = function (arg) {};
  2214. console.group = function (arg) {};
  2215. console.groupCollapsed = function (arg) {};
  2216. console.groupEnd = function (arg) {};
  2217. /* jshint +W020 */
  2218. }
  2219. webrtcDetectedType = 'plugin';
  2220. webrtcDetectedDCSupport = 'plugin';
  2221. AdapterJS.parseWebrtcDetectedBrowser();
  2222. isIE = webrtcDetectedBrowser === 'IE';
  2223. /* jshint -W035 */
  2224. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2225. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2226. /* empty because it needs to prevent the function from running. */
  2227. }
  2228. };
  2229. /* jshint +W035 */
  2230. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2231. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2232. // Call immediately if possible
  2233. // Once the plugin is set, the code will always take this path
  2234. callback();
  2235. } else {
  2236. // otherwise start a 100ms interval
  2237. var checkPluginReadyState = setInterval(function () {
  2238. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2239. clearInterval(checkPluginReadyState);
  2240. callback();
  2241. }
  2242. }, 100);
  2243. }
  2244. };
  2245. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2246. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2247. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2248. });
  2249. };
  2250. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2251. // only inject once the page is ready
  2252. if (document.readyState !== 'complete') {
  2253. return;
  2254. }
  2255. // Prevent multiple injections
  2256. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2257. return;
  2258. }
  2259. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2260. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2261. var frag = document.createDocumentFragment();
  2262. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2263. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2264. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2265. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2266. '<param name="pluginId" value="' +
  2267. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2268. '<param name="windowless" value="false" /> ' +
  2269. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2270. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2271. '" />' +
  2272. // uncomment to be able to use virtual cams
  2273. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2274. '</object>';
  2275. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2276. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2277. }
  2278. document.body.appendChild(frag);
  2279. // Need to re-fetch the plugin
  2280. AdapterJS.WebRTCPlugin.plugin =
  2281. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2282. } else {
  2283. // Load Plugin
  2284. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2285. AdapterJS.WebRTCPlugin.plugin.id =
  2286. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2287. // IE will only start the plugin if it's ACTUALLY visible
  2288. if (isIE) {
  2289. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2290. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2291. } else { // The size of the plugin on Safari should be 0x0px
  2292. // so that the autorisation prompt is at the top
  2293. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2294. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2295. }
  2296. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2297. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2298. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2299. '<param name="pluginId" value="' +
  2300. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2301. '<param name="windowless" value="false" /> ' +
  2302. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2303. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2304. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2305. }
  2306. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2307. };
  2308. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2309. function (comName, plugName, installedCb, notInstalledCb) {
  2310. if (!isIE) {
  2311. var pluginArray = navigator.plugins;
  2312. for (var i = 0; i < pluginArray.length; i++) {
  2313. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2314. installedCb();
  2315. return;
  2316. }
  2317. }
  2318. notInstalledCb();
  2319. } else {
  2320. try {
  2321. var axo = new ActiveXObject(comName + '.' + plugName);
  2322. } catch (e) {
  2323. notInstalledCb();
  2324. return;
  2325. }
  2326. installedCb();
  2327. }
  2328. };
  2329. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2330. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2331. AdapterJS.isDefined = function (variable) {
  2332. return variable !== null && variable !== undefined;
  2333. };
  2334. createIceServer = function (url, username, password) {
  2335. var iceServer = null;
  2336. var url_parts = url.split(':');
  2337. if (url_parts[0].indexOf('stun') === 0) {
  2338. iceServer = {
  2339. 'url' : url,
  2340. 'hasCredentials' : false
  2341. };
  2342. } else if (url_parts[0].indexOf('turn') === 0) {
  2343. iceServer = {
  2344. 'url' : url,
  2345. 'hasCredentials' : true,
  2346. 'credential' : password,
  2347. 'username' : username
  2348. };
  2349. }
  2350. return iceServer;
  2351. };
  2352. createIceServers = function (urls, username, password) {
  2353. var iceServers = [];
  2354. for (var i = 0; i < urls.length; ++i) {
  2355. iceServers.push(createIceServer(urls[i], username, password));
  2356. }
  2357. return iceServers;
  2358. };
  2359. RTCSessionDescription = function (info) {
  2360. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2361. return AdapterJS.WebRTCPlugin.plugin.
  2362. ConstructSessionDescription(info.type, info.sdp);
  2363. };
  2364. RTCPeerConnection = function (servers, constraints) {
  2365. var iceServers = null;
  2366. if (servers) {
  2367. iceServers = servers.iceServers;
  2368. for (var i = 0; i < iceServers.length; i++) {
  2369. if (iceServers[i].urls && !iceServers[i].url) {
  2370. iceServers[i].url = iceServers[i].urls;
  2371. }
  2372. iceServers[i].hasCredentials = AdapterJS.
  2373. isDefined(iceServers[i].username) &&
  2374. AdapterJS.isDefined(iceServers[i].credential);
  2375. }
  2376. }
  2377. var mandatory = (constraints && constraints.mandatory) ?
  2378. constraints.mandatory : null;
  2379. var optional = (constraints && constraints.optional) ?
  2380. constraints.optional : null;
  2381. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2382. return AdapterJS.WebRTCPlugin.plugin.
  2383. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2384. iceServers, mandatory, optional);
  2385. };
  2386. MediaStreamTrack = {};
  2387. MediaStreamTrack.getSources = function (callback) {
  2388. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2389. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2390. });
  2391. };
  2392. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2393. constraints.audio = constraints.audio || false;
  2394. constraints.video = constraints.video || false;
  2395. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2396. AdapterJS.WebRTCPlugin.plugin.
  2397. getUserMedia(constraints, successCallback, failureCallback);
  2398. });
  2399. };
  2400. window.navigator.getUserMedia = window.getUserMedia;
  2401. attachMediaStream = function (element, stream) {
  2402. if (!element || !element.parentNode) {
  2403. return;
  2404. }
  2405. var streamId
  2406. if (stream === null) {
  2407. streamId = '';
  2408. }
  2409. else {
  2410. stream.enableSoundTracks(true);
  2411. streamId = stream.id;
  2412. }
  2413. if (element.nodeName.toLowerCase() !== 'audio') {
  2414. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2415. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2416. var frag = document.createDocumentFragment();
  2417. var temp = document.createElement('div');
  2418. var classHTML = '';
  2419. if (element.className) {
  2420. classHTML = 'class="' + element.className + '" ';
  2421. } else if (element.attributes && element.attributes['class']) {
  2422. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2423. }
  2424. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2425. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2426. '<param name="pluginId" value="' + elementId + '" /> ' +
  2427. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2428. '<param name="windowless" value="true" /> ' +
  2429. '<param name="streamId" value="' + streamId + '" /> ' +
  2430. '</object>';
  2431. while (temp.firstChild) {
  2432. frag.appendChild(temp.firstChild);
  2433. }
  2434. var height = '';
  2435. var width = '';
  2436. if (element.getBoundingClientRect) {
  2437. var rectObject = element.getBoundingClientRect();
  2438. width = rectObject.width + 'px';
  2439. height = rectObject.height + 'px';
  2440. }
  2441. else if (element.width) {
  2442. width = element.width;
  2443. height = element.height;
  2444. } else {
  2445. // TODO: What scenario could bring us here?
  2446. }
  2447. element.parentNode.insertBefore(frag, element);
  2448. frag = document.getElementById(elementId);
  2449. frag.width = width;
  2450. frag.height = height;
  2451. element.parentNode.removeChild(element);
  2452. } else {
  2453. var children = element.children;
  2454. for (var i = 0; i !== children.length; ++i) {
  2455. if (children[i].name === 'streamId') {
  2456. children[i].value = streamId;
  2457. break;
  2458. }
  2459. }
  2460. element.setStreamId(streamId);
  2461. }
  2462. var newElement = document.getElementById(elementId);
  2463. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2464. if (isIE) { // on IE the event needs to be plugged manually
  2465. newElement.attachEvent('onplaying', newElement.onplaying);
  2466. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2467. newElement._TemOnClick = function (id) {
  2468. var arg = {
  2469. srcElement : document.getElementById(id)
  2470. };
  2471. newElement.onclick(arg);
  2472. };
  2473. }
  2474. return newElement;
  2475. } else {
  2476. return element;
  2477. }
  2478. };
  2479. reattachMediaStream = function (to, from) {
  2480. var stream = null;
  2481. var children = from.children;
  2482. for (var i = 0; i !== children.length; ++i) {
  2483. if (children[i].name === 'streamId') {
  2484. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2485. stream = AdapterJS.WebRTCPlugin.plugin
  2486. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2487. break;
  2488. }
  2489. }
  2490. if (stream !== null) {
  2491. return attachMediaStream(to, stream);
  2492. } else {
  2493. console.log('Could not find the stream associated with this element');
  2494. }
  2495. };
  2496. RTCIceCandidate = function (candidate) {
  2497. if (!candidate.sdpMid) {
  2498. candidate.sdpMid = '';
  2499. }
  2500. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2501. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2502. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2503. );
  2504. };
  2505. // inject plugin
  2506. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2507. AdapterJS.WebRTCPlugin.injectPlugin();
  2508. };
  2509. // This function will be called if the plugin is needed (browser different
  2510. // from Chrome or Firefox), but the plugin is not installed.
  2511. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2512. function() {
  2513. AdapterJS.addEvent(document,
  2514. 'readystatechange',
  2515. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2516. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2517. };
  2518. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2519. if (AdapterJS.options.hidePluginInstallPrompt) {
  2520. return;
  2521. }
  2522. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2523. if(downloadLink) { // if download link
  2524. var popupString;
  2525. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2526. popupString = 'This website requires you to install the ' +
  2527. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2528. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2529. ' WebRTC Plugin</a>' +
  2530. ' to work on this browser.';
  2531. } else { // no portal link, just print a generic explanation
  2532. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2533. }
  2534. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2535. } else { // no download link, just print a generic explanation
  2536. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2537. }
  2538. };
  2539. // Try to detect the plugin and act accordingly
  2540. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2541. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2542. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2543. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2544. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2545. }
  2546. (function () {
  2547. 'use strict';
  2548. var baseGetUserMedia = null;
  2549. AdapterJS.TEXT.EXTENSION = {
  2550. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2551. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2552. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2553. BUTTON_FF: 'Install Now',
  2554. BUTTON_CHROME: 'Go to Chrome Web Store'
  2555. };
  2556. var clone = function(obj) {
  2557. if (null == obj || "object" != typeof obj) return obj;
  2558. var copy = obj.constructor();
  2559. for (var attr in obj) {
  2560. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2561. }
  2562. return copy;
  2563. };
  2564. if (window.navigator.mozGetUserMedia) {
  2565. baseGetUserMedia = window.navigator.getUserMedia;
  2566. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2567. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2568. // intercepting screensharing requests
  2569. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2570. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2571. }
  2572. var updatedConstraints = clone(constraints);
  2573. //constraints.video.mediaSource = constraints.video.mediaSource;
  2574. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2575. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2576. // strange but this works anyway
  2577. var checkIfReady = setInterval(function () {
  2578. if (document.readyState === 'complete') {
  2579. clearInterval(checkIfReady);
  2580. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2581. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2582. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2583. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2584. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2585. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2586. } else {
  2587. failureCb(error);
  2588. }
  2589. });
  2590. }
  2591. }, 1);
  2592. } else { // regular GetUserMediaRequest
  2593. baseGetUserMedia(constraints, successCb, failureCb);
  2594. }
  2595. };
  2596. getUserMedia = navigator.getUserMedia;
  2597. } else if (window.navigator.webkitGetUserMedia) {
  2598. baseGetUserMedia = window.navigator.getUserMedia;
  2599. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2600. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2601. if (window.webrtcDetectedBrowser !== 'chrome') {
  2602. throw new Error('Current browser does not support screensharing');
  2603. }
  2604. // would be fine since no methods
  2605. var updatedConstraints = clone(constraints);
  2606. var chromeCallback = function(error, sourceId) {
  2607. if(!error) {
  2608. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2609. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2610. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2611. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2612. if (sourceId) {
  2613. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2614. }
  2615. delete updatedConstraints.video.mediaSource;
  2616. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2617. } else {
  2618. if (error === 'permission-denied') {
  2619. throw new Error('Permission denied for screen retrieval');
  2620. } else {
  2621. throw new Error('Failed retrieving selected screen');
  2622. }
  2623. }
  2624. };
  2625. var onIFrameCallback = function (event) {
  2626. if (!event.data) {
  2627. return;
  2628. }
  2629. if (event.data.chromeMediaSourceId) {
  2630. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2631. chromeCallback('permission-denied');
  2632. } else {
  2633. chromeCallback(null, event.data.chromeMediaSourceId);
  2634. }
  2635. }
  2636. if (event.data.chromeExtensionStatus) {
  2637. if (event.data.chromeExtensionStatus === 'not-installed') {
  2638. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2639. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2640. event.data.data, true, true);
  2641. } else {
  2642. chromeCallback(event.data.chromeExtensionStatus, null);
  2643. }
  2644. }
  2645. // this event listener is no more needed
  2646. window.removeEventListener('message', onIFrameCallback);
  2647. };
  2648. window.addEventListener('message', onIFrameCallback);
  2649. postFrameMessage({
  2650. captureSourceId: true
  2651. });
  2652. } else {
  2653. baseGetUserMedia(constraints, successCb, failureCb);
  2654. }
  2655. };
  2656. getUserMedia = navigator.getUserMedia;
  2657. } else {
  2658. baseGetUserMedia = window.navigator.getUserMedia;
  2659. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2660. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2661. // would be fine since no methods
  2662. var updatedConstraints = clone(constraints);
  2663. // wait for plugin to be ready
  2664. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2665. // check if screensharing feature is available
  2666. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2667. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2668. // set the constraints
  2669. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2670. updatedConstraints.video.optional.push({
  2671. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2672. });
  2673. delete updatedConstraints.video.mediaSource;
  2674. } else {
  2675. throw new Error('Your WebRTC plugin does not support screensharing');
  2676. }
  2677. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2678. });
  2679. } else {
  2680. baseGetUserMedia(constraints, successCb, failureCb);
  2681. }
  2682. };
  2683. getUserMedia = window.navigator.getUserMedia;
  2684. }
  2685. if (window.webrtcDetectedBrowser === 'chrome') {
  2686. var iframe = document.createElement('iframe');
  2687. iframe.onload = function() {
  2688. iframe.isLoaded = true;
  2689. };
  2690. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2691. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2692. iframe.style.display = 'none';
  2693. (document.body || document.documentElement).appendChild(iframe);
  2694. var postFrameMessage = function (object) {
  2695. object = object || {};
  2696. if (!iframe.isLoaded) {
  2697. setTimeout(function () {
  2698. iframe.contentWindow.postMessage(object, '*');
  2699. }, 100);
  2700. return;
  2701. }
  2702. iframe.contentWindow.postMessage(object, '*');
  2703. };
  2704. }
  2705. })();
  2706. },{}],11:[function(require,module,exports){
  2707. var UI = {};
  2708. var VideoLayout = require("./videolayout/VideoLayout.js");
  2709. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2710. var Prezi = require("./prezi/Prezi.js");
  2711. var Etherpad = require("./etherpad/Etherpad.js");
  2712. var Chat = require("./side_pannels/chat/Chat.js");
  2713. var Toolbar = require("./toolbars/Toolbar");
  2714. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2715. var BottomToolbar = require("./toolbars/BottomToolbar");
  2716. var ContactList = require("./side_pannels/contactlist/ContactList");
  2717. var Avatar = require("./avatar/Avatar");
  2718. var EventEmitter = require("events");
  2719. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2720. var Settings = require("./../settings/Settings");
  2721. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2722. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2723. UI.messageHandler = require("./util/MessageHandler");
  2724. var messageHandler = UI.messageHandler;
  2725. var Authentication = require("./authentication/Authentication");
  2726. var UIUtil = require("./util/UIUtil");
  2727. var NicknameHandler = require("./util/NicknameHandler");
  2728. var CQEvents = require("../../service/connectionquality/CQEvents");
  2729. var DesktopSharingEventTypes
  2730. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2731. var RTCEvents = require("../../service/RTC/RTCEvents");
  2732. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2733. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2734. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2735. var MemberEvents = require("../../service/members/Events");
  2736. var eventEmitter = new EventEmitter();
  2737. var roomName = null;
  2738. function promptDisplayName() {
  2739. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2740. message += APP.translation.translateString(
  2741. "dialog.displayNameRequired");
  2742. message += '</h2>' +
  2743. '<input name="displayName" type="text" data-i18n=' +
  2744. '"[placeholder]defaultNickname" placeholder="' +
  2745. APP.translation.translateString(
  2746. "defaultNickname", {name: "Jane Pink"}) +
  2747. '" autofocus>';
  2748. var buttonTxt
  2749. = APP.translation.generateTranslationHTML("dialog.Ok");
  2750. var buttons = [];
  2751. buttons.push({title: buttonTxt, value: "ok"});
  2752. messageHandler.openDialog(null, message,
  2753. true,
  2754. buttons,
  2755. function (e, v, m, f) {
  2756. if (v == "ok") {
  2757. var displayName = f.displayName;
  2758. if (displayName) {
  2759. VideoLayout.inputDisplayNameHandler(displayName);
  2760. return true;
  2761. }
  2762. }
  2763. e.preventDefault();
  2764. },
  2765. function () {
  2766. var form = $.prompt.getPrompt();
  2767. var input = form.find("input[name='displayName']");
  2768. input.focus();
  2769. var button = form.find("button");
  2770. button.attr("disabled", "disabled");
  2771. input.keyup(function () {
  2772. if(!input.val())
  2773. button.attr("disabled", "disabled");
  2774. else
  2775. button.removeAttr("disabled");
  2776. });
  2777. }
  2778. );
  2779. }
  2780. function notifyForInitialMute()
  2781. {
  2782. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2783. "notify.muted", null, {timeOut: 120000});
  2784. }
  2785. function setupPrezi()
  2786. {
  2787. $("#reloadPresentationLink").click(function()
  2788. {
  2789. Prezi.reloadPresentation();
  2790. });
  2791. }
  2792. function setupChat()
  2793. {
  2794. Chat.init();
  2795. $("#toggle_smileys").click(function() {
  2796. Chat.toggleSmileys();
  2797. });
  2798. }
  2799. function setupToolbars() {
  2800. Toolbar.init(UI);
  2801. Toolbar.setupButtonsFromConfig();
  2802. BottomToolbar.init();
  2803. }
  2804. function streamHandler(stream, isMuted) {
  2805. switch (stream.type)
  2806. {
  2807. case "audio":
  2808. VideoLayout.changeLocalAudio(stream, isMuted);
  2809. break;
  2810. case "video":
  2811. VideoLayout.changeLocalVideo(stream, isMuted);
  2812. break;
  2813. case "stream":
  2814. VideoLayout.changeLocalStream(stream, isMuted);
  2815. break;
  2816. }
  2817. }
  2818. function onXmppConnectionFailed(stropheErrorMsg) {
  2819. var title = APP.translation.generateTranslationHTML(
  2820. "dialog.error");
  2821. var message;
  2822. if (stropheErrorMsg) {
  2823. message = APP.translation.generateTranslationHTML(
  2824. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2825. } else {
  2826. message = APP.translation.generateTranslationHTML(
  2827. "dialog.connectError");
  2828. }
  2829. messageHandler.openDialog(
  2830. title, message, true, {}, function (e, v, m, f) { return false; });
  2831. }
  2832. function onDisposeConference(unload) {
  2833. Toolbar.showAuthenticateButton(false);
  2834. }
  2835. function onDisplayNameChanged(jid, displayName) {
  2836. ContactList.onDisplayNameChange(jid, displayName);
  2837. SettingsMenu.onDisplayNameChange(jid, displayName);
  2838. VideoLayout.onDisplayNameChanged(jid, displayName);
  2839. }
  2840. function registerListeners() {
  2841. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2842. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2843. APP.RTC.addStreamListener(function (stream) {
  2844. VideoLayout.onRemoteStreamAdded(stream);
  2845. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2846. APP.RTC.addStreamListener(function (jid) {
  2847. VideoLayout.onVideoTypeChanged(jid);
  2848. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  2849. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2850. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  2851. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2852. });
  2853. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2854. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2855. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2856. endpointsEnteringLastN, stream);
  2857. });
  2858. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2859. function (devices) {
  2860. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2861. })
  2862. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  2863. {
  2864. var resourceJid;
  2865. if(jid === APP.statistics.LOCAL_JID)
  2866. {
  2867. resourceJid = AudioLevels.LOCAL_LEVEL;
  2868. if(APP.RTC.localAudio.isMuted())
  2869. {
  2870. audioLevel = 0;
  2871. }
  2872. }
  2873. else
  2874. {
  2875. resourceJid = Strophe.getResourceFromJid(jid);
  2876. }
  2877. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2878. UI.getLargeVideoJid());
  2879. });
  2880. APP.desktopsharing.addListener(function () {
  2881. ToolbarToggler.showDesktopSharingButton();
  2882. }, DesktopSharingEventTypes.INIT);
  2883. APP.desktopsharing.addListener(
  2884. Toolbar.changeDesktopSharingButtonState,
  2885. DesktopSharingEventTypes.SWITCHING_DONE);
  2886. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2887. VideoLayout.updateLocalConnectionStats);
  2888. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2889. VideoLayout.updateConnectionStats);
  2890. APP.connectionquality.addListener(CQEvents.STOP,
  2891. VideoLayout.onStatsStop);
  2892. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2893. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2894. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2895. messageHandler.openMessageDialog(
  2896. 'dialog.serviceUnavailable',
  2897. 'dialog.gracefulShutdown'
  2898. );
  2899. });
  2900. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2901. var title = APP.translation.generateTranslationHTML(
  2902. "dialog.reservationError");
  2903. var message = APP.translation.generateTranslationHTML(
  2904. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2905. messageHandler.openDialog(
  2906. title,
  2907. message,
  2908. true, {},
  2909. function (event, value, message, formVals)
  2910. {
  2911. return false;
  2912. }
  2913. );
  2914. });
  2915. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2916. messageHandler.openMessageDialog("dialog.sessTerminated",
  2917. "dialog.kickMessage");
  2918. });
  2919. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2920. //FIXME: use Session Terminated from translation, but
  2921. // 'reason' text comes from XMPP packet and is not translated
  2922. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2923. messageHandler.openDialog(
  2924. title, reason, true, {},
  2925. function (event, value, message, formVals)
  2926. {
  2927. return false;
  2928. }
  2929. );
  2930. });
  2931. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2932. messageHandler.showError("dialog.error",
  2933. "dialog.bridgeUnavailable");
  2934. });
  2935. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2936. Avatar.setUserAvatar(from, id);
  2937. });
  2938. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2939. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2940. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2941. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2942. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2943. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2944. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2945. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2946. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2947. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2948. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2949. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2950. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2951. onAuthenticationRequired);
  2952. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2953. function (resource, devices) {
  2954. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2955. });
  2956. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  2957. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  2958. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2959. onDtmfSupportChanged);
  2960. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  2961. SettingsMenu.setStartMuted(audio, video);
  2962. });
  2963. }
  2964. /**
  2965. * Mutes/unmutes the local video.
  2966. *
  2967. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2968. * @param options an object which specifies optional arguments such as the
  2969. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2970. * specifies whether the method was initiated in response to a user command (in
  2971. * contrast to an automatic decision taken by the application logic)
  2972. */
  2973. function setVideoMute(mute, options) {
  2974. APP.RTC.setVideoMute(mute,
  2975. UI.setVideoMuteButtonsState,
  2976. options);
  2977. }
  2978. function onResize()
  2979. {
  2980. Chat.resizeChat();
  2981. VideoLayout.resizeLargeVideoContainer();
  2982. }
  2983. function bindEvents()
  2984. {
  2985. /**
  2986. * Resizes and repositions videos in full screen mode.
  2987. */
  2988. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  2989. onResize);
  2990. $(window).resize(onResize);
  2991. }
  2992. UI.start = function (init) {
  2993. document.title = interfaceConfig.APP_NAME;
  2994. if(config.enableWelcomePage && window.location.pathname == "/" &&
  2995. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  2996. {
  2997. $("#videoconference_page").hide();
  2998. var setupWelcomePage = require("./welcome_page/WelcomePage");
  2999. setupWelcomePage();
  3000. return;
  3001. }
  3002. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  3003. var leftWatermarkDiv
  3004. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  3005. leftWatermarkDiv.css({display: 'block'});
  3006. leftWatermarkDiv.parent().get(0).href
  3007. = interfaceConfig.JITSI_WATERMARK_LINK;
  3008. }
  3009. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  3010. var rightWatermarkDiv
  3011. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  3012. rightWatermarkDiv.css({display: 'block'});
  3013. rightWatermarkDiv.parent().get(0).href
  3014. = interfaceConfig.BRAND_WATERMARK_LINK;
  3015. rightWatermarkDiv.get(0).style.backgroundImage
  3016. = "url(images/rightwatermark.png)";
  3017. }
  3018. if (interfaceConfig.SHOW_POWERED_BY) {
  3019. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  3020. }
  3021. $("#welcome_page").hide();
  3022. $("#videospace").mousemove(function () {
  3023. return ToolbarToggler.showToolbar();
  3024. });
  3025. // Set the defaults for prompt dialogs.
  3026. jQuery.prompt.setDefaults({persistent: false});
  3027. VideoLayout.init(eventEmitter);
  3028. AudioLevels.init();
  3029. NicknameHandler.init(eventEmitter);
  3030. registerListeners();
  3031. bindEvents();
  3032. setupPrezi();
  3033. setupToolbars();
  3034. setupChat();
  3035. document.title = interfaceConfig.APP_NAME;
  3036. $("#downloadlog").click(function (event) {
  3037. dump(event.target);
  3038. });
  3039. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3040. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3041. {
  3042. $("#videoconference_page").hide();
  3043. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3044. setupWelcomePage();
  3045. return;
  3046. }
  3047. $("#welcome_page").hide();
  3048. // Display notice message at the top of the toolbar
  3049. if (config.noticeMessage) {
  3050. $('#noticeText').text(config.noticeMessage);
  3051. $('#notice').css({display: 'block'});
  3052. }
  3053. if (!RTCBrowserType.isIExplorer()) {
  3054. document.getElementById('largeVideo').volume = 0;
  3055. }
  3056. if(config.requireDisplayName) {
  3057. var currentSettings = Settings.getSettings();
  3058. if (!currentSettings.displayName) {
  3059. promptDisplayName();
  3060. }
  3061. }
  3062. init();
  3063. toastr.options = {
  3064. "closeButton": true,
  3065. "debug": false,
  3066. "positionClass": "notification-bottom-right",
  3067. "onclick": null,
  3068. "showDuration": "300",
  3069. "hideDuration": "1000",
  3070. "timeOut": "2000",
  3071. "extendedTimeOut": "1000",
  3072. "showEasing": "swing",
  3073. "hideEasing": "linear",
  3074. "showMethod": "fadeIn",
  3075. "hideMethod": "fadeOut",
  3076. "reposition": function() {
  3077. if(PanelToggler.isVisible()) {
  3078. $("#toast-container").addClass("notification-bottom-right-center");
  3079. } else {
  3080. $("#toast-container").removeClass("notification-bottom-right-center");
  3081. }
  3082. },
  3083. "newestOnTop": false
  3084. };
  3085. SettingsMenu.init();
  3086. };
  3087. function chatAddError(errorMessage, originalText)
  3088. {
  3089. return Chat.chatAddError(errorMessage, originalText);
  3090. };
  3091. function chatSetSubject(text)
  3092. {
  3093. return Chat.chatSetSubject(text);
  3094. };
  3095. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3096. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3097. }
  3098. function onMucJoined(jid, info) {
  3099. Toolbar.updateRoomUrl(window.location.href);
  3100. var meHTML = APP.translation.generateTranslationHTML("me");
  3101. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3102. var settings = Settings.getSettings();
  3103. // Add myself to the contact list.
  3104. ContactList.addContact(jid, settings.email || settings.uid);
  3105. // Once we've joined the muc show the toolbar
  3106. ToolbarToggler.showToolbar();
  3107. var displayName = !config.displayJids
  3108. ? info.displayName : Strophe.getResourceFromJid(jid);
  3109. if (displayName)
  3110. onDisplayNameChanged('localVideoContainer', displayName);
  3111. VideoLayout.mucJoined();
  3112. }
  3113. function initEtherpad(name) {
  3114. Etherpad.init(name);
  3115. }
  3116. function onMucMemberLeft(jid) {
  3117. console.log('left.muc', jid);
  3118. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3119. '>.displayname').html();
  3120. messageHandler.notify(displayName,'notify.somebody',
  3121. 'disconnected',
  3122. 'notify.disconnected');
  3123. if(!config.startAudioMuted ||
  3124. config.startAudioMuted > APP.members.size())
  3125. UIUtil.playSoundNotification('userLeft');
  3126. // Need to call this with a slight delay, otherwise the element couldn't be
  3127. // found for some reason.
  3128. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  3129. window.setTimeout(function () {
  3130. var container = document.getElementById(
  3131. 'participant_' + Strophe.getResourceFromJid(jid));
  3132. if (container) {
  3133. ContactList.removeContact(jid);
  3134. VideoLayout.removeConnectionIndicator(jid);
  3135. // hide here, wait for video to close before removing
  3136. $(container).hide();
  3137. VideoLayout.resizeThumbnails();
  3138. }
  3139. }, 10);
  3140. VideoLayout.participantLeft(jid);
  3141. };
  3142. function onLocalRoleChanged(jid, info, pres, isModerator)
  3143. {
  3144. console.info("My role changed, new role: " + info.role);
  3145. onModeratorStatusChanged(isModerator);
  3146. VideoLayout.showModeratorIndicator();
  3147. SettingsMenu.onRoleChanged();
  3148. if (isModerator) {
  3149. Authentication.closeAuthenticationWindow();
  3150. messageHandler.notify(null, "notify.me",
  3151. 'connected', "notify.moderator");
  3152. }
  3153. }
  3154. function onModeratorStatusChanged(isModerator) {
  3155. Toolbar.showSipCallButton(isModerator);
  3156. Toolbar.showRecordingButton(
  3157. isModerator); //&&
  3158. // FIXME:
  3159. // Recording visible if
  3160. // there are at least 2(+ 1 focus) participants
  3161. //Object.keys(connection.emuc.members).length >= 3);
  3162. }
  3163. function onPasswordRequired(callback) {
  3164. // password is required
  3165. Toolbar.lockLockButton();
  3166. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3167. message += APP.translation.translateString(
  3168. "dialog.passwordRequired");
  3169. message += '</h2>' +
  3170. '<input name="lockKey" type="text" data-i18n=' +
  3171. '"[placeholder]dialog.password" placeholder="' +
  3172. APP.translation.translateString("dialog.password") +
  3173. '" autofocus>';
  3174. messageHandler.openTwoButtonDialog(null, null, null, message,
  3175. true,
  3176. "dialog.Ok",
  3177. function (e, v, m, f) {},
  3178. null,
  3179. function (e, v, m, f) {
  3180. if (v) {
  3181. var lockKey = f.lockKey;
  3182. if (lockKey) {
  3183. Toolbar.setSharedKey(lockKey);
  3184. callback(lockKey);
  3185. }
  3186. }
  3187. },
  3188. ':input:first'
  3189. );
  3190. }
  3191. /**
  3192. * The dialpad button is shown iff there is at least one member that supports
  3193. * DTMF (e.g. jigasi).
  3194. */
  3195. function onDtmfSupportChanged(dtmfSupport) {
  3196. //TODO: enable when the UI is ready
  3197. //Toolbar.showDialPadButton(dtmfSupport);
  3198. }
  3199. function onMucMemberJoined(jid, id, displayName) {
  3200. messageHandler.notify(displayName,'notify.somebody',
  3201. 'connected',
  3202. 'notify.connected');
  3203. if(!config.startAudioMuted ||
  3204. config.startAudioMuted > APP.members.size())
  3205. UIUtil.playSoundNotification('userJoined');
  3206. // Add Peer's container
  3207. VideoLayout.ensurePeerContainerExists(jid,id);
  3208. }
  3209. function onMucPresenceStatus(jid, info) {
  3210. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3211. }
  3212. function onMucRoleChanged(role, displayName) {
  3213. VideoLayout.showModeratorIndicator();
  3214. if (role === 'moderator') {
  3215. var messageKey, messageOptions = {};
  3216. if (!displayName) {
  3217. messageKey = "notify.grantedToUnknown";
  3218. }
  3219. else
  3220. {
  3221. messageKey = "notify.grantedTo";
  3222. messageOptions = {to: displayName};
  3223. }
  3224. messageHandler.notify(
  3225. displayName,'notify.somebody',
  3226. 'connected', messageKey,
  3227. messageOptions);
  3228. }
  3229. }
  3230. function onAuthenticationRequired(intervalCallback) {
  3231. Authentication.openAuthenticationDialog(
  3232. roomName, intervalCallback, function () {
  3233. Toolbar.authenticateClicked();
  3234. });
  3235. };
  3236. function onLastNChanged(oldValue, newValue) {
  3237. if (config.muteLocalVideoIfNotInLastN) {
  3238. setVideoMute(!newValue, { 'byUser': false });
  3239. }
  3240. }
  3241. UI.toggleSmileys = function () {
  3242. Chat.toggleSmileys();
  3243. };
  3244. UI.getSettings = function () {
  3245. return Settings.getSettings();
  3246. };
  3247. UI.toggleFilmStrip = function () {
  3248. return BottomToolbar.toggleFilmStrip();
  3249. };
  3250. UI.toggleChat = function () {
  3251. return BottomToolbar.toggleChat();
  3252. };
  3253. UI.toggleContactList = function () {
  3254. return BottomToolbar.toggleContactList();
  3255. };
  3256. UI.inputDisplayNameHandler = function (value) {
  3257. VideoLayout.inputDisplayNameHandler(value);
  3258. };
  3259. UI.getLargeVideoJid = function()
  3260. {
  3261. return VideoLayout.getLargeVideoJid();
  3262. };
  3263. UI.generateRoomName = function() {
  3264. if(roomName)
  3265. return roomName;
  3266. var roomnode = null;
  3267. var path = window.location.pathname;
  3268. // determinde the room node from the url
  3269. // TODO: just the roomnode or the whole bare jid?
  3270. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3271. // custom function might be responsible for doing the pushstate
  3272. roomnode = config.getroomnode(path);
  3273. } else {
  3274. /* fall back to default strategy
  3275. * this is making assumptions about how the URL->room mapping happens.
  3276. * It currently assumes deployment at root, with a rewrite like the
  3277. * following one (for nginx):
  3278. location ~ ^/([a-zA-Z0-9]+)$ {
  3279. rewrite ^/(.*)$ / break;
  3280. }
  3281. */
  3282. if (path.length > 1) {
  3283. roomnode = path.substr(1).toLowerCase();
  3284. } else {
  3285. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3286. roomnode = word.toLowerCase();
  3287. window.history.pushState('VideoChat',
  3288. 'Room: ' + word, window.location.pathname + word);
  3289. }
  3290. }
  3291. roomName = roomnode + '@' + config.hosts.muc;
  3292. return roomName;
  3293. };
  3294. UI.connectionIndicatorShowMore = function(jid)
  3295. {
  3296. return VideoLayout.showMore(jid);
  3297. };
  3298. UI.showLoginPopup = function(callback)
  3299. {
  3300. console.log('password is required');
  3301. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3302. message += APP.translation.translateString(
  3303. "dialog.passwordRequired");
  3304. message += '</h2>' +
  3305. '<input name="username" type="text" ' +
  3306. 'placeholder="user@domain.net" autofocus>' +
  3307. '<input name="password" ' +
  3308. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3309. ' placeholder="user password">';
  3310. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3311. true,
  3312. "dialog.Ok",
  3313. function (e, v, m, f) {
  3314. if (v) {
  3315. if (f.username !== null && f.password != null) {
  3316. callback(f.username, f.password);
  3317. }
  3318. }
  3319. },
  3320. null, null, ':input:first'
  3321. );
  3322. }
  3323. UI.checkForNicknameAndJoin = function () {
  3324. Authentication.closeAuthenticationDialog();
  3325. Authentication.stopInterval();
  3326. var nick = null;
  3327. if (config.useNicks) {
  3328. nick = window.prompt('Your nickname (optional)');
  3329. }
  3330. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3331. };
  3332. function dump(elem, filename) {
  3333. elem = elem.parentNode;
  3334. elem.download = filename || 'meetlog.json';
  3335. elem.href = 'data:application/json;charset=utf-8,\n';
  3336. var data = APP.xmpp.populateData();
  3337. var metadata = {};
  3338. metadata.time = new Date();
  3339. metadata.url = window.location.href;
  3340. metadata.ua = navigator.userAgent;
  3341. var log = APP.xmpp.getLogger();
  3342. if (log) {
  3343. metadata.xmpp = log;
  3344. }
  3345. data.metadata = metadata;
  3346. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3347. return false;
  3348. }
  3349. UI.getRoomName = function () {
  3350. return roomName;
  3351. };
  3352. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3353. if(muteAudio || muteVideo) notifyForInitialMute();
  3354. if(muteAudio) UI.setAudioMuted(true);
  3355. if(muteVideo) UI.setVideoMute(true);
  3356. }
  3357. /**
  3358. * Mutes/unmutes the local video.
  3359. */
  3360. UI.toggleVideo = function () {
  3361. setVideoMute(!APP.RTC.localVideo.isMuted());
  3362. };
  3363. /**
  3364. * Mutes / unmutes audio for the local participant.
  3365. */
  3366. UI.toggleAudio = function() {
  3367. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3368. };
  3369. /**
  3370. * Sets muted audio state for the local participant.
  3371. */
  3372. UI.setAudioMuted = function (mute, earlyMute) {
  3373. var audioMute = null;
  3374. if(earlyMute)
  3375. audioMute = function (mute, cb) {
  3376. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3377. };
  3378. else
  3379. audioMute = function (mute, cb) {
  3380. return APP.xmpp.setAudioMute(mute, cb);
  3381. }
  3382. if(!audioMute(mute, function () {
  3383. VideoLayout.showLocalAudioIndicator(mute);
  3384. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3385. }))
  3386. {
  3387. // We still click the button.
  3388. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3389. return;
  3390. }
  3391. }
  3392. UI.addListener = function (type, listener) {
  3393. eventEmitter.on(type, listener);
  3394. }
  3395. UI.clickOnVideo = function (videoNumber) {
  3396. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3397. if (remoteVideos.length > videoNumber) {
  3398. remoteVideos[videoNumber].click();
  3399. }
  3400. }
  3401. //Used by torture
  3402. UI.showToolbar = function () {
  3403. return ToolbarToggler.showToolbar();
  3404. }
  3405. //Used by torture
  3406. UI.dockToolbar = function (isDock) {
  3407. return ToolbarToggler.dockToolbar(isDock);
  3408. }
  3409. UI.setVideoMuteButtonsState = function (mute) {
  3410. var video = $('#video');
  3411. var communicativeClass = "icon-camera";
  3412. var muteClass = "icon-camera icon-camera-disabled";
  3413. if (mute) {
  3414. video.removeClass(communicativeClass);
  3415. video.addClass(muteClass);
  3416. } else {
  3417. video.removeClass(muteClass);
  3418. video.addClass(communicativeClass);
  3419. }
  3420. }
  3421. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3422. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3423. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3424. if(resourceJid === APP.xmpp.myResource())
  3425. SettingsMenu.changeAvatar(thumbUrl);
  3426. }
  3427. UI.setVideoMute = setVideoMute;
  3428. module.exports = UI;
  3429. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes":101,"../../service/connectionquality/CQEvents":104,"../../service/desktopsharing/DesktopSharingEventTypes":105,"../../service/members/Events":106,"../../service/xmpp/XMPPEvents":108,"../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/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":109}],12:[function(require,module,exports){
  3430. var CanvasUtil = require("./CanvasUtils");
  3431. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3432. function initActiveSpeakerAudioLevels() {
  3433. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3434. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3435. // Draw a circle.
  3436. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3437. // Add a shadow around the circle
  3438. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3439. ASDrawContext.shadowOffsetX = 0;
  3440. ASDrawContext.shadowOffsetY = 0;
  3441. }
  3442. /**
  3443. * The audio Levels plugin.
  3444. */
  3445. var AudioLevels = (function(my) {
  3446. var audioLevelCanvasCache = {};
  3447. my.LOCAL_LEVEL = 'local';
  3448. my.init = function () {
  3449. initActiveSpeakerAudioLevels();
  3450. }
  3451. /**
  3452. * Updates the audio level canvas for the given peerJid. If the canvas
  3453. * didn't exist we create it.
  3454. */
  3455. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3456. var resourceJid = null;
  3457. var videoSpanId = null;
  3458. if (!peerJid)
  3459. videoSpanId = 'localVideoContainer';
  3460. else {
  3461. resourceJid = Strophe.getResourceFromJid(peerJid);
  3462. videoSpanId = 'participant_' + resourceJid;
  3463. }
  3464. var videoSpan = document.getElementById(videoSpanId);
  3465. if (!videoSpan) {
  3466. if (resourceJid)
  3467. console.error("No video element for jid", resourceJid);
  3468. else
  3469. console.error("No video element for local video.");
  3470. return;
  3471. }
  3472. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3473. var videoSpaceWidth = $('#remoteVideos').width();
  3474. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3475. var thumbnailWidth = thumbnailSize[0];
  3476. var thumbnailHeight = thumbnailSize[1];
  3477. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3478. audioLevelCanvas = document.createElement('canvas');
  3479. audioLevelCanvas.className = "audiolevel";
  3480. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3481. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3482. resizeAudioLevelCanvas( audioLevelCanvas,
  3483. thumbnailWidth,
  3484. thumbnailHeight);
  3485. videoSpan.appendChild(audioLevelCanvas);
  3486. } else {
  3487. audioLevelCanvas = audioLevelCanvas.get(0);
  3488. resizeAudioLevelCanvas( audioLevelCanvas,
  3489. thumbnailWidth,
  3490. thumbnailHeight);
  3491. }
  3492. };
  3493. /**
  3494. * Updates the audio level UI for the given resourceJid.
  3495. *
  3496. * @param resourceJid the resource jid indicating the video element for
  3497. * which we draw the audio level
  3498. * @param audioLevel the newAudio level to render
  3499. */
  3500. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3501. drawAudioLevelCanvas(resourceJid, audioLevel);
  3502. var videoSpanId = getVideoSpanId(resourceJid);
  3503. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3504. if (!audioLevelCanvas)
  3505. return;
  3506. var drawContext = audioLevelCanvas.getContext('2d');
  3507. var canvasCache = audioLevelCanvasCache[resourceJid];
  3508. drawContext.clearRect (0, 0,
  3509. audioLevelCanvas.width, audioLevelCanvas.height);
  3510. drawContext.drawImage(canvasCache, 0, 0);
  3511. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3512. if(!APP.xmpp.myJid()) {
  3513. return;
  3514. }
  3515. resourceJid = APP.xmpp.myResource();
  3516. }
  3517. if(resourceJid === largeVideoResourceJid) {
  3518. window.requestAnimationFrame(function () {
  3519. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3520. });
  3521. }
  3522. };
  3523. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3524. if($("#activeSpeaker").css("visibility") == "hidden")
  3525. return;
  3526. ASDrawContext.clearRect(0, 0, 300, 300);
  3527. if(audioLevel == 0)
  3528. return;
  3529. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3530. // Fill the shape.
  3531. ASDrawContext.fill();
  3532. };
  3533. /**
  3534. * Resizes the given audio level canvas to match the given thumbnail size.
  3535. */
  3536. function resizeAudioLevelCanvas(audioLevelCanvas,
  3537. thumbnailWidth,
  3538. thumbnailHeight) {
  3539. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3540. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3541. }
  3542. /**
  3543. * Draws the audio level canvas into the cached canvas object.
  3544. *
  3545. * @param resourceJid the resource jid indicating the video element for
  3546. * which we draw the audio level
  3547. * @param audioLevel the newAudio level to render
  3548. */
  3549. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3550. if (!audioLevelCanvasCache[resourceJid]) {
  3551. var videoSpanId = getVideoSpanId(resourceJid);
  3552. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3553. /*
  3554. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3555. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3556. * error. Since audio levels are frequently updated, the errors have
  3557. * been observed to pile into the console, strain the CPU.
  3558. */
  3559. if (audioLevelCanvasOrig)
  3560. {
  3561. audioLevelCanvasCache[resourceJid]
  3562. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3563. }
  3564. }
  3565. var canvas = audioLevelCanvasCache[resourceJid];
  3566. if (!canvas)
  3567. return;
  3568. var drawContext = canvas.getContext('2d');
  3569. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3570. var shadowLevel = getShadowLevel(audioLevel);
  3571. if (shadowLevel > 0)
  3572. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3573. CanvasUtil.drawRoundRectGlow( drawContext,
  3574. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  3575. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3576. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3577. interfaceConfig.CANVAS_RADIUS,
  3578. interfaceConfig.SHADOW_COLOR,
  3579. shadowLevel);
  3580. }
  3581. /**
  3582. * Returns the shadow/glow level for the given audio level.
  3583. *
  3584. * @param audioLevel the audio level from which we determine the shadow
  3585. * level
  3586. */
  3587. function getShadowLevel (audioLevel) {
  3588. var shadowLevel = 0;
  3589. if (audioLevel <= 0.3) {
  3590. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3591. }
  3592. else if (audioLevel <= 0.6) {
  3593. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3594. }
  3595. else {
  3596. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3597. }
  3598. return shadowLevel;
  3599. }
  3600. /**
  3601. * Returns the video span id corresponding to the given resourceJid or local
  3602. * user.
  3603. */
  3604. function getVideoSpanId(resourceJid) {
  3605. var videoSpanId = null;
  3606. if (resourceJid === AudioLevels.LOCAL_LEVEL
  3607. || (APP.xmpp.myResource() && resourceJid
  3608. === APP.xmpp.myResource()))
  3609. videoSpanId = 'localVideoContainer';
  3610. else
  3611. videoSpanId = 'participant_' + resourceJid;
  3612. return videoSpanId;
  3613. }
  3614. /**
  3615. * Indicates that the remote video has been resized.
  3616. */
  3617. $(document).bind('remotevideo.resized', function (event, width, height) {
  3618. var resized = false;
  3619. $('#remoteVideos>span>canvas').each(function() {
  3620. var canvas = $(this).get(0);
  3621. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3622. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3623. resized = true;
  3624. }
  3625. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3626. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3627. resized = true;
  3628. }
  3629. });
  3630. if (resized)
  3631. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3632. audioLevelCanvasCache[resourceJid].width
  3633. = width + interfaceConfig.CANVAS_EXTRA;
  3634. audioLevelCanvasCache[resourceJid].height
  3635. = height + interfaceConfig.CANVAS_EXTRA;
  3636. });
  3637. });
  3638. return my;
  3639. })(AudioLevels || {});
  3640. module.exports = AudioLevels;
  3641. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3642. /**
  3643. * Utility class for drawing canvas shapes.
  3644. */
  3645. var CanvasUtil = (function(my) {
  3646. /**
  3647. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3648. * of the glow.
  3649. *
  3650. * @param drawContext the context of the canvas to draw to
  3651. * @param x the x coordinate of the round rectangle
  3652. * @param y the y coordinate of the round rectangle
  3653. * @param w the width of the round rectangle
  3654. * @param h the height of the round rectangle
  3655. * @param glowColor the color of the glow
  3656. * @param glowWidth the width of the glow
  3657. */
  3658. my.drawRoundRectGlow
  3659. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3660. // Save the previous state of the context.
  3661. drawContext.save();
  3662. if (w < 2 * r) r = w / 2;
  3663. if (h < 2 * r) r = h / 2;
  3664. // Draw a round rectangle.
  3665. drawContext.beginPath();
  3666. drawContext.moveTo(x+r, y);
  3667. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3668. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3669. drawContext.arcTo(x, y+h, x, y, r);
  3670. drawContext.arcTo(x, y, x+w, y, r);
  3671. drawContext.closePath();
  3672. // Add a shadow around the rectangle
  3673. drawContext.shadowColor = glowColor;
  3674. drawContext.shadowBlur = glowWidth;
  3675. drawContext.shadowOffsetX = 0;
  3676. drawContext.shadowOffsetY = 0;
  3677. // Fill the shape.
  3678. drawContext.fill();
  3679. drawContext.save();
  3680. drawContext.restore();
  3681. // 1) Uncomment this line to use Composite Operation, which is doing the
  3682. // same as the clip function below and is also antialiasing the round
  3683. // border, but is said to be less fast performance wise.
  3684. // drawContext.globalCompositeOperation='destination-out';
  3685. drawContext.beginPath();
  3686. drawContext.moveTo(x+r, y);
  3687. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3688. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3689. drawContext.arcTo(x, y+h, x, y, r);
  3690. drawContext.arcTo(x, y, x+w, y, r);
  3691. drawContext.closePath();
  3692. // 2) Uncomment this line to use Composite Operation, which is doing the
  3693. // same as the clip function below and is also antialiasing the round
  3694. // border, but is said to be less fast performance wise.
  3695. // drawContext.fill();
  3696. // Comment these two lines if choosing to do the same with composite
  3697. // operation above 1 and 2.
  3698. drawContext.clip();
  3699. drawContext.clearRect(0, 0, 277, 200);
  3700. // Restore the previous context state.
  3701. drawContext.restore();
  3702. };
  3703. /**
  3704. * Clones the given canvas.
  3705. *
  3706. * @return the new cloned canvas.
  3707. */
  3708. my.cloneCanvas = function (oldCanvas) {
  3709. /*
  3710. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3711. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3712. * levels are frequently updated, the errors have been observed to pile
  3713. * into the console, strain the CPU.
  3714. */
  3715. if (!oldCanvas)
  3716. return oldCanvas;
  3717. //create a new canvas
  3718. var newCanvas = document.createElement('canvas');
  3719. var context = newCanvas.getContext('2d');
  3720. //set dimensions
  3721. newCanvas.width = oldCanvas.width;
  3722. newCanvas.height = oldCanvas.height;
  3723. //apply the old canvas to the new one
  3724. context.drawImage(oldCanvas, 0, 0);
  3725. //return the new canvas
  3726. return newCanvas;
  3727. };
  3728. return my;
  3729. })(CanvasUtil || {});
  3730. module.exports = CanvasUtil;
  3731. },{}],14:[function(require,module,exports){
  3732. /* global $, APP*/
  3733. var LoginDialog = require('./LoginDialog');
  3734. var Moderator = require('../../xmpp/moderator');
  3735. /* Initial "authentication required" dialog */
  3736. var authDialog = null;
  3737. /* Loop retry ID that wits for other user to create the room */
  3738. var authRetryId = null;
  3739. var authenticationWindow = null;
  3740. var Authentication = {
  3741. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3742. // This is the loop that will wait for the room to be created by
  3743. // someone else. 'auth_required.moderator' will bring us back here.
  3744. authRetryId = window.setTimeout(intervalCallback, 5000);
  3745. // Show prompt only if it's not open
  3746. if (authDialog !== null) {
  3747. return;
  3748. }
  3749. // extract room name from 'room@muc.server.net'
  3750. var room = roomName.substr(0, roomName.indexOf('@'));
  3751. var title
  3752. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3753. var msg
  3754. = APP.translation.generateTranslationHTML(
  3755. "dialog.WaitForHostMsg", {room: room});
  3756. var buttonTxt
  3757. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3758. var buttons = [];
  3759. buttons.push({title: buttonTxt, value: "authNow"});
  3760. authDialog = APP.UI.messageHandler.openDialog(
  3761. title,
  3762. msg,
  3763. true,
  3764. buttons,
  3765. function (onSubmitEvent, submitValue) {
  3766. // Do not close the dialog yet
  3767. onSubmitEvent.preventDefault();
  3768. // Open login popup
  3769. if (submitValue === 'authNow') {
  3770. callback();
  3771. }
  3772. }
  3773. );
  3774. },
  3775. closeAuthenticationWindow: function () {
  3776. if (authenticationWindow) {
  3777. authenticationWindow.close();
  3778. authenticationWindow = null;
  3779. }
  3780. },
  3781. xmppAuthenticate: function () {
  3782. var loginDialog = LoginDialog.show(
  3783. function (connection, state) {
  3784. if (!state) {
  3785. // User cancelled
  3786. loginDialog.close();
  3787. return;
  3788. } else if (state == APP.xmpp.Status.CONNECTED) {
  3789. loginDialog.close();
  3790. Authentication.stopInterval();
  3791. Authentication.closeAuthenticationDialog();
  3792. // Close the connection as anonymous one will be used
  3793. // to create the conference. Session-id will authorize
  3794. // the request.
  3795. connection.disconnect();
  3796. var roomName = APP.UI.generateRoomName();
  3797. Moderator.allocateConferenceFocus(roomName, function () {
  3798. // If it's not "on the fly" authentication now join
  3799. // the conference room
  3800. if (!APP.xmpp.getMUCJoined()) {
  3801. APP.UI.checkForNicknameAndJoin();
  3802. }
  3803. });
  3804. }
  3805. }, true);
  3806. },
  3807. focusAuthenticationWindow: function () {
  3808. // If auth window exists just bring it to the front
  3809. if (authenticationWindow) {
  3810. authenticationWindow.focus();
  3811. return;
  3812. }
  3813. },
  3814. closeAuthenticationDialog: function () {
  3815. // Close authentication dialog if opened
  3816. if (authDialog) {
  3817. authDialog.close();
  3818. authDialog = null;
  3819. }
  3820. },
  3821. createAuthenticationWindow: function (callback, url) {
  3822. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3823. url, 910, 660,
  3824. // On closed
  3825. function () {
  3826. // Close authentication dialog if opened
  3827. Authentication.closeAuthenticationDialog();
  3828. callback();
  3829. authenticationWindow = null;
  3830. });
  3831. return authenticationWindow;
  3832. },
  3833. stopInterval: function () {
  3834. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3835. if (authRetryId) {
  3836. window.clearTimeout(authRetryId);
  3837. authRetryId = null;
  3838. }
  3839. }
  3840. };
  3841. module.exports = Authentication;
  3842. },{"../../xmpp/moderator":58,"./LoginDialog":15}],15:[function(require,module,exports){
  3843. /* global $, APP, config*/
  3844. var XMPP = require('../../xmpp/xmpp');
  3845. var Moderator = require('../../xmpp/moderator');
  3846. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3847. // anonymous domain is not enabled
  3848. /**
  3849. * Creates new <tt>Dialog</tt> instance.
  3850. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3851. * when we either fail to connect or succeed(check Strophe.Status).
  3852. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3853. * in order to create session-id after the connection is established.
  3854. * @constructor
  3855. */
  3856. function Dialog(callback, obtainSession) {
  3857. var self = this;
  3858. var stop = false;
  3859. var connection = APP.xmpp.createConnection();
  3860. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3861. message += APP.translation.translateString("dialog.passwordRequired");
  3862. message += '</h2>' +
  3863. '<input name="username" type="text" ' +
  3864. 'placeholder="user@domain.net" autofocus>' +
  3865. '<input name="password" ' +
  3866. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3867. ' placeholder="user password">';
  3868. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3869. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3870. var states = {
  3871. login: {
  3872. html: message,
  3873. buttons: [
  3874. { title: okButton, value: true},
  3875. { title: cancelButton, value: false}
  3876. ],
  3877. focus: ':input:first',
  3878. submit: function (e, v, m, f) {
  3879. e.preventDefault();
  3880. if (v) {
  3881. var jid = f.username;
  3882. var password = f.password;
  3883. if (jid && password) {
  3884. stop = false;
  3885. connection.reset();
  3886. connDialog.goToState('connecting');
  3887. connection.connect(jid, password, stateHandler);
  3888. }
  3889. } else {
  3890. // User cancelled
  3891. stop = true;
  3892. callback();
  3893. }
  3894. }
  3895. },
  3896. connecting: {
  3897. title: APP.translation.translateString('dialog.connecting'),
  3898. html: '<div id="connectionStatus"></div>',
  3899. buttons: [],
  3900. defaultButton: 0
  3901. },
  3902. finished: {
  3903. title: APP.translation.translateString('dialog.error'),
  3904. html: '<div id="errorMessage"></div>',
  3905. buttons: [
  3906. {
  3907. title: APP.translation.translateString('dialog.retry'),
  3908. value: 'retry'
  3909. },
  3910. {
  3911. title: APP.translation.translateString('dialog.Cancel'),
  3912. value: 'cancel'
  3913. },
  3914. ],
  3915. defaultButton: 0,
  3916. submit: function (e, v, m, f) {
  3917. e.preventDefault();
  3918. if (v === 'retry')
  3919. connDialog.goToState('login');
  3920. else
  3921. callback();
  3922. }
  3923. }
  3924. };
  3925. var connDialog
  3926. = APP.UI.messageHandler.openDialogWithStates(states,
  3927. { persistent: true, closeText: '' }, null);
  3928. var stateHandler = function (status, message) {
  3929. if (stop) {
  3930. return;
  3931. }
  3932. var translateKey = "connection." + XMPP.getStatusString(status);
  3933. var statusStr = APP.translation.translateString(translateKey);
  3934. // Display current state
  3935. var connectionStatus =
  3936. connDialog.getState('connecting').find('#connectionStatus');
  3937. connectionStatus.text(statusStr);
  3938. switch (status) {
  3939. case XMPP.Status.CONNECTED:
  3940. stop = true;
  3941. if (!obtainSession) {
  3942. callback(connection, status);
  3943. return;
  3944. }
  3945. // Obtaining session-id status
  3946. connectionStatus.text(
  3947. APP.translation.translateString(
  3948. 'connection.FETCH_SESSION_ID'));
  3949. // Authenticate with Jicofo and obtain session-id
  3950. var roomName = APP.UI.generateRoomName();
  3951. // Jicofo will return new session-id when connected
  3952. // from authenticated domain
  3953. connection.sendIQ(
  3954. Moderator.createConferenceIq(roomName),
  3955. function (result) {
  3956. connectionStatus.text(
  3957. APP.translation.translateString(
  3958. 'connection.GOT_SESSION_ID'));
  3959. stop = true;
  3960. // Parse session-id
  3961. Moderator.parseSessionId(result);
  3962. callback(connection, status);
  3963. },
  3964. function (error) {
  3965. console.error("Auth on the fly failed", error);
  3966. stop = true;
  3967. var errorMsg =
  3968. APP.translation.translateString(
  3969. 'connection.GET_SESSION_ID_ERROR') +
  3970. $(error).find('>error').attr('code');
  3971. self.displayError(errorMsg);
  3972. connection.disconnect();
  3973. });
  3974. break;
  3975. case XMPP.Status.AUTHFAIL:
  3976. case XMPP.Status.CONNFAIL:
  3977. case XMPP.Status.DISCONNECTED:
  3978. stop = true;
  3979. callback(connection, status);
  3980. var errorMessage = statusStr;
  3981. if (message)
  3982. {
  3983. errorMessage += ': ' + message;
  3984. }
  3985. self.displayError(errorMessage);
  3986. break;
  3987. default:
  3988. break;
  3989. }
  3990. };
  3991. /**
  3992. * Displays error message in 'finished' state which allows either to cancel
  3993. * or retry.
  3994. * @param message the final message to be displayed.
  3995. */
  3996. this.displayError = function (message) {
  3997. var finishedState = connDialog.getState('finished');
  3998. var errorMessageElem = finishedState.find('#errorMessage');
  3999. errorMessageElem.text(message);
  4000. connDialog.goToState('finished');
  4001. };
  4002. /**
  4003. * Closes LoginDialog.
  4004. */
  4005. this.close = function () {
  4006. stop = true;
  4007. connDialog.close();
  4008. };
  4009. }
  4010. var LoginDialog = {
  4011. /**
  4012. * Displays login prompt used to establish new XMPP connection. Given
  4013. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4014. * called when we connect successfully(status === CONNECTED) or when we fail
  4015. * to do so. On connection failure program can call Dialog.close() method in
  4016. * order to cancel or do nothing to let the user retry.
  4017. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4018. * called when we either fail to connect or succeed(check
  4019. * Strophe.Status).
  4020. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4021. * Jicofo in order to create session-id after the connection is
  4022. * established.
  4023. * @returns {Dialog}
  4024. */
  4025. show: function (callback, obtainSession) {
  4026. return new Dialog(callback, obtainSession);
  4027. }
  4028. };
  4029. module.exports = LoginDialog;
  4030. },{"../../xmpp/moderator":58,"../../xmpp/xmpp":66}],16:[function(require,module,exports){
  4031. var Settings = require("../../settings/Settings");
  4032. var users = {};
  4033. var Avatar = {
  4034. /**
  4035. * Sets the user's avatar in the settings menu(if local user), contact list
  4036. * and thumbnail
  4037. * @param jid jid of the user
  4038. * @param id email or userID to be used as a hash
  4039. */
  4040. setUserAvatar: function (jid, id) {
  4041. if (id) {
  4042. if (users[jid] === id) {
  4043. return;
  4044. }
  4045. users[jid] = id;
  4046. }
  4047. var thumbUrl = this.getGravatarUrl(users[jid] || jid, 100);
  4048. var contactListUrl = this.getGravatarUrl(users[jid] || jid);
  4049. var resourceJid = Strophe.getResourceFromJid(jid);
  4050. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4051. },
  4052. getGravatarUrl: function (id, size) {
  4053. if(id === APP.xmpp.myJid() || !id) {
  4054. id = Settings.getSettings().uid;
  4055. }
  4056. return 'https://www.gravatar.com/avatar/' +
  4057. MD5.hexdigest(id.trim().toLowerCase()) +
  4058. "?d=wavatar&size=" + (size || "30");
  4059. }
  4060. };
  4061. module.exports = Avatar;
  4062. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4063. /* global $, config,
  4064. setLargeVideoVisible, Util */
  4065. var VideoLayout = require("../videolayout/VideoLayout");
  4066. var Prezi = require("../prezi/Prezi");
  4067. var UIUtil = require("../util/UIUtil");
  4068. var etherpadName = null;
  4069. var etherpadIFrame = null;
  4070. var domain = null;
  4071. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4072. /**
  4073. * Resizes the etherpad.
  4074. */
  4075. function resize() {
  4076. if ($('#etherpad>iframe').length) {
  4077. var remoteVideos = $('#remoteVideos');
  4078. var availableHeight
  4079. = window.innerHeight - remoteVideos.outerHeight();
  4080. var availableWidth = UIUtil.getAvailableVideoWidth();
  4081. $('#etherpad>iframe').width(availableWidth);
  4082. $('#etherpad>iframe').height(availableHeight);
  4083. }
  4084. }
  4085. /**
  4086. * Creates the Etherpad button and adds it to the toolbar.
  4087. */
  4088. function enableEtherpadButton() {
  4089. if (!$('#etherpadButton').is(":visible"))
  4090. $('#etherpadButton').css({display: 'inline-block'});
  4091. }
  4092. /**
  4093. * Creates the IFrame for the etherpad.
  4094. */
  4095. function createIFrame() {
  4096. etherpadIFrame = document.createElement('iframe');
  4097. etherpadIFrame.src = domain + etherpadName + options;
  4098. etherpadIFrame.frameBorder = 0;
  4099. etherpadIFrame.scrolling = "no";
  4100. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  4101. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  4102. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  4103. document.getElementById('etherpad').appendChild(etherpadIFrame);
  4104. etherpadIFrame.onload = function() {
  4105. document.domain = document.domain;
  4106. bubbleIframeMouseMove(etherpadIFrame);
  4107. setTimeout(function() {
  4108. // the iframes inside of the etherpad are
  4109. // not yet loaded when the etherpad iframe is loaded
  4110. var outer = etherpadIFrame.
  4111. contentDocument.getElementsByName("ace_outer")[0];
  4112. bubbleIframeMouseMove(outer);
  4113. var inner = outer.
  4114. contentDocument.getElementsByName("ace_inner")[0];
  4115. bubbleIframeMouseMove(inner);
  4116. }, 2000);
  4117. };
  4118. }
  4119. function bubbleIframeMouseMove(iframe){
  4120. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4121. iframe.contentWindow.onmousemove = function(e){
  4122. if(existingOnMouseMove) existingOnMouseMove(e);
  4123. var evt = document.createEvent("MouseEvents");
  4124. var boundingClientRect = iframe.getBoundingClientRect();
  4125. evt.initMouseEvent(
  4126. "mousemove",
  4127. true, // bubbles
  4128. false, // not cancelable
  4129. window,
  4130. e.detail,
  4131. e.screenX,
  4132. e.screenY,
  4133. e.clientX + boundingClientRect.left,
  4134. e.clientY + boundingClientRect.top,
  4135. e.ctrlKey,
  4136. e.altKey,
  4137. e.shiftKey,
  4138. e.metaKey,
  4139. e.button,
  4140. null // no related element
  4141. );
  4142. iframe.dispatchEvent(evt);
  4143. };
  4144. }
  4145. /**
  4146. * On video selected event.
  4147. */
  4148. $(document).bind('video.selected', function (event, isPresentation) {
  4149. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  4150. Etherpad.toggleEtherpad(isPresentation);
  4151. });
  4152. var Etherpad = {
  4153. /**
  4154. * Initializes the etherpad.
  4155. */
  4156. init: function (name) {
  4157. if (config.etherpad_base && !etherpadName && name) {
  4158. domain = config.etherpad_base;
  4159. etherpadName = name;
  4160. enableEtherpadButton();
  4161. /**
  4162. * Resizes the etherpad, when the window is resized.
  4163. */
  4164. $(window).resize(function () {
  4165. resize();
  4166. });
  4167. }
  4168. },
  4169. /**
  4170. * Opens/hides the Etherpad.
  4171. */
  4172. toggleEtherpad: function (isPresentation) {
  4173. if (!etherpadIFrame)
  4174. createIFrame();
  4175. var largeVideo = null;
  4176. if (Prezi.isPresentationVisible())
  4177. largeVideo = $('#presentation>iframe');
  4178. else
  4179. largeVideo = $('#largeVideo');
  4180. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  4181. $('#activeSpeaker').css('visibility', 'hidden');
  4182. largeVideo.fadeOut(300, function () {
  4183. if (Prezi.isPresentationVisible()) {
  4184. largeVideo.css({opacity: '0'});
  4185. } else {
  4186. VideoLayout.setLargeVideoVisible(false);
  4187. }
  4188. });
  4189. $('#etherpad>iframe').fadeIn(300, function () {
  4190. document.body.style.background = '#eeeeee';
  4191. $('#etherpad>iframe').css({visibility: 'visible'});
  4192. $('#etherpad').css({zIndex: 2});
  4193. });
  4194. }
  4195. else if ($('#etherpad>iframe')) {
  4196. $('#etherpad>iframe').fadeOut(300, function () {
  4197. $('#etherpad>iframe').css({visibility: 'hidden'});
  4198. $('#etherpad').css({zIndex: 0});
  4199. document.body.style.background = 'black';
  4200. });
  4201. if (!isPresentation) {
  4202. $('#largeVideo').fadeIn(300, function () {
  4203. VideoLayout.setLargeVideoVisible(true);
  4204. });
  4205. }
  4206. }
  4207. resize();
  4208. },
  4209. isVisible: function() {
  4210. var etherpadIframe = $('#etherpad>iframe');
  4211. return etherpadIframe && etherpadIframe.is(':visible');
  4212. }
  4213. };
  4214. module.exports = Etherpad;
  4215. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4216. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4217. var UIUtil = require("../util/UIUtil");
  4218. var VideoLayout = require("../videolayout/VideoLayout");
  4219. var messageHandler = require("../util/MessageHandler");
  4220. var PreziPlayer = require("./PreziPlayer");
  4221. var preziPlayer = null;
  4222. var Prezi = {
  4223. /**
  4224. * Reloads the current presentation.
  4225. */
  4226. reloadPresentation: function() {
  4227. var iframe = document.getElementById(preziPlayer.options.preziId);
  4228. iframe.src = iframe.src;
  4229. },
  4230. /**
  4231. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4232. * otherwise.
  4233. */
  4234. isPresentationVisible: function () {
  4235. return ($('#presentation>iframe') != null
  4236. && $('#presentation>iframe').css('opacity') == 1);
  4237. },
  4238. /**
  4239. * Opens the Prezi dialog, from which the user could choose a presentation
  4240. * to load.
  4241. */
  4242. openPreziDialog: function() {
  4243. var myprezi = APP.xmpp.getPrezi();
  4244. if (myprezi) {
  4245. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4246. null,
  4247. "dialog.removePreziMsg",
  4248. null,
  4249. false,
  4250. "dialog.Remove",
  4251. function(e,v,m,f) {
  4252. if(v) {
  4253. APP.xmpp.removePreziFromPresence();
  4254. }
  4255. }
  4256. );
  4257. }
  4258. else if (preziPlayer != null) {
  4259. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4260. null, "dialog.sharePreziMsg",
  4261. null,
  4262. false,
  4263. "dialog.Ok",
  4264. function(e,v,m,f) {
  4265. $.prompt.close();
  4266. }
  4267. );
  4268. }
  4269. else {
  4270. var html = APP.translation.generateTranslationHTML(
  4271. "dialog.sharePreziTitle");
  4272. var cancelButton = APP.translation.generateTranslationHTML(
  4273. "dialog.Cancel");
  4274. var shareButton = APP.translation.generateTranslationHTML(
  4275. "dialog.Share");
  4276. var backButton = APP.translation.generateTranslationHTML(
  4277. "dialog.Back");
  4278. var buttons = [];
  4279. var buttons1 = [];
  4280. // Cancel button to both states
  4281. buttons.push({title: cancelButton, value: false});
  4282. buttons1.push({title: cancelButton, value: false});
  4283. // Share button
  4284. buttons.push({title: shareButton, value: true});
  4285. // Back button
  4286. buttons1.push({title: backButton, value: true});
  4287. var linkError = APP.translation.generateTranslationHTML(
  4288. "dialog.preziLinkError");
  4289. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4290. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4291. var openPreziState = {
  4292. state0: {
  4293. html: '<h2>' + html + '</h2>' +
  4294. '<input name="preziUrl" type="text" ' +
  4295. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4296. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4297. '\' placeholder="' + defaultUrl + '" autofocus>',
  4298. persistent: false,
  4299. buttons: buttons,
  4300. focus: ':input:first',
  4301. defaultButton: 0,
  4302. submit: function (e, v, m, f) {
  4303. e.preventDefault();
  4304. if(v)
  4305. {
  4306. var preziUrl = f.preziUrl;
  4307. if (preziUrl)
  4308. {
  4309. var urlValue
  4310. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4311. if (urlValue.indexOf('http://prezi.com/') != 0
  4312. && urlValue.indexOf('https://prezi.com/') != 0)
  4313. {
  4314. $.prompt.goToState('state1');
  4315. return false;
  4316. }
  4317. else {
  4318. var presIdTmp = urlValue.substring(
  4319. urlValue.indexOf("prezi.com/") + 10);
  4320. if (!isAlphanumeric(presIdTmp)
  4321. || presIdTmp.indexOf('/') < 2) {
  4322. $.prompt.goToState('state1');
  4323. return false;
  4324. }
  4325. else {
  4326. APP.xmpp.addToPresence("prezi", urlValue);
  4327. $.prompt.close();
  4328. }
  4329. }
  4330. }
  4331. }
  4332. else
  4333. $.prompt.close();
  4334. }
  4335. },
  4336. state1: {
  4337. html: '<h2>' + html + '</h2>' +
  4338. linkError,
  4339. persistent: false,
  4340. buttons: buttons1,
  4341. focus: ':input:first',
  4342. defaultButton: 1,
  4343. submit: function (e, v, m, f) {
  4344. e.preventDefault();
  4345. if (v === 0)
  4346. $.prompt.close();
  4347. else
  4348. $.prompt.goToState('state0');
  4349. }
  4350. }
  4351. };
  4352. messageHandler.openDialogWithStates(openPreziState);
  4353. }
  4354. }
  4355. };
  4356. /**
  4357. * A new presentation has been added.
  4358. *
  4359. * @param event the event indicating the add of a presentation
  4360. * @param jid the jid from which the presentation was added
  4361. * @param presUrl url of the presentation
  4362. * @param currentSlide the current slide to which we should move
  4363. */
  4364. function presentationAdded(event, jid, presUrl, currentSlide) {
  4365. console.log("presentation added", presUrl);
  4366. var presId = getPresentationId(presUrl);
  4367. var elementId = 'participant_'
  4368. + Strophe.getResourceFromJid(jid)
  4369. + '_' + presId;
  4370. VideoLayout.addPreziContainer(elementId);
  4371. VideoLayout.resizeThumbnails();
  4372. var controlsEnabled = false;
  4373. if (jid === APP.xmpp.myJid())
  4374. controlsEnabled = true;
  4375. setPresentationVisible(true);
  4376. $('#largeVideoContainer').hover(
  4377. function (event) {
  4378. if (Prezi.isPresentationVisible()) {
  4379. var reloadButtonRight = window.innerWidth
  4380. - $('#presentation>iframe').offset().left
  4381. - $('#presentation>iframe').width();
  4382. $('#reloadPresentation').css({ right: reloadButtonRight,
  4383. display:'inline-block'});
  4384. }
  4385. },
  4386. function (event) {
  4387. if (!Prezi.isPresentationVisible())
  4388. $('#reloadPresentation').css({display:'none'});
  4389. else {
  4390. var e = event.toElement || event.relatedTarget;
  4391. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4392. $('#reloadPresentation').css({display:'none'});
  4393. }
  4394. });
  4395. preziPlayer = new PreziPlayer(
  4396. 'presentation',
  4397. {preziId: presId,
  4398. width: getPresentationWidth(),
  4399. height: getPresentationHeihgt(),
  4400. controls: controlsEnabled,
  4401. debug: true
  4402. });
  4403. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4404. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4405. console.log("prezi status", event.value);
  4406. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4407. if (jid != APP.xmpp.myJid())
  4408. preziPlayer.flyToStep(currentSlide);
  4409. }
  4410. });
  4411. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4412. console.log("event value", event.value);
  4413. APP.xmpp.addToPresence("preziSlide", event.value);
  4414. });
  4415. $("#" + elementId).css( 'background-image',
  4416. 'url(../images/avatarprezi.png)');
  4417. $("#" + elementId).click(
  4418. function () {
  4419. setPresentationVisible(true);
  4420. }
  4421. );
  4422. };
  4423. /**
  4424. * A presentation has been removed.
  4425. *
  4426. * @param event the event indicating the remove of a presentation
  4427. * @param jid the jid for which the presentation was removed
  4428. * @param the url of the presentation
  4429. */
  4430. function presentationRemoved(event, jid, presUrl) {
  4431. console.log('presentation removed', presUrl);
  4432. var presId = getPresentationId(presUrl);
  4433. setPresentationVisible(false);
  4434. $('#participant_'
  4435. + Strophe.getResourceFromJid(jid)
  4436. + '_' + presId).remove();
  4437. $('#presentation>iframe').remove();
  4438. if (preziPlayer != null) {
  4439. preziPlayer.destroy();
  4440. preziPlayer = null;
  4441. }
  4442. };
  4443. /**
  4444. * Indicates if the given string is an alphanumeric string.
  4445. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4446. * purpose of checking URIs.
  4447. */
  4448. function isAlphanumeric(unsafeText) {
  4449. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4450. return regex.test(unsafeText);
  4451. }
  4452. /**
  4453. * Returns the presentation id from the given url.
  4454. */
  4455. function getPresentationId (presUrl) {
  4456. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4457. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4458. }
  4459. /**
  4460. * Returns the presentation width.
  4461. */
  4462. function getPresentationWidth() {
  4463. var availableWidth = UIUtil.getAvailableVideoWidth();
  4464. var availableHeight = getPresentationHeihgt();
  4465. var aspectRatio = 16.0 / 9.0;
  4466. if (availableHeight < availableWidth / aspectRatio) {
  4467. availableWidth = Math.floor(availableHeight * aspectRatio);
  4468. }
  4469. return availableWidth;
  4470. }
  4471. /**
  4472. * Returns the presentation height.
  4473. */
  4474. function getPresentationHeihgt() {
  4475. var remoteVideos = $('#remoteVideos');
  4476. return window.innerHeight - remoteVideos.outerHeight();
  4477. }
  4478. /**
  4479. * Resizes the presentation iframe.
  4480. */
  4481. function resize() {
  4482. if ($('#presentation>iframe')) {
  4483. $('#presentation>iframe').width(getPresentationWidth());
  4484. $('#presentation>iframe').height(getPresentationHeihgt());
  4485. }
  4486. }
  4487. /**
  4488. * Shows/hides a presentation.
  4489. */
  4490. function setPresentationVisible(visible) {
  4491. var prezi = $('#presentation>iframe');
  4492. if (visible) {
  4493. // Trigger the video.selected event to indicate a change in the
  4494. // large video.
  4495. $(document).trigger("video.selected", [true]);
  4496. $('#largeVideo').fadeOut(300);
  4497. prezi.fadeIn(300, function() {
  4498. prezi.css({opacity:'1'});
  4499. ToolbarToggler.dockToolbar(true);
  4500. VideoLayout.setLargeVideoVisible(false);
  4501. });
  4502. $('#activeSpeaker').css('visibility', 'hidden');
  4503. }
  4504. else {
  4505. if (prezi.css('opacity') == '1') {
  4506. prezi.fadeOut(300, function () {
  4507. prezi.css({opacity:'0'});
  4508. $('#reloadPresentation').css({display:'none'});
  4509. $('#largeVideo').fadeIn(300, function() {
  4510. VideoLayout.setLargeVideoVisible(true);
  4511. ToolbarToggler.dockToolbar(false);
  4512. });
  4513. });
  4514. }
  4515. }
  4516. }
  4517. /**
  4518. * Presentation has been removed.
  4519. */
  4520. $(document).bind('presentationremoved.muc', presentationRemoved);
  4521. /**
  4522. * Presentation has been added.
  4523. */
  4524. $(document).bind('presentationadded.muc', presentationAdded);
  4525. /*
  4526. * Indicates presentation slide change.
  4527. */
  4528. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4529. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4530. preziPlayer.flyToStep(current);
  4531. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4532. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4533. preziPlayer.flyToStep(current, i);
  4534. }
  4535. }
  4536. });
  4537. /**
  4538. * On video selected event.
  4539. */
  4540. $(document).bind('video.selected', function (event, isPresentation) {
  4541. if (!isPresentation && $('#presentation>iframe')) {
  4542. setPresentationVisible(false);
  4543. }
  4544. });
  4545. $(window).resize(function () {
  4546. resize();
  4547. });
  4548. module.exports = Prezi;
  4549. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4550. (function() {
  4551. "use strict";
  4552. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4553. window.PreziPlayer = (function() {
  4554. PreziPlayer.API_VERSION = 1;
  4555. PreziPlayer.CURRENT_STEP = 'currentStep';
  4556. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4557. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4558. PreziPlayer.STATUS_LOADING = 'loading';
  4559. PreziPlayer.STATUS_READY = 'ready';
  4560. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4561. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4562. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4563. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4564. PreziPlayer.EVENT_STATUS = "statusChange";
  4565. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4566. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4567. PreziPlayer.domain = "https://prezi.com";
  4568. PreziPlayer.path = "/player/";
  4569. PreziPlayer.players = {};
  4570. PreziPlayer.binded_methods = ['changesHandler'];
  4571. PreziPlayer.createMultiplePlayers = function(optionArray){
  4572. for(var i=0; i<optionArray.length; i++) {
  4573. var optionSet = optionArray[i];
  4574. new PreziPlayer(optionSet.id, optionSet);
  4575. };
  4576. };
  4577. PreziPlayer.messageReceived = function(event){
  4578. var message, item, player;
  4579. try {
  4580. message = JSON.parse(event.data);
  4581. if (message.id && (player = PreziPlayer.players[message.id])) {
  4582. if (player.options.debug === true) {
  4583. if (console && console.log)
  4584. console.log('received', message);
  4585. }
  4586. if (message.type === "changes") {
  4587. player.changesHandler(message);
  4588. }
  4589. for (var i = 0; i < player.callbacks.length; i++) {
  4590. item = player.callbacks[i];
  4591. if (item && message.type === item.event) {
  4592. item.callback(message);
  4593. }
  4594. }
  4595. }
  4596. } catch (e) { }
  4597. };
  4598. function PreziPlayer(id, options) {
  4599. var params, paramString = "", _this = this;
  4600. if (PreziPlayer.players[id]){
  4601. PreziPlayer.players[id].destroy();
  4602. }
  4603. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4604. var method_name = PreziPlayer.binded_methods[i];
  4605. _this[method_name] = __bind(_this[method_name], _this);
  4606. };
  4607. options = options || {};
  4608. this.options = options;
  4609. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4610. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4611. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4612. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4613. this.callbacks = [];
  4614. this.id = id;
  4615. this.embedTo = document.getElementById(id);
  4616. if (!this.embedTo) {
  4617. throw "The element id is not available.";
  4618. }
  4619. this.iframe = document.createElement('iframe');
  4620. params = [
  4621. { name: 'oid', value: options.preziId },
  4622. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4623. { name: 'controls', value: options.controls ? 1 : 0 }
  4624. ];
  4625. for(var i=0; i<params.length; i++) {
  4626. var param = params[i];
  4627. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4628. };
  4629. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4630. this.iframe.frameBorder = 0;
  4631. this.iframe.scrolling = "no";
  4632. this.iframe.width = options.width || 640;
  4633. this.iframe.height = options.height || 480;
  4634. this.embedTo.innerHTML = '';
  4635. // JITSI: IN CASE SOMETHING GOES WRONG.
  4636. try {
  4637. this.embedTo.appendChild(this.iframe);
  4638. }
  4639. catch (err) {
  4640. console.log("CATCH ERROR");
  4641. }
  4642. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4643. // crashes for us.
  4644. this.initPollInterval = setInterval(function(){
  4645. _this.sendMessage({'action': 'init'});
  4646. }, 500);
  4647. PreziPlayer.players[id] = this;
  4648. }
  4649. PreziPlayer.prototype.changesHandler = function(message) {
  4650. var key, value, j, item;
  4651. if (this.initPollInterval) {
  4652. clearInterval(this.initPollInterval);
  4653. this.initPollInterval = false;
  4654. }
  4655. for (key in message.data) {
  4656. if (message.data.hasOwnProperty(key)){
  4657. value = message.data[key];
  4658. this.values[key] = value;
  4659. for (j=0; j<this.callbacks.length; j++) {
  4660. item = this.callbacks[j];
  4661. if (item && item.event === key + "Change"){
  4662. item.callback({type: item.event, value: value});
  4663. }
  4664. }
  4665. }
  4666. }
  4667. };
  4668. PreziPlayer.prototype.destroy = function() {
  4669. if (this.initPollInterval) {
  4670. clearInterval(this.initPollInterval);
  4671. this.initPollInterval = false;
  4672. }
  4673. this.embedTo.innerHTML = '';
  4674. };
  4675. PreziPlayer.prototype.sendMessage = function(message) {
  4676. if (this.options.debug === true) {
  4677. if (console && console.log) console.log('sent', message);
  4678. }
  4679. message.version = PreziPlayer.API_VERSION;
  4680. message.id = this.id;
  4681. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4682. };
  4683. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4684. PreziPlayer.prototype.flyToNextStep = function() {
  4685. return this.sendMessage({
  4686. 'action': 'present',
  4687. 'data': ['moveToNextStep']
  4688. });
  4689. };
  4690. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4691. PreziPlayer.prototype.flyToPreviousStep = function() {
  4692. return this.sendMessage({
  4693. 'action': 'present',
  4694. 'data': ['moveToPrevStep']
  4695. });
  4696. };
  4697. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4698. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4699. var obj = this;
  4700. // check animation_step
  4701. if (animation_step > 0 &&
  4702. obj.values.animationCountOnSteps &&
  4703. obj.values.animationCountOnSteps[step] <= animation_step) {
  4704. animation_step = obj.values.animationCountOnSteps[step];
  4705. }
  4706. // jump to animation steps by calling flyToNextStep()
  4707. function doAnimationSteps() {
  4708. if (obj.values.isMoving == true) {
  4709. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4710. return;
  4711. }
  4712. while (animation_step-- > 0) {
  4713. obj.flyToNextStep(); // do the animation steps
  4714. }
  4715. }
  4716. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4717. // jump to the step
  4718. return this.sendMessage({
  4719. 'action': 'present',
  4720. 'data': ['moveToStep', step]
  4721. });
  4722. };
  4723. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4724. PreziPlayer.prototype.flyToObject = function(objectId) {
  4725. return this.sendMessage({
  4726. 'action': 'present',
  4727. 'data': ['moveToObject', objectId]
  4728. });
  4729. };
  4730. PreziPlayer.prototype.play = function(defaultDelay) {
  4731. return this.sendMessage({
  4732. 'action': 'present',
  4733. 'data': ['startAutoPlay', defaultDelay]
  4734. });
  4735. };
  4736. PreziPlayer.prototype.stop = function() {
  4737. return this.sendMessage({
  4738. 'action': 'present',
  4739. 'data': ['stopAutoPlay']
  4740. });
  4741. };
  4742. PreziPlayer.prototype.pause = function(defaultDelay) {
  4743. return this.sendMessage({
  4744. 'action': 'present',
  4745. 'data': ['pauseAutoPlay', defaultDelay]
  4746. });
  4747. };
  4748. PreziPlayer.prototype.getCurrentStep = function() {
  4749. return this.values.currentStep;
  4750. };
  4751. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4752. return this.values.currentAnimationStep;
  4753. };
  4754. PreziPlayer.prototype.getCurrentObject = function() {
  4755. return this.values.currentObject;
  4756. };
  4757. PreziPlayer.prototype.getStatus = function() {
  4758. return this.values.status;
  4759. };
  4760. PreziPlayer.prototype.isPlaying = function() {
  4761. return this.values.isAutoPlaying;
  4762. };
  4763. PreziPlayer.prototype.getStepCount = function() {
  4764. return this.values.stepCount;
  4765. };
  4766. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4767. return this.values.animationCountOnSteps;
  4768. };
  4769. PreziPlayer.prototype.getTitle = function() {
  4770. return this.values.title;
  4771. };
  4772. PreziPlayer.prototype.setDimensions = function(dims) {
  4773. for (var parameter in dims) {
  4774. this.iframe[parameter] = dims[parameter];
  4775. }
  4776. }
  4777. PreziPlayer.prototype.getDimensions = function() {
  4778. return {
  4779. width: parseInt(this.iframe.width, 10),
  4780. height: parseInt(this.iframe.height, 10)
  4781. }
  4782. }
  4783. PreziPlayer.prototype.on = function(event, callback) {
  4784. this.callbacks.push({
  4785. event: event,
  4786. callback: callback
  4787. });
  4788. };
  4789. PreziPlayer.prototype.off = function(event, callback) {
  4790. var j, item;
  4791. if (event === undefined) {
  4792. this.callbacks = [];
  4793. }
  4794. j = this.callbacks.length;
  4795. while (j--) {
  4796. item = this.callbacks[j];
  4797. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4798. this.callbacks.splice(j, 1);
  4799. }
  4800. }
  4801. };
  4802. if (window.addEventListener) {
  4803. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4804. } else {
  4805. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4806. }
  4807. return PreziPlayer;
  4808. })();
  4809. })();
  4810. module.exports = PreziPlayer;
  4811. },{}],20:[function(require,module,exports){
  4812. var Chat = require("./chat/Chat");
  4813. var ContactList = require("./contactlist/ContactList");
  4814. var Settings = require("./../../settings/Settings");
  4815. var SettingsMenu = require("./settings/SettingsMenu");
  4816. var VideoLayout = require("../videolayout/VideoLayout");
  4817. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4818. var UIUtil = require("../util/UIUtil");
  4819. var LargeVideo = require("../videolayout/LargeVideo");
  4820. /**
  4821. * Toggler for the chat, contact list, settings menu, etc..
  4822. */
  4823. var PanelToggler = (function(my) {
  4824. var currentlyOpen = null;
  4825. var buttons = {
  4826. '#chatspace': '#chatBottomButton',
  4827. '#contactlist': '#contactListButton',
  4828. '#settingsmenu': '#settingsButton'
  4829. };
  4830. /**
  4831. * Toggles the windows in the side panel
  4832. * @param object the window that should be shown
  4833. * @param selector the selector for the element containing the panel
  4834. * @param onOpenComplete function to be called when the panel is opened
  4835. * @param onOpen function to be called if the window is going to be opened
  4836. * @param onClose function to be called if the window is going to be closed
  4837. */
  4838. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4839. UIUtil.buttonClick(buttons[selector], "active");
  4840. if (object.isVisible()) {
  4841. $("#toast-container").animate({
  4842. right: '5px'
  4843. },
  4844. {
  4845. queue: false,
  4846. duration: 500
  4847. });
  4848. $(selector).hide("slide", {
  4849. direction: "right",
  4850. queue: false,
  4851. duration: 500
  4852. });
  4853. if(typeof onClose === "function") {
  4854. onClose();
  4855. }
  4856. currentlyOpen = null;
  4857. }
  4858. else {
  4859. // Undock the toolbar when the chat is shown and if we're in a
  4860. // video mode.
  4861. if (LargeVideo.isLargeVideoVisible()) {
  4862. ToolbarToggler.dockToolbar(false);
  4863. }
  4864. if(currentlyOpen) {
  4865. var current = $(currentlyOpen);
  4866. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4867. current.css('z-index', 4);
  4868. setTimeout(function () {
  4869. current.css('display', 'none');
  4870. current.css('z-index', 5);
  4871. }, 500);
  4872. }
  4873. $("#toast-container").animate({
  4874. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4875. },
  4876. {
  4877. queue: false,
  4878. duration: 500
  4879. });
  4880. $(selector).show("slide", {
  4881. direction: "right",
  4882. queue: false,
  4883. duration: 500,
  4884. complete: onOpenComplete
  4885. });
  4886. if(typeof onOpen === "function") {
  4887. onOpen();
  4888. }
  4889. currentlyOpen = selector;
  4890. }
  4891. };
  4892. /**
  4893. * Opens / closes the chat area.
  4894. */
  4895. my.toggleChat = function() {
  4896. var chatCompleteFunction = Chat.isVisible() ?
  4897. function() {} : function () {
  4898. Chat.scrollChatToBottom();
  4899. $('#chatspace').trigger('shown');
  4900. };
  4901. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4902. toggle(Chat,
  4903. '#chatspace',
  4904. function () {
  4905. // Request the focus in the nickname field or the chat input field.
  4906. if ($('#nickname').css('visibility') === 'visible') {
  4907. $('#nickinput').focus();
  4908. } else {
  4909. $('#usermsg').focus();
  4910. }
  4911. },
  4912. null,
  4913. Chat.resizeChat,
  4914. null);
  4915. };
  4916. /**
  4917. * Opens / closes the contact list area.
  4918. */
  4919. my.toggleContactList = function () {
  4920. var completeFunction = ContactList.isVisible() ?
  4921. function() {} : function () { $('#contactlist').trigger('shown');};
  4922. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4923. toggle(ContactList,
  4924. '#contactlist',
  4925. null,
  4926. function() {
  4927. ContactList.setVisualNotification(false);
  4928. },
  4929. null);
  4930. };
  4931. /**
  4932. * Opens / closes the settings menu
  4933. */
  4934. my.toggleSettingsMenu = function() {
  4935. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4936. toggle(SettingsMenu,
  4937. '#settingsmenu',
  4938. null,
  4939. function() {
  4940. var settings = Settings.getSettings();
  4941. $('#setDisplayName').get(0).value = settings.displayName;
  4942. $('#setEmail').get(0).value = settings.email;
  4943. },
  4944. null);
  4945. };
  4946. /**
  4947. * Returns the size of the side panel.
  4948. */
  4949. my.getPanelSize = function () {
  4950. var availableHeight = window.innerHeight;
  4951. var availableWidth = window.innerWidth;
  4952. var panelWidth = 200;
  4953. if (availableWidth * 0.2 < 200) {
  4954. panelWidth = availableWidth * 0.2;
  4955. }
  4956. return [panelWidth, availableHeight];
  4957. };
  4958. my.isVisible = function() {
  4959. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4960. };
  4961. return my;
  4962. }(PanelToggler || {}));
  4963. module.exports = PanelToggler;
  4964. },{"../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){
  4965. /* global $, Util, nickname:true */
  4966. var Replacement = require("./Replacement");
  4967. var CommandsProcessor = require("./Commands");
  4968. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4969. var smileys = require("./smileys.json").smileys;
  4970. var NicknameHandler = require("../../util/NicknameHandler");
  4971. var UIUtil = require("../../util/UIUtil");
  4972. var UIEvents = require("../../../../service/UI/UIEvents");
  4973. var notificationInterval = false;
  4974. var unreadMessages = 0;
  4975. /**
  4976. * Shows/hides a visual notification, indicating that a message has arrived.
  4977. */
  4978. function setVisualNotification(show) {
  4979. var unreadMsgElement = document.getElementById('unreadMessages');
  4980. var unreadMsgBottomElement
  4981. = document.getElementById('bottomUnreadMessages');
  4982. var glower = $('#chatButton');
  4983. var bottomGlower = $('#chatBottomButton');
  4984. if (unreadMessages) {
  4985. unreadMsgElement.innerHTML = unreadMessages.toString();
  4986. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4987. ToolbarToggler.dockToolbar(true);
  4988. var chatButtonElement
  4989. = document.getElementById('chatButton').parentNode;
  4990. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4991. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4992. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4993. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4994. unreadMsgElement.setAttribute(
  4995. 'style',
  4996. 'top:' + topIndent +
  4997. '; left:' + leftIndent + ';');
  4998. var chatBottomButtonElement
  4999. = document.getElementById('chatBottomButton').parentNode;
  5000. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  5001. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  5002. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  5003. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5004. unreadMsgBottomElement.setAttribute(
  5005. 'style',
  5006. 'top:' + bottomTopIndent +
  5007. '; left:' + bottomLeftIndent + ';');
  5008. if (!glower.hasClass('icon-chat-simple')) {
  5009. glower.removeClass('icon-chat');
  5010. glower.addClass('icon-chat-simple');
  5011. }
  5012. }
  5013. else {
  5014. unreadMsgElement.innerHTML = '';
  5015. unreadMsgBottomElement.innerHTML = '';
  5016. glower.removeClass('icon-chat-simple');
  5017. glower.addClass('icon-chat');
  5018. }
  5019. if (show && !notificationInterval) {
  5020. notificationInterval = window.setInterval(function () {
  5021. glower.toggleClass('active');
  5022. bottomGlower.toggleClass('active glowing');
  5023. }, 800);
  5024. }
  5025. else if (!show && notificationInterval) {
  5026. window.clearInterval(notificationInterval);
  5027. notificationInterval = false;
  5028. glower.removeClass('active');
  5029. bottomGlower.removeClass('glowing');
  5030. bottomGlower.addClass('active');
  5031. }
  5032. }
  5033. /**
  5034. * Returns the current time in the format it is shown to the user
  5035. * @returns {string}
  5036. */
  5037. function getCurrentTime(stamp) {
  5038. var now = (stamp? new Date(stamp): new Date());
  5039. var hour = now.getHours();
  5040. var minute = now.getMinutes();
  5041. var second = now.getSeconds();
  5042. if(hour.toString().length === 1) {
  5043. hour = '0'+hour;
  5044. }
  5045. if(minute.toString().length === 1) {
  5046. minute = '0'+minute;
  5047. }
  5048. if(second.toString().length === 1) {
  5049. second = '0'+second;
  5050. }
  5051. return hour+':'+minute+':'+second;
  5052. }
  5053. function toggleSmileys()
  5054. {
  5055. var smileys = $('#smileysContainer');
  5056. if(!smileys.is(':visible')) {
  5057. smileys.show("slide", { direction: "down", duration: 300});
  5058. } else {
  5059. smileys.hide("slide", { direction: "down", duration: 300});
  5060. }
  5061. $('#usermsg').focus();
  5062. }
  5063. function addClickFunction(smiley, number) {
  5064. smiley.onclick = function addSmileyToMessage() {
  5065. var usermsg = $('#usermsg');
  5066. var message = usermsg.val();
  5067. message += smileys['smiley' + number];
  5068. usermsg.val(message);
  5069. usermsg.get(0).setSelectionRange(message.length, message.length);
  5070. toggleSmileys();
  5071. usermsg.focus();
  5072. };
  5073. }
  5074. /**
  5075. * Adds the smileys container to the chat
  5076. */
  5077. function addSmileys() {
  5078. var smileysContainer = document.createElement('div');
  5079. smileysContainer.id = 'smileysContainer';
  5080. for(var i = 1; i <= 21; i++) {
  5081. var smileyContainer = document.createElement('div');
  5082. smileyContainer.id = 'smiley' + i;
  5083. smileyContainer.className = 'smileyContainer';
  5084. var smiley = document.createElement('img');
  5085. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5086. smiley.className = 'smiley';
  5087. addClickFunction(smiley, i);
  5088. smileyContainer.appendChild(smiley);
  5089. smileysContainer.appendChild(smileyContainer);
  5090. }
  5091. $("#chatspace").append(smileysContainer);
  5092. }
  5093. /**
  5094. * Resizes the chat conversation.
  5095. */
  5096. function resizeChatConversation() {
  5097. var msgareaHeight = $('#usermsg').outerHeight();
  5098. var chatspace = $('#chatspace');
  5099. var width = chatspace.width();
  5100. var chat = $('#chatconversation');
  5101. var smileys = $('#smileysarea');
  5102. smileys.height(msgareaHeight);
  5103. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5104. $('#smileysContainer').css('bottom', msgareaHeight);
  5105. chat.width(width - 10);
  5106. chat.height(window.innerHeight - 15 - msgareaHeight);
  5107. }
  5108. /**
  5109. * Chat related user interface.
  5110. */
  5111. var Chat = (function (my) {
  5112. /**
  5113. * Initializes chat related interface.
  5114. */
  5115. my.init = function () {
  5116. if(NicknameHandler.getNickname())
  5117. Chat.setChatConversationMode(true);
  5118. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5119. function (nickname) {
  5120. Chat.setChatConversationMode(true);
  5121. });
  5122. $('#nickinput').keydown(function (event) {
  5123. if (event.keyCode === 13) {
  5124. event.preventDefault();
  5125. var val = UIUtil.escapeHtml(this.value);
  5126. this.value = '';
  5127. if (!NicknameHandler.getNickname()) {
  5128. NicknameHandler.setNickname(val);
  5129. return;
  5130. }
  5131. }
  5132. });
  5133. $('#usermsg').keydown(function (event) {
  5134. if (event.keyCode === 13) {
  5135. event.preventDefault();
  5136. var value = this.value;
  5137. $('#usermsg').val('').trigger('autosize.resize');
  5138. this.focus();
  5139. var command = new CommandsProcessor(value);
  5140. if(command.isCommand())
  5141. {
  5142. command.processCommand();
  5143. }
  5144. else
  5145. {
  5146. var message = UIUtil.escapeHtml(value);
  5147. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5148. }
  5149. }
  5150. });
  5151. var onTextAreaResize = function () {
  5152. resizeChatConversation();
  5153. Chat.scrollChatToBottom();
  5154. };
  5155. $('#usermsg').autosize({callback: onTextAreaResize});
  5156. $("#chatspace").bind("shown",
  5157. function () {
  5158. unreadMessages = 0;
  5159. setVisualNotification(false);
  5160. });
  5161. addSmileys();
  5162. };
  5163. /**
  5164. * Appends the given message to the chat conversation.
  5165. */
  5166. my.updateChatConversation = function (from, displayName, message, myjid, stamp) {
  5167. var divClassName = '';
  5168. if (APP.xmpp.myJid() === from) {
  5169. divClassName = "localuser";
  5170. }
  5171. else {
  5172. divClassName = "remoteuser";
  5173. if (!Chat.isVisible()) {
  5174. unreadMessages++;
  5175. UIUtil.playSoundNotification('chatNotification');
  5176. setVisualNotification(true);
  5177. }
  5178. }
  5179. // replace links and smileys
  5180. // Strophe already escapes special symbols on sending,
  5181. // so we escape here only tags to avoid double &amp;
  5182. var escMessage = message.replace(/</g, '&lt;').
  5183. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5184. var escDisplayName = UIUtil.escapeHtml(displayName);
  5185. message = Replacement.processReplacements(escMessage);
  5186. var messageContainer =
  5187. '<div class="chatmessage">'+
  5188. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5189. '<div class="username ' + divClassName +'">' + escDisplayName +
  5190. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5191. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5192. '</div>';
  5193. $('#chatconversation').append(messageContainer);
  5194. $('#chatconversation').animate(
  5195. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5196. };
  5197. /**
  5198. * Appends error message to the conversation
  5199. * @param errorMessage the received error message.
  5200. * @param originalText the original message.
  5201. */
  5202. my.chatAddError = function(errorMessage, originalText)
  5203. {
  5204. errorMessage = UIUtil.escapeHtml(errorMessage);
  5205. originalText = UIUtil.escapeHtml(originalText);
  5206. $('#chatconversation').append(
  5207. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5208. (originalText? (' \"'+ originalText + '\"') : "") +
  5209. ' was not sent.' +
  5210. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5211. $('#chatconversation').animate(
  5212. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5213. };
  5214. /**
  5215. * Sets the subject to the UI
  5216. * @param subject the subject
  5217. */
  5218. my.chatSetSubject = function(subject)
  5219. {
  5220. if(subject)
  5221. subject = subject.trim();
  5222. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5223. if(subject === "")
  5224. {
  5225. $("#subject").css({display: "none"});
  5226. }
  5227. else
  5228. {
  5229. $("#subject").css({display: "block"});
  5230. }
  5231. };
  5232. /**
  5233. * Sets the chat conversation mode.
  5234. */
  5235. my.setChatConversationMode = function (isConversationMode) {
  5236. if (isConversationMode) {
  5237. $('#nickname').css({visibility: 'hidden'});
  5238. $('#chatconversation').css({visibility: 'visible'});
  5239. $('#usermsg').css({visibility: 'visible'});
  5240. $('#smileysarea').css({visibility: 'visible'});
  5241. $('#usermsg').focus();
  5242. }
  5243. };
  5244. /**
  5245. * Resizes the chat area.
  5246. */
  5247. my.resizeChat = function () {
  5248. var chatSize = require("../SidePanelToggler").getPanelSize();
  5249. $('#chatspace').width(chatSize[0]);
  5250. $('#chatspace').height(chatSize[1]);
  5251. resizeChatConversation();
  5252. };
  5253. /**
  5254. * Indicates if the chat is currently visible.
  5255. */
  5256. my.isVisible = function () {
  5257. return $('#chatspace').is(":visible");
  5258. };
  5259. /**
  5260. * Shows and hides the window with the smileys
  5261. */
  5262. my.toggleSmileys = toggleSmileys;
  5263. /**
  5264. * Scrolls chat to the bottom.
  5265. */
  5266. my.scrollChatToBottom = function() {
  5267. setTimeout(function () {
  5268. $('#chatconversation').scrollTop(
  5269. $('#chatconversation')[0].scrollHeight);
  5270. }, 5);
  5271. };
  5272. return my;
  5273. }(Chat || {}));
  5274. module.exports = Chat;
  5275. },{"../../../../service/UI/UIEvents":102,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5276. var UIUtil = require("../../util/UIUtil");
  5277. /**
  5278. * List with supported commands. The keys are the names of the commands and
  5279. * the value is the function that processes the message.
  5280. * @type {{String: function}}
  5281. */
  5282. var commands = {
  5283. "topic" : processTopic
  5284. };
  5285. /**
  5286. * Extracts the command from the message.
  5287. * @param message the received message
  5288. * @returns {string} the command
  5289. */
  5290. function getCommand(message)
  5291. {
  5292. if(message)
  5293. {
  5294. for(var command in commands)
  5295. {
  5296. if(message.indexOf("/" + command) == 0)
  5297. return command;
  5298. }
  5299. }
  5300. return "";
  5301. };
  5302. /**
  5303. * Processes the data for topic command.
  5304. * @param commandArguments the arguments of the topic command.
  5305. */
  5306. function processTopic(commandArguments)
  5307. {
  5308. var topic = UIUtil.escapeHtml(commandArguments);
  5309. APP.xmpp.setSubject(topic);
  5310. }
  5311. /**
  5312. * Constructs new CommandProccessor instance from a message that
  5313. * handles commands received via chat messages.
  5314. * @param message the message
  5315. * @constructor
  5316. */
  5317. function CommandsProcessor(message)
  5318. {
  5319. var command = getCommand(message);
  5320. /**
  5321. * Returns the name of the command.
  5322. * @returns {String} the command
  5323. */
  5324. this.getCommand = function()
  5325. {
  5326. return command;
  5327. };
  5328. var messageArgument = message.substr(command.length + 2);
  5329. /**
  5330. * Returns the arguments of the command.
  5331. * @returns {string}
  5332. */
  5333. this.getArgument = function()
  5334. {
  5335. return messageArgument;
  5336. };
  5337. }
  5338. /**
  5339. * Checks whether this instance is valid command or not.
  5340. * @returns {boolean}
  5341. */
  5342. CommandsProcessor.prototype.isCommand = function()
  5343. {
  5344. if(this.getCommand())
  5345. return true;
  5346. return false;
  5347. };
  5348. /**
  5349. * Processes the command.
  5350. */
  5351. CommandsProcessor.prototype.processCommand = function()
  5352. {
  5353. if(!this.isCommand())
  5354. return;
  5355. commands[this.getCommand()](this.getArgument());
  5356. };
  5357. module.exports = CommandsProcessor;
  5358. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5359. var Smileys = require("./smileys.json");
  5360. /**
  5361. * Processes links and smileys in "body"
  5362. */
  5363. function processReplacements(body)
  5364. {
  5365. //make links clickable
  5366. body = linkify(body);
  5367. //add smileys
  5368. body = smilify(body);
  5369. return body;
  5370. }
  5371. /**
  5372. * Finds and replaces all links in the links in "body"
  5373. * with their <a href=""></a>
  5374. */
  5375. function linkify(inputText)
  5376. {
  5377. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5378. //URLs starting with http://, https://, or ftp://
  5379. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5380. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5381. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5382. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5383. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5384. //Change email addresses to mailto:: links.
  5385. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5386. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5387. return replacedText;
  5388. }
  5389. /**
  5390. * Replaces common smiley strings with images
  5391. */
  5392. function smilify(body)
  5393. {
  5394. if(!body) {
  5395. return body;
  5396. }
  5397. var regexs = Smileys["regexs"];
  5398. for(var smiley in regexs) {
  5399. if(regexs.hasOwnProperty(smiley)) {
  5400. body = body.replace(regexs[smiley],
  5401. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5402. }
  5403. }
  5404. return body;
  5405. }
  5406. module.exports = {
  5407. processReplacements: processReplacements,
  5408. linkify: linkify
  5409. };
  5410. },{"./smileys.json":24}],24:[function(require,module,exports){
  5411. module.exports={
  5412. "smileys": {
  5413. "smiley1": ":)",
  5414. "smiley2": ":(",
  5415. "smiley3": ":D",
  5416. "smiley4": "(y)",
  5417. "smiley5": " :P",
  5418. "smiley6": "(wave)",
  5419. "smiley7": "(blush)",
  5420. "smiley8": "(chuckle)",
  5421. "smiley9": "(shocked)",
  5422. "smiley10": ":*",
  5423. "smiley11": "(n)",
  5424. "smiley12": "(search)",
  5425. "smiley13": " <3",
  5426. "smiley14": "(oops)",
  5427. "smiley15": "(angry)",
  5428. "smiley16": "(angel)",
  5429. "smiley17": "(sick)",
  5430. "smiley18": ";(",
  5431. "smiley19": "(bomb)",
  5432. "smiley20": "(clap)",
  5433. "smiley21": " ;)"
  5434. },
  5435. "regexs": {
  5436. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5437. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5438. "smiley1": /(:-\)|:\))/gi,
  5439. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5440. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5441. "smiley6": /(\(wave\))/gi,
  5442. "smiley7": /(\(blush\))/gi,
  5443. "smiley8": /(\(chuckle\))/gi,
  5444. "smiley9": /(:-0|\(shocked\))/gi,
  5445. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5446. "smiley11": /(\(n\))/gi,
  5447. "smiley12": /(\(search\))/g,
  5448. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5449. "smiley14": /(\(oops\))/gi,
  5450. "smiley15": /(\(angry\))/gi,
  5451. "smiley16": /(\(angel\))/gi,
  5452. "smiley17": /(\(sick\))/gi,
  5453. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5454. "smiley19": /(\(bomb\))/gi,
  5455. "smiley20": /(\(clap\))/gi,
  5456. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5457. }
  5458. }
  5459. },{}],25:[function(require,module,exports){
  5460. var numberOfContacts = 0;
  5461. var notificationInterval;
  5462. /**
  5463. * Updates the number of participants in the contact list button and sets
  5464. * the glow
  5465. * @param delta indicates whether a new user has joined (1) or someone has
  5466. * left(-1)
  5467. */
  5468. function updateNumberOfParticipants(delta) {
  5469. numberOfContacts += delta;
  5470. if (numberOfContacts === 1) {
  5471. // when the user is alone we don't show the number of participants
  5472. $("#numberOfParticipants").text('');
  5473. ContactList.setVisualNotification(false);
  5474. } else if (numberOfContacts > 1) {
  5475. ContactList.setVisualNotification(!ContactList.isVisible());
  5476. $("#numberOfParticipants").text(numberOfContacts);
  5477. } else {
  5478. console.error("Invalid number of participants: " + numberOfContacts);
  5479. }
  5480. }
  5481. /**
  5482. * Creates the avatar element.
  5483. *
  5484. * @return the newly created avatar element
  5485. */
  5486. function createAvatar(id) {
  5487. var avatar = document.createElement('img');
  5488. avatar.className = "icon-avatar avatar";
  5489. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  5490. return avatar;
  5491. }
  5492. /**
  5493. * Creates the display name paragraph.
  5494. *
  5495. * @param displayName the display name to set
  5496. */
  5497. function createDisplayNameParagraph(key, displayName) {
  5498. var p = document.createElement('p');
  5499. if(displayName)
  5500. p.innerText = displayName;
  5501. else if(key)
  5502. {
  5503. p.setAttribute("data-i18n",key);
  5504. p.innerText = APP.translation.translateString(key);
  5505. }
  5506. return p;
  5507. }
  5508. function stopGlowing(glower) {
  5509. window.clearInterval(notificationInterval);
  5510. notificationInterval = false;
  5511. glower.removeClass('glowing');
  5512. if (!ContactList.isVisible()) {
  5513. glower.removeClass('active');
  5514. }
  5515. }
  5516. /**
  5517. * Contact list.
  5518. */
  5519. var ContactList = {
  5520. /**
  5521. * Indicates if the chat is currently visible.
  5522. *
  5523. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5524. * otherwise
  5525. */
  5526. isVisible: function () {
  5527. return $('#contactlist').is(":visible");
  5528. },
  5529. /**
  5530. * Adds a contact for the given peerJid if such doesn't yet exist.
  5531. *
  5532. * @param peerJid the peerJid corresponding to the contact
  5533. * @param id the user's email or userId used to get the user's avatar
  5534. */
  5535. ensureAddContact: function (peerJid, id) {
  5536. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5537. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5538. if (!contact || contact.length <= 0)
  5539. ContactList.addContact(peerJid, id);
  5540. },
  5541. /**
  5542. * Adds a contact for the given peer jid.
  5543. *
  5544. * @param peerJid the jid of the contact to add
  5545. * @param id the email or userId of the user
  5546. */
  5547. addContact: function (peerJid, id) {
  5548. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5549. var contactlist = $('#contacts');
  5550. var newContact = document.createElement('li');
  5551. newContact.id = resourceJid;
  5552. newContact.className = "clickable";
  5553. newContact.onclick = function (event) {
  5554. if (event.currentTarget.className === "clickable") {
  5555. $(ContactList).trigger('contactclicked', [peerJid]);
  5556. }
  5557. };
  5558. newContact.appendChild(createAvatar(id));
  5559. newContact.appendChild(createDisplayNameParagraph("participant"));
  5560. if (resourceJid === APP.xmpp.myResource()) {
  5561. contactlist.prepend(newContact);
  5562. }
  5563. else {
  5564. contactlist.append(newContact);
  5565. }
  5566. updateNumberOfParticipants(1);
  5567. },
  5568. /**
  5569. * Removes a contact for the given peer jid.
  5570. *
  5571. * @param peerJid the peerJid corresponding to the contact to remove
  5572. */
  5573. removeContact: function (peerJid) {
  5574. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5575. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5576. if (contact && contact.length > 0) {
  5577. var contactlist = $('#contactlist>ul');
  5578. contactlist.get(0).removeChild(contact.get(0));
  5579. updateNumberOfParticipants(-1);
  5580. }
  5581. },
  5582. setVisualNotification: function (show, stopGlowingIn) {
  5583. var glower = $('#contactListButton');
  5584. if (show && !notificationInterval) {
  5585. notificationInterval = window.setInterval(function () {
  5586. glower.toggleClass('active glowing');
  5587. }, 800);
  5588. }
  5589. else if (!show && notificationInterval) {
  5590. stopGlowing(glower);
  5591. }
  5592. if (stopGlowingIn) {
  5593. setTimeout(function () {
  5594. stopGlowing(glower);
  5595. }, stopGlowingIn);
  5596. }
  5597. },
  5598. setClickable: function (resourceJid, isClickable) {
  5599. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5600. if (isClickable) {
  5601. contact.addClass('clickable');
  5602. } else {
  5603. contact.removeClass('clickable');
  5604. }
  5605. },
  5606. onDisplayNameChange: function (peerJid, displayName) {
  5607. if (peerJid === 'localVideoContainer')
  5608. peerJid = APP.xmpp.myJid();
  5609. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5610. var contactName = $('#contacts #' + resourceJid + '>p');
  5611. if (contactName && displayName && displayName.length > 0)
  5612. contactName.html(displayName);
  5613. },
  5614. userAvatarChanged: function (resourceJid, contactListUrl) {
  5615. // set the avatar in the contact list
  5616. var contact = $('#' + resourceJid + '>img');
  5617. if (contact && contact.length > 0) {
  5618. contact.get(0).src = contactListUrl;
  5619. }
  5620. }
  5621. };
  5622. module.exports = ContactList;
  5623. },{}],26:[function(require,module,exports){
  5624. var Avatar = require("../../avatar/Avatar");
  5625. var Settings = require("./../../../settings/Settings");
  5626. var UIUtil = require("../../util/UIUtil");
  5627. var languages = require("../../../../service/translation/languages");
  5628. function generateLanguagesSelectBox()
  5629. {
  5630. var currentLang = APP.translation.getCurrentLanguage();
  5631. var html = "<select id=\"languages_selectbox\">";
  5632. var langArray = languages.getLanguages();
  5633. for(var i = 0; i < langArray.length; i++)
  5634. {
  5635. var lang = langArray[i];
  5636. html += "<option ";
  5637. if(lang === currentLang)
  5638. html += "selected ";
  5639. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5640. html += "</option>";
  5641. }
  5642. return html + "</select>";
  5643. }
  5644. var SettingsMenu = {
  5645. init: function () {
  5646. $("#startMutedOptions").before(generateLanguagesSelectBox());
  5647. APP.translation.translateElement($("#languages_selectbox"));
  5648. $('#settingsmenu>input').keyup(function(event){
  5649. if(event.keyCode === 13) {//enter
  5650. SettingsMenu.update();
  5651. }
  5652. });
  5653. if(APP.xmpp.isModerator())
  5654. {
  5655. $("#startMutedOptions").css("display", "block");
  5656. }
  5657. else
  5658. {
  5659. $("#startMutedOptions").css("display", "none");
  5660. }
  5661. $("#updateSettings").click(function () {
  5662. SettingsMenu.update();
  5663. });
  5664. },
  5665. onRoleChanged: function () {
  5666. if(APP.xmpp.isModerator())
  5667. {
  5668. $("#startMutedOptions").css("display", "block");
  5669. }
  5670. else
  5671. {
  5672. $("#startMutedOptions").css("display", "none");
  5673. }
  5674. },
  5675. setStartMuted: function (audio, video) {
  5676. $("#startAudioMuted").attr("checked", audio);
  5677. $("#startVideoMuted").attr("checked", video);
  5678. },
  5679. update: function() {
  5680. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5681. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5682. if(newDisplayName) {
  5683. var displayName = Settings.setDisplayName(newDisplayName);
  5684. APP.xmpp.addToPresence("displayName", displayName, true);
  5685. }
  5686. var language = $("#languages_selectbox").val();
  5687. APP.translation.setLanguage(language);
  5688. Settings.setLanguage(language);
  5689. APP.xmpp.addToPresence("email", newEmail);
  5690. var email = Settings.setEmail(newEmail);
  5691. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5692. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5693. APP.xmpp.addToPresence("startMuted",
  5694. [startAudioMuted, startVideoMuted]);
  5695. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5696. },
  5697. isVisible: function() {
  5698. return $('#settingsmenu').is(':visible');
  5699. },
  5700. setDisplayName: function(newDisplayName) {
  5701. var displayName = Settings.setDisplayName(newDisplayName);
  5702. $('#setDisplayName').get(0).value = displayName;
  5703. },
  5704. onDisplayNameChange: function(peerJid, newDisplayName) {
  5705. if(peerJid === 'localVideoContainer' ||
  5706. peerJid === APP.xmpp.myJid()) {
  5707. this.setDisplayName(newDisplayName);
  5708. }
  5709. },
  5710. changeAvatar: function (thumbUrl) {
  5711. $('#avatar').get(0).src = thumbUrl;
  5712. }
  5713. };
  5714. module.exports = SettingsMenu;
  5715. },{"../../../../service/translation/languages":107,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5716. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5717. var buttonHandlers = {
  5718. "bottom_toolbar_contact_list": function () {
  5719. BottomToolbar.toggleContactList();
  5720. },
  5721. "bottom_toolbar_film_strip": function () {
  5722. BottomToolbar.toggleFilmStrip();
  5723. },
  5724. "bottom_toolbar_chat": function () {
  5725. BottomToolbar.toggleChat();
  5726. }
  5727. };
  5728. var BottomToolbar = (function (my) {
  5729. my.init = function () {
  5730. for(var k in buttonHandlers)
  5731. $("#" + k).click(buttonHandlers[k]);
  5732. };
  5733. my.toggleChat = function() {
  5734. PanelToggler.toggleChat();
  5735. };
  5736. my.toggleContactList = function() {
  5737. PanelToggler.toggleContactList();
  5738. };
  5739. my.toggleFilmStrip = function() {
  5740. var filmstrip = $("#remoteVideos");
  5741. filmstrip.toggleClass("hidden");
  5742. };
  5743. $(document).bind("remotevideo.resized", function (event, width, height) {
  5744. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5745. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5746. });
  5747. return my;
  5748. }(BottomToolbar || {}));
  5749. module.exports = BottomToolbar;
  5750. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5751. /* global APP,$, buttonClick, config, lockRoom,
  5752. setSharedKey, Util */
  5753. var messageHandler = require("../util/MessageHandler");
  5754. var BottomToolbar = require("./BottomToolbar");
  5755. var Prezi = require("../prezi/Prezi");
  5756. var Etherpad = require("../etherpad/Etherpad");
  5757. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5758. var Authentication = require("../authentication/Authentication");
  5759. var UIUtil = require("../util/UIUtil");
  5760. var AuthenticationEvents
  5761. = require("../../../service/authentication/AuthenticationEvents");
  5762. var roomUrl = null;
  5763. var sharedKey = '';
  5764. var UI = null;
  5765. var buttonHandlers =
  5766. {
  5767. "toolbar_button_mute": function () {
  5768. return APP.UI.toggleAudio();
  5769. },
  5770. "toolbar_button_camera": function () {
  5771. return APP.UI.toggleVideo();
  5772. },
  5773. /*"toolbar_button_authentication": function () {
  5774. return Toolbar.authenticateClicked();
  5775. },*/
  5776. "toolbar_button_record": function () {
  5777. return toggleRecording();
  5778. },
  5779. "toolbar_button_security": function () {
  5780. return Toolbar.openLockDialog();
  5781. },
  5782. "toolbar_button_link": function () {
  5783. return Toolbar.openLinkDialog();
  5784. },
  5785. "toolbar_button_chat": function () {
  5786. return BottomToolbar.toggleChat();
  5787. },
  5788. "toolbar_button_prezi": function () {
  5789. return Prezi.openPreziDialog();
  5790. },
  5791. "toolbar_button_etherpad": function () {
  5792. return Etherpad.toggleEtherpad(0);
  5793. },
  5794. "toolbar_button_desktopsharing": function () {
  5795. return APP.desktopsharing.toggleScreenSharing();
  5796. },
  5797. "toolbar_button_fullScreen": function()
  5798. {
  5799. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  5800. return Toolbar.toggleFullScreen();
  5801. },
  5802. "toolbar_button_sip": function () {
  5803. return callSipButtonClicked();
  5804. },
  5805. "toolbar_button_dialpad": function () {
  5806. return dialpadButtonClicked();
  5807. },
  5808. "toolbar_button_settings": function () {
  5809. PanelToggler.toggleSettingsMenu();
  5810. },
  5811. "toolbar_button_hangup": function () {
  5812. return hangup();
  5813. },
  5814. "toolbar_button_login": function () {
  5815. Toolbar.authenticateClicked();
  5816. },
  5817. "toolbar_button_logout": function () {
  5818. // Ask for confirmation
  5819. messageHandler.openTwoButtonDialog(
  5820. "dialog.logoutTitle",
  5821. null,
  5822. "dialog.logoutQuestion",
  5823. null,
  5824. false,
  5825. "dialog.Yes",
  5826. function (evt, yes) {
  5827. if (yes) {
  5828. APP.xmpp.logout(function (url) {
  5829. if (url) {
  5830. window.location.href = url;
  5831. } else {
  5832. hangup();
  5833. }
  5834. });
  5835. }
  5836. });
  5837. }
  5838. };
  5839. function hangup() {
  5840. APP.xmpp.disposeConference();
  5841. if(config.enableWelcomePage)
  5842. {
  5843. setTimeout(function()
  5844. {
  5845. window.localStorage.welcomePageDisabled = false;
  5846. window.location.pathname = "/";
  5847. }, 10000);
  5848. }
  5849. var title = APP.translation.generateTranslationHTML(
  5850. "dialog.sessTerminated");
  5851. var msg = APP.translation.generateTranslationHTML(
  5852. "dialog.hungUp");
  5853. var button = APP.translation.generateTranslationHTML(
  5854. "dialog.joinAgain");
  5855. var buttons = [];
  5856. buttons.push({title: button, value: true});
  5857. UI.messageHandler.openDialog(
  5858. title,
  5859. msg,
  5860. true,
  5861. buttons,
  5862. function(event, value, message, formVals)
  5863. {
  5864. window.location.reload();
  5865. return false;
  5866. }
  5867. );
  5868. }
  5869. /**
  5870. * Starts or stops the recording for the conference.
  5871. */
  5872. function toggleRecording() {
  5873. APP.xmpp.toggleRecording(function (callback) {
  5874. var msg = APP.translation.generateTranslationHTML(
  5875. "dialog.recordingToken");
  5876. var token = APP.translation.translateString("dialog.token");
  5877. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5878. '<h2>' + msg + '</h2>' +
  5879. '<input name="recordingToken" type="text" ' +
  5880. ' data-i18n="[placeholder]dialog.token" ' +
  5881. 'placeholder="' + token + '" autofocus>',
  5882. false,
  5883. "dialog.Save",
  5884. function (e, v, m, f) {
  5885. if (v) {
  5886. var token = f.recordingToken;
  5887. if (token) {
  5888. callback(UIUtil.escapeHtml(token));
  5889. }
  5890. }
  5891. },
  5892. null,
  5893. function () { },
  5894. ':input:first'
  5895. );
  5896. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  5897. }
  5898. /**
  5899. * Locks / unlocks the room.
  5900. */
  5901. function lockRoom(lock) {
  5902. var currentSharedKey = '';
  5903. if (lock)
  5904. currentSharedKey = sharedKey;
  5905. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5906. // password is required
  5907. if (sharedKey)
  5908. {
  5909. console.log('set room password');
  5910. Toolbar.lockLockButton();
  5911. }
  5912. else
  5913. {
  5914. console.log('removed room password');
  5915. Toolbar.unlockLockButton();
  5916. }
  5917. }, function (err) {
  5918. console.warn('setting password failed', err);
  5919. messageHandler.showError("dialog.lockTitle",
  5920. "dialog.lockMessage");
  5921. Toolbar.setSharedKey('');
  5922. }, function () {
  5923. console.warn('room passwords not supported');
  5924. messageHandler.showError("dialog.warning",
  5925. "dialog.passwordNotSupported");
  5926. Toolbar.setSharedKey('');
  5927. });
  5928. };
  5929. /**
  5930. * Invite participants to conference.
  5931. */
  5932. function inviteParticipants() {
  5933. if (roomUrl === null)
  5934. return;
  5935. var sharedKeyText = "";
  5936. if (sharedKey && sharedKey.length > 0) {
  5937. sharedKeyText =
  5938. APP.translation.translateString("email.sharedKey",
  5939. {sharedKey: sharedKey});
  5940. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5941. }
  5942. var supportedBrowsers = "Chromium, Google Chrome " +
  5943. APP.translation.translateString("email.and") + " Opera";
  5944. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5945. var subject = APP.translation.translateString("email.subject",
  5946. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5947. var body = APP.translation.translateString("email.body",
  5948. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5949. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5950. body = body.replace(/\n/g, "%0D%0A");
  5951. if (window.localStorage.displayname) {
  5952. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5953. }
  5954. if (interfaceConfig.INVITATION_POWERED_BY) {
  5955. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5956. }
  5957. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5958. }
  5959. function dialpadButtonClicked()
  5960. {
  5961. //TODO show the dialpad window
  5962. }
  5963. function callSipButtonClicked()
  5964. {
  5965. var defaultNumber
  5966. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5967. var sipMsg = APP.translation.generateTranslationHTML(
  5968. "dialog.sipMsg");
  5969. messageHandler.openTwoButtonDialog(null, null, null,
  5970. '<h2>' + sipMsg + '</h2>' +
  5971. '<input name="sipNumber" type="text"' +
  5972. ' value="' + defaultNumber + '" autofocus>',
  5973. false,
  5974. "dialog.Dial",
  5975. function (e, v, m, f) {
  5976. if (v) {
  5977. var numberInput = f.sipNumber;
  5978. if (numberInput) {
  5979. APP.xmpp.dial(
  5980. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5981. }
  5982. }
  5983. },
  5984. null, null, ':input:first'
  5985. );
  5986. }
  5987. var Toolbar = (function (my) {
  5988. my.init = function (ui) {
  5989. for(var k in buttonHandlers)
  5990. $("#" + k).click(buttonHandlers[k]);
  5991. UI = ui;
  5992. // Update login info
  5993. APP.xmpp.addListener(
  5994. AuthenticationEvents.IDENTITY_UPDATED,
  5995. function (authenticationEnabled, userIdentity) {
  5996. var loggedIn = false;
  5997. if (userIdentity) {
  5998. loggedIn = true;
  5999. }
  6000. Toolbar.showAuthenticateButton(authenticationEnabled);
  6001. if (authenticationEnabled) {
  6002. Toolbar.setAuthenticatedIdentity(userIdentity);
  6003. Toolbar.showLoginButton(!loggedIn);
  6004. Toolbar.showLogoutButton(loggedIn);
  6005. }
  6006. }
  6007. );
  6008. },
  6009. /**
  6010. * Sets shared key
  6011. * @param sKey the shared key
  6012. */
  6013. my.setSharedKey = function (sKey) {
  6014. sharedKey = sKey;
  6015. };
  6016. my.authenticateClicked = function () {
  6017. Authentication.focusAuthenticationWindow();
  6018. if (!APP.xmpp.isExternalAuthEnabled()) {
  6019. Authentication.xmppAuthenticate();
  6020. return;
  6021. }
  6022. // Get authentication URL
  6023. if (!APP.xmpp.getMUCJoined()) {
  6024. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6025. // If conference has not been started yet - redirect to login page
  6026. window.location.href = url;
  6027. });
  6028. } else {
  6029. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6030. // Otherwise - open popup with authentication URL
  6031. var authenticationWindow = Authentication.createAuthenticationWindow(
  6032. function () {
  6033. // On popup closed - retry room allocation
  6034. APP.xmpp.allocateConferenceFocus(
  6035. APP.UI.getRoomName(),
  6036. function () { console.info("AUTH DONE"); }
  6037. );
  6038. }, url);
  6039. if (!authenticationWindow) {
  6040. messageHandler.openMessageDialog(
  6041. null, "dialog.popupError");
  6042. }
  6043. });
  6044. }
  6045. };
  6046. /**
  6047. * Updates the room invite url.
  6048. */
  6049. my.updateRoomUrl = function (newRoomUrl) {
  6050. roomUrl = newRoomUrl;
  6051. // If the invite dialog has been already opened we update the information.
  6052. var inviteLink = document.getElementById('inviteLinkRef');
  6053. if (inviteLink) {
  6054. inviteLink.value = roomUrl;
  6055. inviteLink.select();
  6056. $('#inviteLinkRef').parent()
  6057. .find('button[value=true]').prop('disabled', false);
  6058. }
  6059. };
  6060. /**
  6061. * Disables and enables some of the buttons.
  6062. */
  6063. my.setupButtonsFromConfig = function () {
  6064. if (config.disablePrezi)
  6065. {
  6066. $("#prezi_button").css({display: "none"});
  6067. }
  6068. };
  6069. /**
  6070. * Opens the lock room dialog.
  6071. */
  6072. my.openLockDialog = function () {
  6073. // Only the focus is able to set a shared key.
  6074. if (!APP.xmpp.isModerator()) {
  6075. if (sharedKey) {
  6076. messageHandler.openMessageDialog(null,
  6077. "dialog.passwordError");
  6078. } else {
  6079. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6080. }
  6081. } else {
  6082. if (sharedKey) {
  6083. messageHandler.openTwoButtonDialog(null, null,
  6084. "dialog.passwordCheck",
  6085. null,
  6086. false,
  6087. "dialog.Remove",
  6088. function (e, v) {
  6089. if (v) {
  6090. Toolbar.setSharedKey('');
  6091. lockRoom(false);
  6092. }
  6093. });
  6094. } else {
  6095. var msg = APP.translation.generateTranslationHTML(
  6096. "dialog.passwordMsg");
  6097. var yourPassword = APP.translation.translateString(
  6098. "dialog.yourPassword");
  6099. messageHandler.openTwoButtonDialog(null, null, null,
  6100. '<h2>' + msg + '</h2>' +
  6101. '<input name="lockKey" type="text"' +
  6102. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6103. 'placeholder="' + yourPassword + '" autofocus>',
  6104. false,
  6105. "dialog.Save",
  6106. function (e, v, m, f) {
  6107. if (v) {
  6108. var lockKey = f.lockKey;
  6109. if (lockKey) {
  6110. Toolbar.setSharedKey(
  6111. UIUtil.escapeHtml(lockKey));
  6112. lockRoom(true);
  6113. }
  6114. }
  6115. },
  6116. null, null, 'input:first'
  6117. );
  6118. }
  6119. }
  6120. };
  6121. /**
  6122. * Opens the invite link dialog.
  6123. */
  6124. my.openLinkDialog = function () {
  6125. var inviteAttreibutes;
  6126. if (roomUrl === null) {
  6127. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6128. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6129. } else {
  6130. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6131. }
  6132. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6133. null, null,
  6134. '<input id="inviteLinkRef" type="text" ' +
  6135. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6136. false,
  6137. "dialog.Invite",
  6138. function (e, v) {
  6139. if (v) {
  6140. if (roomUrl) {
  6141. inviteParticipants();
  6142. }
  6143. }
  6144. },
  6145. function (event) {
  6146. if (roomUrl) {
  6147. document.getElementById('inviteLinkRef').select();
  6148. } else {
  6149. if (event && event.target)
  6150. $(event.target)
  6151. .find('button[value=true]').prop('disabled', true);
  6152. }
  6153. }
  6154. );
  6155. };
  6156. /**
  6157. * Opens the settings dialog.
  6158. * FIXME: not used ?
  6159. */
  6160. my.openSettingsDialog = function () {
  6161. var settings1 = APP.translation.generateTranslationHTML(
  6162. "dialog.settings1");
  6163. var settings2 = APP.translation.generateTranslationHTML(
  6164. "dialog.settings2");
  6165. var settings3 = APP.translation.generateTranslationHTML(
  6166. "dialog.settings3");
  6167. var yourPassword = APP.translation.translateString(
  6168. "dialog.yourPassword");
  6169. messageHandler.openTwoButtonDialog(null,
  6170. '<h2>' + settings1 + '</h2>' +
  6171. '<input type="checkbox" id="initMuted">' +
  6172. settings2 + '<br/>' +
  6173. '<input type="checkbox" id="requireNicknames">' +
  6174. settings3 +
  6175. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6176. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6177. null,
  6178. null,
  6179. false,
  6180. "dialog.Save",
  6181. function () {
  6182. document.getElementById('lockKey').focus();
  6183. },
  6184. function (e, v) {
  6185. if (v) {
  6186. if ($('#initMuted').is(":checked")) {
  6187. // it is checked
  6188. }
  6189. if ($('#requireNicknames').is(":checked")) {
  6190. // it is checked
  6191. }
  6192. /*
  6193. var lockKey = document.getElementById('lockKey');
  6194. if (lockKey.value) {
  6195. setSharedKey(lockKey.value);
  6196. lockRoom(true);
  6197. }
  6198. */
  6199. }
  6200. }
  6201. );
  6202. };
  6203. /**
  6204. * Toggles the application in and out of full screen mode
  6205. * (a.k.a. presentation mode in Chrome).
  6206. */
  6207. my.toggleFullScreen = function () {
  6208. var fsElement = document.documentElement;
  6209. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6210. //Enter Full Screen
  6211. if (fsElement.mozRequestFullScreen) {
  6212. fsElement.mozRequestFullScreen();
  6213. }
  6214. else {
  6215. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6216. }
  6217. } else {
  6218. //Exit Full Screen
  6219. if (document.mozCancelFullScreen) {
  6220. document.mozCancelFullScreen();
  6221. } else {
  6222. document.webkitCancelFullScreen();
  6223. }
  6224. }
  6225. };
  6226. /**
  6227. * Unlocks the lock button state.
  6228. */
  6229. my.unlockLockButton = function () {
  6230. if ($("#lockIcon").hasClass("icon-security-locked"))
  6231. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6232. };
  6233. /**
  6234. * Updates the lock button state to locked.
  6235. */
  6236. my.lockLockButton = function () {
  6237. if ($("#lockIcon").hasClass("icon-security"))
  6238. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6239. };
  6240. /**
  6241. * Shows or hides authentication button
  6242. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6243. */
  6244. my.showAuthenticateButton = function (show) {
  6245. if (show) {
  6246. $('#authentication').css({display: "inline"});
  6247. }
  6248. else {
  6249. $('#authentication').css({display: "none"});
  6250. }
  6251. };
  6252. // Shows or hides the 'recording' button.
  6253. my.showRecordingButton = function (show) {
  6254. if (!config.enableRecording) {
  6255. return;
  6256. }
  6257. if (show) {
  6258. $('#recording').css({display: "inline"});
  6259. }
  6260. else {
  6261. $('#recording').css({display: "none"});
  6262. }
  6263. };
  6264. // Sets the state of the recording button
  6265. my.setRecordingButtonState = function (isRecording) {
  6266. var selector = $('#recordButton');
  6267. if (isRecording) {
  6268. selector.removeClass("icon-recEnable");
  6269. selector.addClass("icon-recEnable active");
  6270. } else {
  6271. selector.removeClass("icon-recEnable active");
  6272. selector.addClass("icon-recEnable");
  6273. }
  6274. };
  6275. // Shows or hides SIP calls button
  6276. my.showSipCallButton = function (show) {
  6277. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6278. $('#sipCallButton').css({display: "inline-block"});
  6279. } else {
  6280. $('#sipCallButton').css({display: "none"});
  6281. }
  6282. };
  6283. // Shows or hides the dialpad button
  6284. my.showDialPadButton = function (show) {
  6285. if (show) {
  6286. $('#dialPadButton').css({display: "inline-block"});
  6287. } else {
  6288. $('#dialPadButton').css({display: "none"});
  6289. }
  6290. };
  6291. /**
  6292. * Displays user authenticated identity name(login).
  6293. * @param authIdentity identity name to be displayed.
  6294. */
  6295. my.setAuthenticatedIdentity = function (authIdentity) {
  6296. if (authIdentity) {
  6297. var selector = $('#toolbar_auth_identity');
  6298. selector.css({display: "list-item"});
  6299. selector.text(authIdentity);
  6300. } else {
  6301. $('#toolbar_auth_identity').css({display: "none"});
  6302. }
  6303. };
  6304. /**
  6305. * Shows/hides login button.
  6306. * @param show <tt>true</tt> to show
  6307. */
  6308. my.showLoginButton = function (show) {
  6309. if (show) {
  6310. $('#toolbar_button_login').css({display: "list-item"});
  6311. } else {
  6312. $('#toolbar_button_login').css({display: "none"});
  6313. }
  6314. };
  6315. /**
  6316. * Shows/hides logout button.
  6317. * @param show <tt>true</tt> to show
  6318. */
  6319. my.showLogoutButton = function (show) {
  6320. if (show) {
  6321. $('#toolbar_button_logout').css({display: "list-item"});
  6322. } else {
  6323. $('#toolbar_button_logout').css({display: "none"});
  6324. }
  6325. };
  6326. /**
  6327. * Sets the state of the button. The button has blue glow if desktop
  6328. * streaming is active.
  6329. * @param active the state of the desktop streaming.
  6330. */
  6331. my.changeDesktopSharingButtonState = function (active) {
  6332. var button = $("#desktopsharing > a");
  6333. if (active)
  6334. {
  6335. button.addClass("glow");
  6336. }
  6337. else
  6338. {
  6339. button.removeClass("glow");
  6340. }
  6341. };
  6342. return my;
  6343. }(Toolbar || {}));
  6344. module.exports = Toolbar;
  6345. },{"../../../service/authentication/AuthenticationEvents":103,"../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){
  6346. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  6347. var toolbarTimeoutObject,
  6348. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6349. function showDesktopSharingButton() {
  6350. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6351. $('#desktopsharing').css({display: "inline"});
  6352. } else {
  6353. $('#desktopsharing').css({display: "none"});
  6354. }
  6355. }
  6356. /**
  6357. * Hides the toolbar.
  6358. */
  6359. function hideToolbar() {
  6360. if(config.alwaysVisibleToolbar)
  6361. return;
  6362. var header = $("#header"),
  6363. bottomToolbar = $("#bottomToolbar");
  6364. var isToolbarHover = false;
  6365. header.find('*').each(function () {
  6366. var id = $(this).attr('id');
  6367. if ($("#" + id + ":hover").length > 0) {
  6368. isToolbarHover = true;
  6369. }
  6370. });
  6371. if ($("#bottomToolbar:hover").length > 0) {
  6372. isToolbarHover = true;
  6373. }
  6374. clearTimeout(toolbarTimeoutObject);
  6375. toolbarTimeoutObject = null;
  6376. if (!isToolbarHover) {
  6377. header.hide("slide", { direction: "up", duration: 300});
  6378. $('#subject').animate({top: "-=40"}, 300);
  6379. if ($("#remoteVideos").hasClass("hidden")) {
  6380. bottomToolbar.hide(
  6381. "slide", {direction: "right", duration: 300});
  6382. }
  6383. }
  6384. else {
  6385. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6386. }
  6387. }
  6388. var ToolbarToggler = {
  6389. /**
  6390. * Shows the main toolbar.
  6391. */
  6392. showToolbar: function () {
  6393. var header = $("#header"),
  6394. bottomToolbar = $("#bottomToolbar");
  6395. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6396. header.show("slide", { direction: "up", duration: 300});
  6397. $('#subject').animate({top: "+=40"}, 300);
  6398. if (!bottomToolbar.is(":visible")) {
  6399. bottomToolbar.show(
  6400. "slide", {direction: "right", duration: 300});
  6401. }
  6402. if (toolbarTimeoutObject) {
  6403. clearTimeout(toolbarTimeoutObject);
  6404. toolbarTimeoutObject = null;
  6405. }
  6406. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6407. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6408. }
  6409. if (APP.xmpp.isModerator())
  6410. {
  6411. // TODO: Enable settings functionality.
  6412. // Need to uncomment the settings button in index.html.
  6413. // $('#settingsButton').css({visibility:"visible"});
  6414. }
  6415. // Show/hide desktop sharing button
  6416. showDesktopSharingButton();
  6417. },
  6418. /**
  6419. * Docks/undocks the toolbar.
  6420. *
  6421. * @param isDock indicates what operation to perform
  6422. */
  6423. dockToolbar: function (isDock) {
  6424. if (isDock) {
  6425. // First make sure the toolbar is shown.
  6426. if (!$('#header').is(':visible')) {
  6427. this.showToolbar();
  6428. }
  6429. // Then clear the time out, to dock the toolbar.
  6430. if (toolbarTimeoutObject) {
  6431. clearTimeout(toolbarTimeoutObject);
  6432. toolbarTimeoutObject = null;
  6433. }
  6434. }
  6435. else {
  6436. if (!$('#header').is(':visible')) {
  6437. this.showToolbar();
  6438. }
  6439. else {
  6440. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6441. }
  6442. }
  6443. },
  6444. showDesktopSharingButton: showDesktopSharingButton
  6445. };
  6446. module.exports = ToolbarToggler;
  6447. },{}],30:[function(require,module,exports){
  6448. var JitsiPopover = (function () {
  6449. /**
  6450. * Constructs new JitsiPopover and attaches it to the element
  6451. * @param element jquery selector
  6452. * @param options the options for the popover.
  6453. * @constructor
  6454. */
  6455. function JitsiPopover(element, options)
  6456. {
  6457. this.options = {
  6458. skin: "white",
  6459. content: ""
  6460. };
  6461. if(options)
  6462. {
  6463. if(options.skin)
  6464. this.options.skin = options.skin;
  6465. if(options.content)
  6466. this.options.content = options.content;
  6467. }
  6468. this.elementIsHovered = false;
  6469. this.popoverIsHovered = false;
  6470. this.popoverShown = false;
  6471. element.data("jitsi_popover", this);
  6472. this.element = element;
  6473. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6474. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6475. '<div class="jitsiPopupmenuPadding"></div></div>';
  6476. var self = this;
  6477. this.element.on("mouseenter", function () {
  6478. self.elementIsHovered = true;
  6479. self.show();
  6480. }).on("mouseleave", function () {
  6481. self.elementIsHovered = false;
  6482. setTimeout(function () {
  6483. self.hide();
  6484. }, 10);
  6485. });
  6486. }
  6487. /**
  6488. * Shows the popover
  6489. */
  6490. JitsiPopover.prototype.show = function () {
  6491. this.createPopover();
  6492. this.popoverShown = true;
  6493. };
  6494. /**
  6495. * Hides the popover
  6496. */
  6497. JitsiPopover.prototype.hide = function () {
  6498. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  6499. {
  6500. this.forceHide();
  6501. }
  6502. };
  6503. /**
  6504. * Hides the popover
  6505. */
  6506. JitsiPopover.prototype.forceHide = function () {
  6507. $(".jitsipopover").remove();
  6508. this.popoverShown = false;
  6509. };
  6510. /**
  6511. * Creates the popover html
  6512. */
  6513. JitsiPopover.prototype.createPopover = function () {
  6514. $("body").append(this.template);
  6515. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6516. var self = this;
  6517. $(".jitsipopover").on("mouseenter", function () {
  6518. self.popoverIsHovered = true;
  6519. }).on("mouseleave", function () {
  6520. self.popoverIsHovered = false;
  6521. self.hide();
  6522. });
  6523. this.refreshPosition();
  6524. };
  6525. /**
  6526. * Refreshes the position of the popover
  6527. */
  6528. JitsiPopover.prototype.refreshPosition = function () {
  6529. $(".jitsipopover").position({
  6530. my: "bottom",
  6531. at: "top",
  6532. collision: "fit",
  6533. of: this.element,
  6534. using: function (position, elements) {
  6535. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  6536. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  6537. $(".jitsipopover > .arrow").css({left: calcLeft});
  6538. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  6539. }
  6540. });
  6541. };
  6542. /**
  6543. * Updates the content of popover.
  6544. * @param content new content
  6545. */
  6546. JitsiPopover.prototype.updateContent = function (content) {
  6547. this.options.content = content;
  6548. if(!this.popoverShown)
  6549. return;
  6550. $(".jitsipopover").remove();
  6551. this.createPopover();
  6552. };
  6553. return JitsiPopover;
  6554. })();
  6555. module.exports = JitsiPopover;
  6556. },{}],31:[function(require,module,exports){
  6557. /* global $, APP, jQuery, toastr */
  6558. var messageHandler = (function(my) {
  6559. /**
  6560. * Shows a message to the user.
  6561. *
  6562. * @param titleString the title of the message
  6563. * @param messageString the text of the message
  6564. */
  6565. my.openMessageDialog = function(titleKey, messageKey) {
  6566. var title = null;
  6567. if(titleKey)
  6568. {
  6569. title = APP.translation.generateTranslationHTML(titleKey);
  6570. }
  6571. var message = APP.translation.generateTranslationHTML(messageKey);
  6572. $.prompt(message,
  6573. {
  6574. title: title,
  6575. persistent: false
  6576. }
  6577. );
  6578. };
  6579. /**
  6580. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6581. *
  6582. * @param titleString the title of the message
  6583. * @param msgString the text of the message
  6584. * @param persistent boolean value which determines whether the message is persistent or not
  6585. * @param leftButton the fist button's text
  6586. * @param submitFunction function to be called on submit
  6587. * @param loadedFunction function to be called after the prompt is fully loaded
  6588. * @param closeFunction function to be called after the prompt is closed
  6589. * @param focus optional focus selector or button index to be focused after
  6590. * the dialog is opened
  6591. * @param defaultButton index of default button which will be activated when
  6592. * the user press 'enter'. Indexed from 0.
  6593. */
  6594. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6595. persistent, leftButtonKey, submitFunction, loadedFunction,
  6596. closeFunction, focus, defaultButton)
  6597. {
  6598. var buttons = [];
  6599. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6600. buttons.push({ title: leftButton, value: true});
  6601. var cancelButton
  6602. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6603. buttons.push({title: cancelButton, value: false});
  6604. var message = msgString, title = titleString;
  6605. if (titleKey)
  6606. {
  6607. title = APP.translation.generateTranslationHTML(titleKey);
  6608. }
  6609. if (msgKey) {
  6610. message = APP.translation.generateTranslationHTML(msgKey);
  6611. }
  6612. $.prompt(message, {
  6613. title: title,
  6614. persistent: false,
  6615. buttons: buttons,
  6616. defaultButton: defaultButton,
  6617. focus: focus,
  6618. loaded: loadedFunction,
  6619. submit: submitFunction,
  6620. close: closeFunction
  6621. });
  6622. };
  6623. /**
  6624. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6625. *
  6626. * @param titleString the title of the message
  6627. * @param msgString the text of the message
  6628. * @param persistent boolean value which determines whether the message is persistent or not
  6629. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  6630. * that will be passed to submitFunction
  6631. * @param submitFunction function to be called on submit
  6632. * @param loadedFunction function to be called after the prompt is fully loaded
  6633. */
  6634. my.openDialog = function (titleString, msgString, persistent, buttons,
  6635. submitFunction, loadedFunction) {
  6636. var args = {
  6637. title: titleString,
  6638. persistent: persistent,
  6639. buttons: buttons,
  6640. defaultButton: 1,
  6641. loaded: loadedFunction,
  6642. submit: submitFunction
  6643. };
  6644. if (persistent) {
  6645. args.closeText = '';
  6646. }
  6647. return new Impromptu(msgString, args);
  6648. };
  6649. /**
  6650. * Closes currently opened dialog.
  6651. */
  6652. my.closeDialog = function () {
  6653. $.prompt.close();
  6654. };
  6655. /**
  6656. * Shows a dialog with different states to the user.
  6657. *
  6658. * @param statesObject object containing all the states of the dialog
  6659. */
  6660. my.openDialogWithStates = function (statesObject, options) {
  6661. return new Impromptu(statesObject, options);
  6662. };
  6663. /**
  6664. * Opens new popup window for given <tt>url</tt> centered over current
  6665. * window.
  6666. *
  6667. * @param url the URL to be displayed in the popup window
  6668. * @param w the width of the popup window
  6669. * @param h the height of the popup window
  6670. * @param onPopupClosed optional callback function called when popup window
  6671. * has been closed.
  6672. *
  6673. * @returns popup window object if opened successfully or undefined
  6674. * in case we failed to open it(popup blocked)
  6675. */
  6676. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6677. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6678. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6679. var popup = window.open(
  6680. url, '_blank',
  6681. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6682. if (popup && onPopupClosed) {
  6683. var pollTimer = window.setInterval(function () {
  6684. if (popup.closed !== false) {
  6685. window.clearInterval(pollTimer);
  6686. onPopupClosed();
  6687. }
  6688. }, 200);
  6689. }
  6690. return popup;
  6691. };
  6692. /**
  6693. * Shows a dialog prompting the user to send an error report.
  6694. *
  6695. * @param titleString the title of the message
  6696. * @param msgString the text of the message
  6697. * @param error the error that is being reported
  6698. */
  6699. my.openReportDialog = function(titleKey, msgKey, error) {
  6700. my.openMessageDialog(titleKey, msgKey);
  6701. console.log(error);
  6702. //FIXME send the error to the server
  6703. };
  6704. /**
  6705. * Shows an error dialog to the user.
  6706. * @param title the title of the message
  6707. * @param message the text of the messafe
  6708. */
  6709. my.showError = function(titleKey, msgKey) {
  6710. if(!titleKey) {
  6711. titleKey = "dialog.oops";
  6712. }
  6713. if(!msgKey)
  6714. {
  6715. msgKey = "dialog.defaultError";
  6716. }
  6717. messageHandler.openMessageDialog(titleKey, msgKey);
  6718. };
  6719. my.notify = function(displayName, displayNameKey,
  6720. cls, messageKey, messageArguments, options) {
  6721. var displayNameSpan = '<span class="nickname" ';
  6722. if(displayName)
  6723. {
  6724. displayNameSpan += ">" + displayName;
  6725. }
  6726. else
  6727. {
  6728. displayNameSpan += "data-i18n='" + displayNameKey +
  6729. "'>" + APP.translation.translateString(displayNameKey);
  6730. }
  6731. displayNameSpan += "</span>";
  6732. toastr.info(
  6733. displayNameSpan + '<br>' +
  6734. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6735. (messageArguments?
  6736. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6737. : "") + ">" +
  6738. APP.translation.translateString(messageKey,
  6739. messageArguments) +
  6740. '</span>', null, options);
  6741. };
  6742. return my;
  6743. }(messageHandler || {}));
  6744. module.exports = messageHandler;
  6745. },{}],32:[function(require,module,exports){
  6746. var UIEvents = require("../../../service/UI/UIEvents");
  6747. var nickname = null;
  6748. var eventEmitter = null;
  6749. var NickanameHandler = {
  6750. init: function (emitter) {
  6751. eventEmitter = emitter;
  6752. var storedDisplayName = window.localStorage.displayname;
  6753. if (storedDisplayName) {
  6754. nickname = storedDisplayName;
  6755. }
  6756. },
  6757. setNickname: function (newNickname) {
  6758. if (!newNickname || nickname === newNickname)
  6759. return;
  6760. nickname = newNickname;
  6761. window.localStorage.displayname = nickname;
  6762. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6763. },
  6764. getNickname: function () {
  6765. return nickname;
  6766. },
  6767. addListener: function (type, listener) {
  6768. eventEmitter.on(type, listener);
  6769. }
  6770. };
  6771. module.exports = NickanameHandler;
  6772. },{"../../../service/UI/UIEvents":102}],33:[function(require,module,exports){
  6773. /**
  6774. * Created by hristo on 12/22/14.
  6775. */
  6776. module.exports = {
  6777. /**
  6778. * Returns the available video width.
  6779. */
  6780. getAvailableVideoWidth: function (isVisible) {
  6781. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6782. if(typeof isVisible === "undefined" || isVisible === null)
  6783. isVisible = PanelToggler.isVisible();
  6784. var rightPanelWidth
  6785. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6786. return window.innerWidth - rightPanelWidth;
  6787. },
  6788. /**
  6789. * Changes the style class of the element given by id.
  6790. */
  6791. buttonClick: function(id, classname) {
  6792. $(id).toggleClass(classname); // add the class to the clicked element
  6793. },
  6794. /**
  6795. * Returns the text width for the given element.
  6796. *
  6797. * @param el the element
  6798. */
  6799. getTextWidth: function (el) {
  6800. return (el.clientWidth + 1);
  6801. },
  6802. /**
  6803. * Returns the text height for the given element.
  6804. *
  6805. * @param el the element
  6806. */
  6807. getTextHeight: function (el) {
  6808. return (el.clientHeight + 1);
  6809. },
  6810. /**
  6811. * Plays the sound given by id.
  6812. *
  6813. * @param id the identifier of the audio element.
  6814. */
  6815. playSoundNotification: function (id) {
  6816. document.getElementById(id).play();
  6817. },
  6818. /**
  6819. * Escapes the given text.
  6820. */
  6821. escapeHtml: function (unsafeText) {
  6822. return $('<div/>').text(unsafeText).html();
  6823. },
  6824. imageToGrayScale: function (canvas) {
  6825. var context = canvas.getContext('2d');
  6826. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6827. var pixels = imgData.data;
  6828. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6829. var grayscale
  6830. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  6831. pixels[i ] = grayscale; // red
  6832. pixels[i+1] = grayscale; // green
  6833. pixels[i+2] = grayscale; // blue
  6834. // pixels[i+3] is alpha
  6835. }
  6836. // redraw the image in black & white
  6837. context.putImageData(imgData, 0, 0);
  6838. },
  6839. setTooltip: function (element, key, position) {
  6840. element.setAttribute("data-i18n", "[data-content]" + key);
  6841. element.setAttribute("data-toggle", "popover");
  6842. element.setAttribute("data-placement", position);
  6843. element.setAttribute("data-html", true);
  6844. element.setAttribute("data-container", "body");
  6845. }
  6846. };
  6847. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6848. var JitsiPopover = require("../util/JitsiPopover");
  6849. /**
  6850. * Constructs new connection indicator.
  6851. * @param videoContainer the video container associated with the indicator.
  6852. * @constructor
  6853. */
  6854. function ConnectionIndicator(videoContainer, jid)
  6855. {
  6856. this.videoContainer = videoContainer;
  6857. this.bandwidth = null;
  6858. this.packetLoss = null;
  6859. this.bitrate = null;
  6860. this.showMoreValue = false;
  6861. this.resolution = null;
  6862. this.transport = [];
  6863. this.popover = null;
  6864. this.jid = jid;
  6865. this.create();
  6866. }
  6867. /**
  6868. * Values for the connection quality
  6869. * @type {{98: string,
  6870. * 81: string,
  6871. * 64: string,
  6872. * 47: string,
  6873. * 30: string,
  6874. * 0: string}}
  6875. */
  6876. ConnectionIndicator.connectionQualityValues = {
  6877. 98: "18px", //full
  6878. 81: "15px",//4 bars
  6879. 64: "11px",//3 bars
  6880. 47: "7px",//2 bars
  6881. 30: "3px",//1 bar
  6882. 0: "0px"//empty
  6883. };
  6884. ConnectionIndicator.getIP = function(value)
  6885. {
  6886. return value.substring(0, value.lastIndexOf(":"));
  6887. };
  6888. ConnectionIndicator.getPort = function(value)
  6889. {
  6890. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6891. };
  6892. ConnectionIndicator.getStringFromArray = function (array) {
  6893. var res = "";
  6894. for(var i = 0; i < array.length; i++)
  6895. {
  6896. res += (i === 0? "" : ", ") + array[i];
  6897. }
  6898. return res;
  6899. };
  6900. /**
  6901. * Generates the html content.
  6902. * @returns {string} the html content.
  6903. */
  6904. ConnectionIndicator.prototype.generateText = function () {
  6905. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6906. var translate = APP.translation.translateString;
  6907. if(this.bitrate === null)
  6908. {
  6909. downloadBitrate = "N/A";
  6910. uploadBitrate = "N/A";
  6911. }
  6912. else
  6913. {
  6914. downloadBitrate =
  6915. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6916. uploadBitrate =
  6917. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6918. }
  6919. if(this.packetLoss === null)
  6920. {
  6921. packetLoss = "N/A";
  6922. }
  6923. else
  6924. {
  6925. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6926. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  6927. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6928. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  6929. }
  6930. var resolutionValue = null;
  6931. if(this.resolution && this.jid != null)
  6932. {
  6933. var keys = Object.keys(this.resolution);
  6934. for(var ssrc in this.resolution)
  6935. {
  6936. resolutionValue = this.resolution[ssrc];
  6937. }
  6938. }
  6939. if(this.jid === null)
  6940. {
  6941. resolution = "";
  6942. if(this.resolution === null || !Object.keys(this.resolution) ||
  6943. Object.keys(this.resolution).length === 0)
  6944. {
  6945. resolution = "N/A";
  6946. }
  6947. else
  6948. for(i in this.resolution)
  6949. {
  6950. resolutionValue = this.resolution[i];
  6951. if(resolutionValue)
  6952. {
  6953. if(resolutionValue.height &&
  6954. resolutionValue.width)
  6955. {
  6956. resolution += (resolution === ""? "" : ", ") +
  6957. resolutionValue.width + "x" +
  6958. resolutionValue.height;
  6959. }
  6960. }
  6961. }
  6962. }
  6963. else if(!resolutionValue ||
  6964. !resolutionValue.height ||
  6965. !resolutionValue.width)
  6966. {
  6967. resolution = "N/A";
  6968. }
  6969. else
  6970. {
  6971. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6972. }
  6973. var result = "<table style='width:100%'>" +
  6974. "<tr>" +
  6975. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6976. translate("connectionindicator.bitrate") + "</span></td>" +
  6977. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6978. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6979. uploadBitrate + "</td>" +
  6980. "</tr><tr>" +
  6981. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6982. translate("connectionindicator.packetloss") + "</span></td>" +
  6983. "<td>" + packetLoss + "</td>" +
  6984. "</tr><tr>" +
  6985. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6986. translate("connectionindicator.resolution") + "</span></td>" +
  6987. "<td>" + resolution + "</td></tr></table>";
  6988. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6989. result += "<div class=\"jitsipopover_showmore\" " +
  6990. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6991. this.jid + "')\" data-i18n='connectionindicator." +
  6992. (this.showMoreValue ? "less" : "more") + "'>" +
  6993. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6994. "</div><br />";
  6995. }
  6996. if(this.showMoreValue)
  6997. {
  6998. var downloadBandwidth, uploadBandwidth, transport;
  6999. if(this.bandwidth === null)
  7000. {
  7001. downloadBandwidth = "N/A";
  7002. uploadBandwidth = "N/A";
  7003. }
  7004. else
  7005. {
  7006. downloadBandwidth = this.bandwidth.download?
  7007. this.bandwidth.download + " Kbps" :
  7008. "N/A";
  7009. uploadBandwidth = this.bandwidth.upload?
  7010. this.bandwidth.upload + " Kbps" :
  7011. "N/A";
  7012. }
  7013. if(!this.transport || this.transport.length === 0)
  7014. {
  7015. transport = "<tr>" +
  7016. "<td><span class='jitsipopover_blue' " +
  7017. "data-i18n='connectionindicator.address'>" +
  7018. translate("connectionindicator.address") + "</span></td>" +
  7019. "<td> N/A</td></tr>";
  7020. }
  7021. else
  7022. {
  7023. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7024. for(i = 0; i < this.transport.length; i++)
  7025. {
  7026. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7027. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7028. var localIP =
  7029. ConnectionIndicator.getIP(this.transport[i].localip);
  7030. var localPort =
  7031. ConnectionIndicator.getPort(this.transport[i].localip);
  7032. if(data.remoteIP.indexOf(ip) == -1)
  7033. {
  7034. data.remoteIP.push(ip);
  7035. }
  7036. if(data.remotePort.indexOf(port) == -1)
  7037. {
  7038. data.remotePort.push(port);
  7039. }
  7040. if(data.localIP.indexOf(localIP) == -1)
  7041. {
  7042. data.localIP.push(localIP);
  7043. }
  7044. if(data.localPort.indexOf(localPort) == -1)
  7045. {
  7046. data.localPort.push(localPort);
  7047. }
  7048. }
  7049. var local_address_key = "connectionindicator.localaddress";
  7050. var remote_address_key = "connectionindicator.remoteaddress";
  7051. var localTransport =
  7052. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7053. local_address_key +"' data-i18n-options='" +
  7054. JSON.stringify({count: data.localIP.length}) + "'>" +
  7055. translate(local_address_key, {count: data.localIP.length}) +
  7056. "</span></td><td> " +
  7057. ConnectionIndicator.getStringFromArray(data.localIP) +
  7058. "</td></tr>";
  7059. transport =
  7060. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7061. remote_address_key + "' data-i18n-options='" +
  7062. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7063. translate(remote_address_key,
  7064. {count: data.remoteIP.length}) +
  7065. "</span></td><td> " +
  7066. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7067. "</td></tr>";
  7068. var key_remote = "connectionindicator.remoteport",
  7069. key_local = "connectionindicator.localport";
  7070. transport += "<tr>" +
  7071. "<td>" +
  7072. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7073. "' data-i18n-options='" +
  7074. JSON.stringify({count: this.transport.length}) + "'>" +
  7075. translate(key_remote, {count: this.transport.length}) +
  7076. "</span></td><td>";
  7077. localTransport += "<tr>" +
  7078. "<td>" +
  7079. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7080. "' data-i18n-options='" +
  7081. JSON.stringify({count: this.transport.length}) + "'>" +
  7082. translate(key_local, {count: this.transport.length}) +
  7083. "</span></td><td>";
  7084. transport +=
  7085. ConnectionIndicator.getStringFromArray(data.remotePort);
  7086. localTransport +=
  7087. ConnectionIndicator.getStringFromArray(data.localPort);
  7088. transport += "</td></tr>";
  7089. transport += localTransport + "</td></tr>";
  7090. transport +="<tr>" +
  7091. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7092. translate("connectionindicator.transport") + "</span></td>" +
  7093. "<td>" + this.transport[0].type + "</td></tr>";
  7094. }
  7095. result += "<table style='width:100%'>" +
  7096. "<tr>" +
  7097. "<td>" +
  7098. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7099. translate("connectionindicator.bandwidth") + "</span>" +
  7100. "</td><td>" +
  7101. "<span class='jitsipopover_green'>&darr;</span>" +
  7102. downloadBandwidth +
  7103. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7104. uploadBandwidth + "</td></tr>";
  7105. result += transport + "</table>";
  7106. }
  7107. return result;
  7108. };
  7109. /**
  7110. * Shows or hide the additional information.
  7111. */
  7112. ConnectionIndicator.prototype.showMore = function () {
  7113. this.showMoreValue = !this.showMoreValue;
  7114. this.updatePopoverData();
  7115. };
  7116. function createIcon(classes)
  7117. {
  7118. var icon = document.createElement("span");
  7119. for(var i in classes)
  7120. {
  7121. icon.classList.add(classes[i]);
  7122. }
  7123. icon.appendChild(
  7124. document.createElement("i")).classList.add("icon-connection");
  7125. return icon;
  7126. }
  7127. /**
  7128. * Creates the indicator
  7129. */
  7130. ConnectionIndicator.prototype.create = function () {
  7131. this.connectionIndicatorContainer = document.createElement("div");
  7132. this.connectionIndicatorContainer.className = "connectionindicator";
  7133. this.connectionIndicatorContainer.style.display = "none";
  7134. this.videoContainer.container.appendChild(this.connectionIndicatorContainer);
  7135. this.popover = new JitsiPopover(
  7136. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7137. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7138. APP.translation.translateString("connectionindicator.na") + "</div>",
  7139. skin: "black"});
  7140. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7141. createIcon(["connection", "connection_empty"]));
  7142. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7143. createIcon(["connection", "connection_full"]));
  7144. };
  7145. /**
  7146. * Removes the indicator
  7147. */
  7148. ConnectionIndicator.prototype.remove = function()
  7149. {
  7150. if (this.connectionIndicatorContainer.parentNode) {
  7151. this.connectionIndicatorContainer.parentNode.removeChild(
  7152. this.connectionIndicatorContainer);
  7153. }
  7154. this.popover.forceHide();
  7155. };
  7156. /**
  7157. * Updates the data of the indicator
  7158. * @param percent the percent of connection quality
  7159. * @param object the statistics data.
  7160. */
  7161. ConnectionIndicator.prototype.updateConnectionQuality =
  7162. function (percent, object) {
  7163. if(percent === null)
  7164. {
  7165. this.connectionIndicatorContainer.style.display = "none";
  7166. this.popover.forceHide();
  7167. return;
  7168. }
  7169. else
  7170. {
  7171. if(this.connectionIndicatorContainer.style.display == "none") {
  7172. this.connectionIndicatorContainer.style.display = "block";
  7173. this.videoContainer.updateIconPositions();
  7174. }
  7175. }
  7176. this.bandwidth = object.bandwidth;
  7177. this.bitrate = object.bitrate;
  7178. this.packetLoss = object.packetLoss;
  7179. this.transport = object.transport;
  7180. if(object.resolution)
  7181. {
  7182. this.resolution = object.resolution;
  7183. }
  7184. for(var quality in ConnectionIndicator.connectionQualityValues)
  7185. {
  7186. if(percent >= quality)
  7187. {
  7188. this.fullIcon.style.width =
  7189. ConnectionIndicator.connectionQualityValues[quality];
  7190. }
  7191. }
  7192. this.updatePopoverData();
  7193. };
  7194. /**
  7195. * Updates the resolution
  7196. * @param resolution the new resolution
  7197. */
  7198. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7199. this.resolution = resolution;
  7200. this.updatePopoverData();
  7201. };
  7202. /**
  7203. * Updates the content of the popover
  7204. */
  7205. ConnectionIndicator.prototype.updatePopoverData = function () {
  7206. this.popover.updateContent(
  7207. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7208. APP.translation.translateElement($(".connection_info"));
  7209. };
  7210. /**
  7211. * Hides the popover
  7212. */
  7213. ConnectionIndicator.prototype.hide = function () {
  7214. this.popover.forceHide();
  7215. };
  7216. /**
  7217. * Hides the indicator
  7218. */
  7219. ConnectionIndicator.prototype.hideIndicator = function () {
  7220. this.connectionIndicatorContainer.style.display = "none";
  7221. if(this.popover)
  7222. this.popover.forceHide();
  7223. };
  7224. module.exports = ConnectionIndicator;
  7225. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7226. var Avatar = require("../avatar/Avatar");
  7227. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7228. var UIUtil = require("../util/UIUtil");
  7229. var UIEvents = require("../../../service/UI/UIEvents");
  7230. var xmpp = require("../../xmpp/xmpp");
  7231. // FIXME: With Temasys we have to re-select everytime
  7232. //var video = $('#largeVideo');
  7233. var currentVideoWidth = null;
  7234. var currentVideoHeight = null;
  7235. // By default we use camera
  7236. var getVideoSize = getCameraVideoSize;
  7237. var getVideoPosition = getCameraVideoPosition;
  7238. var currentSmallVideo = null;
  7239. var oldSmallVideo = null;
  7240. /**
  7241. * Sets the size and position of the given video element.
  7242. *
  7243. * @param video the video element to position
  7244. * @param width the desired video width
  7245. * @param height the desired video height
  7246. * @param horizontalIndent the left and right indent
  7247. * @param verticalIndent the top and bottom indent
  7248. */
  7249. function positionVideo(video,
  7250. width,
  7251. height,
  7252. horizontalIndent,
  7253. verticalIndent,
  7254. animate) {
  7255. if(animate)
  7256. {
  7257. video.animate({
  7258. width: width,
  7259. height: height,
  7260. top: verticalIndent,
  7261. bottom: verticalIndent,
  7262. left: horizontalIndent,
  7263. right: horizontalIndent
  7264. },
  7265. {
  7266. queue: false,
  7267. duration: 500
  7268. });
  7269. }
  7270. else
  7271. {
  7272. video.width(width);
  7273. video.height(height);
  7274. video.css({ top: verticalIndent + 'px',
  7275. bottom: verticalIndent + 'px',
  7276. left: horizontalIndent + 'px',
  7277. right: horizontalIndent + 'px'});
  7278. }
  7279. }
  7280. /**
  7281. * Returns an array of the video dimensions, so that it keeps it's aspect
  7282. * ratio and fits available area with it's larger dimension. This method
  7283. * ensures that whole video will be visible and can leave empty areas.
  7284. *
  7285. * @return an array with 2 elements, the video width and the video height
  7286. */
  7287. function getDesktopVideoSize(videoWidth,
  7288. videoHeight,
  7289. videoSpaceWidth,
  7290. videoSpaceHeight) {
  7291. if (!videoWidth)
  7292. videoWidth = currentVideoWidth;
  7293. if (!videoHeight)
  7294. videoHeight = currentVideoHeight;
  7295. var aspectRatio = videoWidth / videoHeight;
  7296. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7297. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7298. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7299. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7300. {
  7301. availableHeight = videoSpaceHeight;
  7302. availableWidth = availableHeight * aspectRatio;
  7303. }
  7304. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7305. {
  7306. availableWidth = videoSpaceWidth;
  7307. availableHeight = availableWidth / aspectRatio;
  7308. }
  7309. return [availableWidth, availableHeight];
  7310. }
  7311. /**
  7312. * Returns an array of the video horizontal and vertical indents,
  7313. * so that if fits its parent.
  7314. *
  7315. * @return an array with 2 elements, the horizontal indent and the vertical
  7316. * indent
  7317. */
  7318. function getCameraVideoPosition(videoWidth,
  7319. videoHeight,
  7320. videoSpaceWidth,
  7321. videoSpaceHeight) {
  7322. // Parent height isn't completely calculated when we position the video in
  7323. // full screen mode and this is why we use the screen height in this case.
  7324. // Need to think it further at some point and implement it properly.
  7325. var isFullScreen = document.fullScreen ||
  7326. document.mozFullScreen ||
  7327. document.webkitIsFullScreen;
  7328. if (isFullScreen)
  7329. videoSpaceHeight = window.innerHeight;
  7330. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7331. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7332. return [horizontalIndent, verticalIndent];
  7333. }
  7334. /**
  7335. * Returns an array of the video horizontal and vertical indents.
  7336. * Centers horizontally and top aligns vertically.
  7337. *
  7338. * @return an array with 2 elements, the horizontal indent and the vertical
  7339. * indent
  7340. */
  7341. function getDesktopVideoPosition(videoWidth,
  7342. videoHeight,
  7343. videoSpaceWidth,
  7344. videoSpaceHeight) {
  7345. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7346. var verticalIndent = 0;// Top aligned
  7347. return [horizontalIndent, verticalIndent];
  7348. }
  7349. /**
  7350. * Returns an array of the video dimensions, so that it covers the screen.
  7351. * It leaves no empty areas, but some parts of the video might not be visible.
  7352. *
  7353. * @return an array with 2 elements, the video width and the video height
  7354. */
  7355. function getCameraVideoSize(videoWidth,
  7356. videoHeight,
  7357. videoSpaceWidth,
  7358. videoSpaceHeight) {
  7359. if (!videoWidth)
  7360. videoWidth = currentVideoWidth;
  7361. if (!videoHeight)
  7362. videoHeight = currentVideoHeight;
  7363. var aspectRatio = videoWidth / videoHeight;
  7364. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7365. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7366. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7367. availableHeight = videoSpaceHeight;
  7368. availableWidth = availableHeight * aspectRatio;
  7369. }
  7370. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7371. availableWidth = videoSpaceWidth;
  7372. availableHeight = availableWidth / aspectRatio;
  7373. }
  7374. return [availableWidth, availableHeight];
  7375. }
  7376. /**
  7377. * Updates the src of the active speaker avatar
  7378. * @param jid of the current active speaker
  7379. */
  7380. function updateActiveSpeakerAvatarSrc() {
  7381. var avatar = $("#activeSpeakerAvatar")[0];
  7382. var jid = currentSmallVideo.peerJid;
  7383. var url = Avatar.getGravatarUrl(jid);
  7384. if (avatar.src === url)
  7385. return;
  7386. var isMuted = null;
  7387. if (!currentSmallVideo.isLocal &&
  7388. !LargeVideo.VideoLayout.isInLastN(currentSmallVideo.resourceJid)) {
  7389. isMuted = true;
  7390. }
  7391. else
  7392. {
  7393. isMuted = APP.RTC.isVideoMuted(jid);
  7394. }
  7395. if (jid && isMuted !== null) {
  7396. avatar.src = url;
  7397. $("#largeVideo").css("visibility", isMuted ? "hidden" : "visible");
  7398. currentSmallVideo.showAvatar(isMuted);
  7399. }
  7400. }
  7401. function changeVideo(isVisible) {
  7402. updateActiveSpeakerAvatarSrc();
  7403. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7404. var videoTransform = document.getElementById('largeVideo')
  7405. .style.webkitTransform;
  7406. var flipX = currentSmallVideo.flipX;
  7407. if (flipX && videoTransform !== 'scaleX(-1)') {
  7408. document.getElementById('largeVideo').style.webkitTransform
  7409. = "scaleX(-1)";
  7410. }
  7411. else if (!flipX && videoTransform === 'scaleX(-1)') {
  7412. document.getElementById('largeVideo').style.webkitTransform
  7413. = "none";
  7414. }
  7415. var isDesktop = APP.RTC.isVideoSrcDesktop(currentSmallVideo.peerJid);
  7416. // Change the way we'll be measuring and positioning large video
  7417. getVideoSize = isDesktop
  7418. ? getDesktopVideoSize
  7419. : getCameraVideoSize;
  7420. getVideoPosition = isDesktop
  7421. ? getDesktopVideoPosition
  7422. : getCameraVideoPosition;
  7423. // Only if the large video is currently visible.
  7424. // Disable previous dominant speaker video.
  7425. if (oldSmallVideo) {
  7426. oldSmallVideo.enableDominantSpeaker(false);
  7427. }
  7428. // Enable new dominant speaker in the remote videos section.
  7429. if (currentSmallVideo) {
  7430. currentSmallVideo.enableDominantSpeaker(true);
  7431. }
  7432. if (isVisible) {
  7433. $('#largeVideo').fadeIn(300);
  7434. }
  7435. if(oldSmallVideo)
  7436. oldSmallVideo.showAvatar();
  7437. }
  7438. var LargeVideo = {
  7439. init: function (VideoLayout, emitter) {
  7440. this.VideoLayout = VideoLayout;
  7441. this.eventEmitter = emitter;
  7442. var self = this;
  7443. // Listen for large video size updates
  7444. var largeVideo = $('#largeVideo')[0];
  7445. var onplaying = function (arg1, arg2, arg3) {
  7446. // re-select
  7447. if (RTCBrowserType.isTemasysPluginUsed())
  7448. largeVideo = $('#largeVideo')[0];
  7449. currentVideoWidth = largeVideo.videoWidth;
  7450. currentVideoHeight = largeVideo.videoHeight;
  7451. self.position(currentVideoWidth, currentVideoHeight);
  7452. };
  7453. largeVideo.onplaying = onplaying;
  7454. },
  7455. /**
  7456. * Indicates if the large video is currently visible.
  7457. *
  7458. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7459. */
  7460. isLargeVideoVisible: function() {
  7461. return $('#largeVideo').is(':visible');
  7462. },
  7463. /**
  7464. * Updates the large video with the given new video source.
  7465. */
  7466. updateLargeVideo: function(resourceJid, forceUpdate) {
  7467. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7468. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7469. if ((currentSmallVideo && currentSmallVideo.resourceJid !== resourceJid)
  7470. || forceUpdate) {
  7471. $('#activeSpeaker').css('visibility', 'hidden');
  7472. if(currentSmallVideo) {
  7473. oldSmallVideo = currentSmallVideo;
  7474. } else {
  7475. oldSmallVideo = null;
  7476. }
  7477. currentSmallVideo = newSmallVideo;
  7478. var oldJid = null;
  7479. if(oldSmallVideo)
  7480. oldJid = oldSmallVideo.peerJid;
  7481. if (oldJid !== resourceJid) {
  7482. // we want the notification to trigger even if userJid is undefined,
  7483. // or null.
  7484. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  7485. resourceJid);
  7486. }
  7487. $('#largeVideo').fadeOut(300,
  7488. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7489. } else {
  7490. if(currentSmallVideo) {
  7491. currentSmallVideo.showAvatar();
  7492. }
  7493. }
  7494. },
  7495. /**
  7496. * Shows/hides the large video.
  7497. */
  7498. setLargeVideoVisible: function(isVisible) {
  7499. if (isVisible) {
  7500. $('#largeVideo').css({visibility: 'visible'});
  7501. $('.watermark').css({visibility: 'visible'});
  7502. if(currentSmallVideo)
  7503. currentSmallVideo.enableDominantSpeaker(true);
  7504. }
  7505. else {
  7506. $('#largeVideo').css({visibility: 'hidden'});
  7507. $('#activeSpeaker').css('visibility', 'hidden');
  7508. $('.watermark').css({visibility: 'hidden'});
  7509. if(currentSmallVideo)
  7510. currentSmallVideo.enableDominantSpeaker(false);
  7511. }
  7512. },
  7513. onVideoTypeChanged: function (jid) {
  7514. if(jid && currentSmallVideo && jid === currentSmallVideo.peerJid)
  7515. {
  7516. var isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7517. getVideoSize = isDesktop
  7518. ? getDesktopVideoSize
  7519. : getCameraVideoSize;
  7520. getVideoPosition = isDesktop
  7521. ? getDesktopVideoPosition
  7522. : getCameraVideoPosition;
  7523. this.position(null, null);
  7524. }
  7525. },
  7526. /**
  7527. * Positions the large video.
  7528. *
  7529. * @param videoWidth the stream video width
  7530. * @param videoHeight the stream video height
  7531. */
  7532. position: function (videoWidth, videoHeight,
  7533. videoSpaceWidth, videoSpaceHeight, animate) {
  7534. if(!videoSpaceWidth)
  7535. videoSpaceWidth = $('#videospace').width();
  7536. if(!videoSpaceHeight)
  7537. videoSpaceHeight = window.innerHeight;
  7538. var videoSize = getVideoSize(videoWidth,
  7539. videoHeight,
  7540. videoSpaceWidth,
  7541. videoSpaceHeight);
  7542. var largeVideoWidth = videoSize[0];
  7543. var largeVideoHeight = videoSize[1];
  7544. var videoPosition = getVideoPosition(largeVideoWidth,
  7545. largeVideoHeight,
  7546. videoSpaceWidth,
  7547. videoSpaceHeight);
  7548. var horizontalIndent = videoPosition[0];
  7549. var verticalIndent = videoPosition[1];
  7550. positionVideo($('#largeVideo'),
  7551. largeVideoWidth,
  7552. largeVideoHeight,
  7553. horizontalIndent, verticalIndent, animate);
  7554. },
  7555. isLargeVideoOnTop: function () {
  7556. var Etherpad = require("../etherpad/Etherpad");
  7557. var Prezi = require("../prezi/Prezi");
  7558. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  7559. },
  7560. resize: function (animate, isVisible, completeFunction) {
  7561. var availableHeight = window.innerHeight;
  7562. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7563. if (availableWidth < 0 || availableHeight < 0) return;
  7564. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7565. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7566. $('#activeSpeaker').css('top', top);
  7567. if(animate)
  7568. {
  7569. $('#videospace').animate({
  7570. right: window.innerWidth - availableWidth,
  7571. width: availableWidth,
  7572. height: availableHeight
  7573. },
  7574. {
  7575. queue: false,
  7576. duration: 500,
  7577. complete: completeFunction
  7578. });
  7579. $('#largeVideoContainer').animate({
  7580. width: availableWidth,
  7581. height: availableHeight
  7582. },
  7583. {
  7584. queue: false,
  7585. duration: 500
  7586. });
  7587. }
  7588. else
  7589. {
  7590. $('#videospace').width(availableWidth);
  7591. $('#videospace').height(availableHeight);
  7592. $('#largeVideoContainer').width(availableWidth);
  7593. $('#largeVideoContainer').height(availableHeight);
  7594. }
  7595. return [availableWidth, availableHeight];
  7596. },
  7597. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7598. var size = this.resize(true, isVisible, completeFunction);
  7599. this.position(null, null, size[0], size[1], true);
  7600. },
  7601. getResourceJid: function () {
  7602. if(!currentSmallVideo)
  7603. return null;
  7604. return currentSmallVideo.resourceJid;
  7605. },
  7606. updateAvatar: function (resourceJid) {
  7607. if (resourceJid === this.getResourceJid()) {
  7608. updateActiveSpeakerAvatarSrc();
  7609. }
  7610. },
  7611. showAvatar: function (resourceJid, show) {
  7612. if(this.getResourceJid() === resourceJid
  7613. && LargeVideo.isLargeVideoOnTop())
  7614. {
  7615. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7616. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7617. return true;
  7618. }
  7619. return false;
  7620. }
  7621. }
  7622. module.exports = LargeVideo;
  7623. },{"../../../service/UI/UIEvents":102,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":66,"../avatar/Avatar":16,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../util/UIUtil":33}],36:[function(require,module,exports){
  7624. var SmallVideo = require("./SmallVideo");
  7625. var ConnectionIndicator = require("./ConnectionIndicator");
  7626. var NicknameHandler = require("../util/NicknameHandler");
  7627. var UIUtil = require("../util/UIUtil");
  7628. var LargeVideo = require("./LargeVideo");
  7629. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7630. function LocalVideo(VideoLayout)
  7631. {
  7632. this.videoSpanId = "localVideoContainer";
  7633. this.container = $("#localVideoContainer").get(0);
  7634. this.VideoLayout = VideoLayout;
  7635. this.flipX = true;
  7636. this.isLocal = true;
  7637. this.peerJid = null;
  7638. this.resourceJid = null;
  7639. }
  7640. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7641. LocalVideo.prototype.constructor = LocalVideo;
  7642. /**
  7643. * Creates the edit display name button.
  7644. *
  7645. * @returns the edit button
  7646. */
  7647. function createEditDisplayNameButton() {
  7648. var editButton = document.createElement('a');
  7649. editButton.className = 'displayname';
  7650. UIUtil.setTooltip(editButton,
  7651. "videothumbnail.editnickname",
  7652. "top");
  7653. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7654. return editButton;
  7655. }
  7656. /**
  7657. * Sets the display name for the given video span id.
  7658. */
  7659. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7660. if (!this.container) {
  7661. console.warn(
  7662. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  7663. return;
  7664. }
  7665. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7666. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7667. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7668. // If we already have a display name for this video.
  7669. if (nameSpan.length > 0) {
  7670. if (nameSpan.text() !== displayName) {
  7671. if (displayName && displayName.length > 0)
  7672. {
  7673. var meHTML = APP.translation.generateTranslationHTML("me");
  7674. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7675. }
  7676. else
  7677. $('#localDisplayName').html(defaultLocalDisplayName);
  7678. }
  7679. } else {
  7680. var editButton = createEditDisplayNameButton();
  7681. nameSpan = document.createElement('span');
  7682. nameSpan.className = 'displayname';
  7683. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7684. if (displayName && displayName.length > 0) {
  7685. var meHTML = APP.translation.generateTranslationHTML("me");
  7686. nameSpan.innerHTML = displayName + meHTML;
  7687. }
  7688. else {
  7689. nameSpan.innerHTML = defaultLocalDisplayName;
  7690. }
  7691. nameSpan.id = 'localDisplayName';
  7692. this.container.appendChild(editButton);
  7693. //translates popover of edit button
  7694. APP.translation.translateElement($("a.displayname"));
  7695. var editableText = document.createElement('input');
  7696. editableText.className = 'displayname';
  7697. editableText.type = 'text';
  7698. editableText.id = 'editDisplayName';
  7699. if (displayName && displayName.length) {
  7700. editableText.value = displayName;
  7701. }
  7702. var defaultNickname = APP.translation.translateString(
  7703. "defaultNickname", {name: "Jane Pink"});
  7704. editableText.setAttribute('style', 'display:none;');
  7705. editableText.setAttribute('data-18n',
  7706. '[placeholder]defaultNickname');
  7707. editableText.setAttribute("data-i18n-options",
  7708. JSON.stringify({name: "Jane Pink"}));
  7709. editableText.setAttribute("placeholder", defaultNickname);
  7710. this.container.appendChild(editableText);
  7711. var self = this;
  7712. $('#localVideoContainer .displayname')
  7713. .bind("click", function (e) {
  7714. e.preventDefault();
  7715. e.stopPropagation();
  7716. $('#localDisplayName').hide();
  7717. $('#editDisplayName').show();
  7718. $('#editDisplayName').focus();
  7719. $('#editDisplayName').select();
  7720. $('#editDisplayName').one("focusout", function (e) {
  7721. self.VideoLayout.inputDisplayNameHandler(this.value);
  7722. });
  7723. $('#editDisplayName').on('keydown', function (e) {
  7724. if (e.keyCode === 13) {
  7725. e.preventDefault();
  7726. self.VideoLayout.inputDisplayNameHandler(this.value);
  7727. }
  7728. });
  7729. });
  7730. }
  7731. }
  7732. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7733. NicknameHandler.setNickname(name);
  7734. if (!$('#localDisplayName').is(":visible")) {
  7735. if (NicknameHandler.getNickname())
  7736. {
  7737. var meHTML = APP.translation.generateTranslationHTML("me");
  7738. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  7739. }
  7740. else
  7741. {
  7742. var defaultHTML = APP.translation.generateTranslationHTML(
  7743. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7744. $('#localDisplayName')
  7745. .html(defaultHTML);
  7746. }
  7747. $('#localDisplayName').show();
  7748. }
  7749. $('#editDisplayName').hide();
  7750. }
  7751. LocalVideo.prototype.createConnectionIndicator = function()
  7752. {
  7753. if(this.connectionIndicator)
  7754. return;
  7755. this.connectionIndicator
  7756. = new ConnectionIndicator(this, null);
  7757. }
  7758. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7759. var self = this;
  7760. function localVideoClick(event) {
  7761. // FIXME: with Temasys plugin event arg is not an event, but
  7762. // the clicked object itself, so we have to skip this call
  7763. if (event.stopPropagation) {
  7764. event.stopPropagation();
  7765. }
  7766. self.VideoLayout.handleVideoThumbClicked(
  7767. false,
  7768. APP.xmpp.myResource());
  7769. }
  7770. $('#localVideoContainer').off('click');
  7771. $('#localVideoContainer').on('click', localVideoClick);
  7772. // Add hover handler
  7773. $('#localVideoContainer').hover(
  7774. function() {
  7775. self.showDisplayName(true);
  7776. },
  7777. function() {
  7778. if (!LargeVideo.isLargeVideoVisible()
  7779. || APP.xmpp.myResource() !== LargeVideo.getResourceJid())
  7780. self.showDisplayName(false);
  7781. }
  7782. );
  7783. if(isMuted)
  7784. {
  7785. APP.UI.setVideoMute(true);
  7786. return;
  7787. }
  7788. this.flipX = (stream.videoType == "screen")? false : true;
  7789. var localVideo = document.createElement('video');
  7790. localVideo.id = 'localVideo_' +
  7791. APP.RTC.getStreamID(stream.getOriginalStream());
  7792. if (!RTCBrowserType.isIExplorer()) {
  7793. localVideo.autoplay = true;
  7794. localVideo.volume = 0; // is it required if audio is separated ?
  7795. }
  7796. localVideo.oncontextmenu = function () { return false; };
  7797. var localVideoContainer = document.getElementById('localVideoWrapper');
  7798. localVideoContainer.appendChild(localVideo);
  7799. var localVideoSelector = $('#' + localVideo.id);
  7800. // Add click handler to both video and video wrapper elements in case
  7801. // there's no video.
  7802. // onclick has to be used with Temasys plugin
  7803. localVideo.onclick = localVideoClick;
  7804. if (this.flipX) {
  7805. localVideoSelector.addClass("flipVideoX");
  7806. }
  7807. // Attach WebRTC stream
  7808. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7809. // Add stream ended handler
  7810. stream.getOriginalStream().onended = function () {
  7811. // We have to re-select after attach when Temasys plugin is used,
  7812. // because <video> element is replaced with <object>
  7813. localVideo = $('#' + localVideo.id)[0];
  7814. localVideoContainer.removeChild(localVideo);
  7815. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7816. };
  7817. }
  7818. LocalVideo.prototype.joined = function (jid) {
  7819. this.peerJid = jid;
  7820. this.resourceJid = Strophe.getResourceFromJid(jid);
  7821. }
  7822. module.exports = LocalVideo;
  7823. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7824. var ConnectionIndicator = require("./ConnectionIndicator");
  7825. var SmallVideo = require("./SmallVideo");
  7826. var AudioLevels = require("../audio_levels/AudioLevels");
  7827. var LargeVideo = require("./LargeVideo");
  7828. var Avatar = require("../avatar/Avatar");
  7829. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7830. function RemoteVideo(peerJid, VideoLayout)
  7831. {
  7832. this.peerJid = peerJid;
  7833. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7834. this.videoSpanId = 'participant_' + this.resourceJid;
  7835. this.VideoLayout = VideoLayout;
  7836. this.addRemoteVideoContainer();
  7837. this.connectionIndicator = new ConnectionIndicator(
  7838. this, this.peerJid);
  7839. this.setDisplayName();
  7840. var nickfield = document.createElement('span');
  7841. nickfield.className = "nick";
  7842. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7843. this.container.appendChild(nickfield);
  7844. this.flipX = false;
  7845. this.isLocal = false;
  7846. }
  7847. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7848. RemoteVideo.prototype.constructor = RemoteVideo;
  7849. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7850. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7851. if (APP.xmpp.isModerator())
  7852. this.addRemoteVideoMenu();
  7853. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7854. return this.container;
  7855. };
  7856. /**
  7857. * Adds the remote video menu element for the given <tt>jid</tt> in the
  7858. * given <tt>parentElement</tt>.
  7859. *
  7860. * @param jid the jid indicating the video for which we're adding a menu.
  7861. * @param parentElement the parent element where this menu will be added
  7862. */
  7863. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  7864. var spanElement = document.createElement('span');
  7865. spanElement.className = 'remotevideomenu';
  7866. this.container.appendChild(spanElement);
  7867. var menuElement = document.createElement('i');
  7868. menuElement.className = 'fa fa-angle-down';
  7869. menuElement.title = 'Remote user controls';
  7870. spanElement.appendChild(menuElement);
  7871. var popupmenuElement = document.createElement('ul');
  7872. popupmenuElement.className = 'popupmenu';
  7873. popupmenuElement.id
  7874. = 'remote_popupmenu_' + this.resourceJid;
  7875. spanElement.appendChild(popupmenuElement);
  7876. var muteMenuItem = document.createElement('li');
  7877. var muteLinkItem = document.createElement('a');
  7878. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  7879. if (!this.isMuted) {
  7880. muteLinkItem.innerHTML = mutedIndicator +
  7881. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7882. muteLinkItem.className = 'mutelink';
  7883. }
  7884. else {
  7885. muteLinkItem.innerHTML = mutedIndicator +
  7886. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7887. muteLinkItem.className = 'mutelink disabled';
  7888. }
  7889. var self = this;
  7890. muteLinkItem.onclick = function(){
  7891. if ($(this).attr('disabled') != undefined) {
  7892. event.preventDefault();
  7893. }
  7894. var isMute = self.isMuted == true;
  7895. APP.xmpp.setMute(self.peerJid, !isMute);
  7896. popupmenuElement.setAttribute('style', 'display:none;');
  7897. if (isMute) {
  7898. this.innerHTML = mutedIndicator +
  7899. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7900. this.className = 'mutelink disabled';
  7901. }
  7902. else {
  7903. this.innerHTML = mutedIndicator +
  7904. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7905. this.className = 'mutelink';
  7906. }
  7907. };
  7908. muteMenuItem.appendChild(muteLinkItem);
  7909. popupmenuElement.appendChild(muteMenuItem);
  7910. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  7911. var ejectMenuItem = document.createElement('li');
  7912. var ejectLinkItem = document.createElement('a');
  7913. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  7914. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  7915. ejectLinkItem.onclick = function(){
  7916. APP.xmpp.eject(self.peerJid);
  7917. popupmenuElement.setAttribute('style', 'display:none;');
  7918. };
  7919. ejectMenuItem.appendChild(ejectLinkItem);
  7920. popupmenuElement.appendChild(ejectMenuItem);
  7921. var paddingSpan = document.createElement('span');
  7922. paddingSpan.className = 'popupmenuPadding';
  7923. popupmenuElement.appendChild(paddingSpan);
  7924. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  7925. }
  7926. /**
  7927. * Removes the remote stream element corresponding to the given stream and
  7928. * parent container.
  7929. *
  7930. * @param stream the stream
  7931. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  7932. * @param container
  7933. */
  7934. RemoteVideo.prototype.removeRemoteStreamElement = function (stream, isVideo, id) {
  7935. if (!this.container)
  7936. return false;
  7937. var select = null;
  7938. if (isVideo) {
  7939. select = $('#' + id);
  7940. }
  7941. else
  7942. select = $('#' + this.videoSpanId + '>audio');
  7943. // Mark video as removed to cancel waiting loop(if video is removed
  7944. // before has started)
  7945. select.removed = true;
  7946. select.remove();
  7947. var audioCount = $('#' + this.videoSpanId + '>audio').length;
  7948. var videoCount = $('#' + this.videoSpanId + '>' + APP.RTC.getVideoElementName()).length;
  7949. if (!audioCount && !videoCount) {
  7950. console.log("Remove whole user", this.videoSpanId);
  7951. if(this.connectionIndicator)
  7952. this.connectionIndicator.remove();
  7953. // Remove whole container
  7954. if (this.container.parentNode)
  7955. this.container.parentNode.removeChild(this.container);
  7956. this.VideoLayout.resizeThumbnails();
  7957. }
  7958. if (isVideo)
  7959. this.VideoLayout.updateRemovedVideo(this.resourceJid);
  7960. };
  7961. RemoteVideo.prototype.waitForPlayback = function (stream) {
  7962. var isVideo = stream.getVideoTracks().length > 0;
  7963. if (!isVideo || stream.id === 'mixedmslabel') {
  7964. return;
  7965. }
  7966. var self = this;
  7967. var sel = this.VideoLayout.getPeerVideoSel(this.resourceJid);
  7968. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  7969. // when video playback starts
  7970. var onPlayingHandler = function () {
  7971. // FIXME: why do i have to do this for FF?
  7972. if (RTCBrowserType.isFirefox()) {
  7973. APP.RTC.attachMediaStream(sel, stream);
  7974. }
  7975. if (RTCBrowserType.isTemasysPluginUsed()) {
  7976. sel = $('#' + newElementId);
  7977. }
  7978. self.VideoLayout.videoactive(sel, self.resourceJid);
  7979. sel[0].onplaying = null;
  7980. if (RTCBrowserType.isTemasysPluginUsed()) {
  7981. // 'currentTime' is used to check if the video has started
  7982. // and the value is not set by the plugin, so we do it
  7983. sel[0].currentTime = 1;
  7984. }
  7985. };
  7986. sel[0].onplaying = onPlayingHandler;
  7987. };
  7988. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  7989. if (!this.container)
  7990. return;
  7991. var self = this;
  7992. var isVideo = stream.getVideoTracks().length > 0;
  7993. var streamElement = SmallVideo.createStreamElement(sid, stream);
  7994. var newElementId = streamElement.id;
  7995. this.container.appendChild(streamElement);
  7996. var sel = $('#' + newElementId);
  7997. sel.hide();
  7998. // If the container is currently visible we attach the stream.
  7999. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8000. this.waitForPlayback(stream);
  8001. APP.RTC.attachMediaStream(sel, stream);
  8002. }
  8003. stream.onended = function () {
  8004. console.log('stream ended', this);
  8005. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8006. };
  8007. // Name of video element name is different for IE/Safari
  8008. var videoElem = APP.RTC.getVideoElementName();
  8009. // Add click handler.
  8010. var onClickHandler = function (event) {
  8011. /*
  8012. * FIXME It turns out that videoThumb may not exist (if there is
  8013. * no actual video).
  8014. */
  8015. var videoThumb = $('#' + self.videoSpanId + '>' + videoElem).get(0);
  8016. if (videoThumb) {
  8017. self.VideoLayout.handleVideoThumbClicked(
  8018. false,
  8019. self.resourceJid);
  8020. }
  8021. // On IE we need to populate this handler on video <object>
  8022. // and it does not give event instance as an argument,
  8023. // so we check here for methods.
  8024. if (event.stopPropagation && event.preventDefault) {
  8025. event.stopPropagation();
  8026. event.preventDefault();
  8027. }
  8028. return false;
  8029. };
  8030. this.container.onclick = onClickHandler;
  8031. // reselect
  8032. if (RTCBrowserType.isTemasysPluginUsed())
  8033. sel = $('#' + newElementId);
  8034. sel[0].onclick = onClickHandler;
  8035. //FIXME
  8036. // Add hover handler
  8037. $(this.container).hover(
  8038. function() {
  8039. self.showDisplayName(true);
  8040. },
  8041. function() {
  8042. var videoSrc = null;
  8043. var videoSelector = $('#' + self.videoSpanId + '>' + videoElem);
  8044. if (videoSelector && videoSelector.length > 0) {
  8045. videoSrc = APP.RTC.getVideoSrc(videoSelector.get(0));
  8046. }
  8047. // If the video has been "pinned" by the user we want to
  8048. // keep the display name on place.
  8049. if (!LargeVideo.isLargeVideoVisible()
  8050. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  8051. self.showDisplayName(false);
  8052. }
  8053. );
  8054. },
  8055. /**
  8056. * Show/hide peer container for the given resourceJid.
  8057. */
  8058. RemoteVideo.prototype.showPeerContainer = function (state) {
  8059. if (!this.container)
  8060. return;
  8061. var isHide = state === 'hide';
  8062. var resizeThumbnails = false;
  8063. if (!isHide) {
  8064. if (!$(this.container).is(':visible')) {
  8065. resizeThumbnails = true;
  8066. $(this.container).show();
  8067. }
  8068. this.showAvatar(state !== 'show');
  8069. }
  8070. else if ($(this.container).is(':visible') && isHide)
  8071. {
  8072. resizeThumbnails = true;
  8073. $(this.container).hide();
  8074. if(this.connectionIndicator)
  8075. this.connectionIndicator.hide();
  8076. }
  8077. if (resizeThumbnails) {
  8078. this.VideoLayout.resizeThumbnails();
  8079. }
  8080. // We want to be able to pin a participant from the contact list, even
  8081. // if he's not in the lastN set!
  8082. // ContactList.setClickable(resourceJid, !isHide);
  8083. };
  8084. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8085. if(this.connectionIndicator)
  8086. this.connectionIndicator.remove();
  8087. }
  8088. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8089. if(this.connectionIndicator)
  8090. this.connectionIndicator.hide();
  8091. }
  8092. /**
  8093. * Updates the remote video menu.
  8094. *
  8095. * @param jid the jid indicating the video for which we're adding a menu.
  8096. * @param isMuted indicates the current mute state
  8097. */
  8098. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8099. var muteMenuItem
  8100. = $('#remote_popupmenu_'
  8101. + this.resourceJid
  8102. + '>li>a.mutelink');
  8103. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8104. if (muteMenuItem.length) {
  8105. var muteLink = muteMenuItem.get(0);
  8106. if (isMuted === 'true') {
  8107. muteLink.innerHTML = mutedIndicator + ' Muted';
  8108. muteLink.className = 'mutelink disabled';
  8109. }
  8110. else {
  8111. muteLink.innerHTML = mutedIndicator + ' Mute';
  8112. muteLink.className = 'mutelink';
  8113. }
  8114. }
  8115. }
  8116. /**
  8117. * Sets the display name for the given video span id.
  8118. */
  8119. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8120. if (!this.container) {
  8121. console.warn(
  8122. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  8123. return;
  8124. }
  8125. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8126. // If we already have a display name for this video.
  8127. if (nameSpan.length > 0) {
  8128. if (displayName && displayName.length > 0)
  8129. {
  8130. $('#' + this.videoSpanId + '_name').html(displayName);
  8131. }
  8132. else if (key && key.length > 0)
  8133. {
  8134. var nameHtml = APP.translation.generateTranslationHTML(key);
  8135. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8136. }
  8137. else
  8138. $('#' + this.videoSpanId + '_name').text(
  8139. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8140. } else {
  8141. nameSpan = document.createElement('span');
  8142. nameSpan.className = 'displayname';
  8143. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8144. if (displayName && displayName.length > 0) {
  8145. nameSpan.innerText = displayName;
  8146. }
  8147. else
  8148. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8149. nameSpan.id = this.videoSpanId + '_name';
  8150. }
  8151. }
  8152. /**
  8153. * Removes remote video menu element from video element identified by
  8154. * given <tt>videoElementId</tt>.
  8155. *
  8156. * @param videoElementId the id of local or remote video element.
  8157. */
  8158. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8159. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8160. if (menuSpan.length) {
  8161. menuSpan.remove();
  8162. }
  8163. }
  8164. RemoteVideo.createContainer = function (spanId) {
  8165. var container = document.createElement('span');
  8166. container.id = spanId;
  8167. container.className = 'videocontainer';
  8168. var remotes = document.getElementById('remoteVideos');
  8169. return remotes.appendChild(container);
  8170. };
  8171. module.exports = RemoteVideo;
  8172. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8173. var UIUtil = require("../util/UIUtil");
  8174. var LargeVideo = require("./LargeVideo");
  8175. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8176. function SmallVideo(){
  8177. this.isMuted = false;
  8178. this.hasAvatar = false;
  8179. }
  8180. function setVisibility(selector, show) {
  8181. if (selector && selector.length > 0) {
  8182. selector.css("visibility", show ? "visible" : "hidden");
  8183. }
  8184. }
  8185. SmallVideo.prototype.showDisplayName = function(isShow) {
  8186. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8187. if (isShow) {
  8188. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8189. nameSpan.setAttribute("style", "display:inline-block;");
  8190. }
  8191. else {
  8192. if (nameSpan)
  8193. nameSpan.setAttribute("style", "display:none;");
  8194. }
  8195. };
  8196. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8197. if(!this.container)
  8198. return;
  8199. $("#" + this.videoSpanId + " > .noMic").remove();
  8200. $("#" + this.videoSpanId + " > .noVideo").remove();
  8201. if(!devices.audio)
  8202. {
  8203. this.container.appendChild(
  8204. document.createElement("div")).setAttribute("class","noMic");
  8205. }
  8206. if(!devices.video)
  8207. {
  8208. this.container.appendChild(
  8209. document.createElement("div")).setAttribute("class","noVideo");
  8210. }
  8211. if(!devices.audio && !devices.video)
  8212. {
  8213. $("#" + this.videoSpanId + " > .noMic").css("background-position", "75%");
  8214. $("#" + this.videoSpanId + " > .noVideo").css("background-position", "25%");
  8215. $("#" + this.videoSpanId + " > .noVideo").css("background-color", "transparent");
  8216. }
  8217. }
  8218. /**
  8219. * Shows the presence status message for the given video.
  8220. */
  8221. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8222. if (!this.container) {
  8223. // No container
  8224. return;
  8225. }
  8226. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8227. if (!statusSpan.length) {
  8228. //Add status span
  8229. statusSpan = document.createElement('span');
  8230. statusSpan.className = 'status';
  8231. statusSpan.id = this.videoSpanId + '_status';
  8232. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8233. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8234. }
  8235. // Display status
  8236. if (statusMsg && statusMsg.length) {
  8237. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8238. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8239. }
  8240. else {
  8241. // Hide
  8242. statusSpan.get(0).setAttribute("style", "display:none;");
  8243. }
  8244. };
  8245. /**
  8246. * Creates an audio or video stream element.
  8247. */
  8248. SmallVideo.createStreamElement = function (sid, stream) {
  8249. var isVideo = stream.getVideoTracks().length > 0;
  8250. var element = isVideo
  8251. ? document.createElement('video')
  8252. : document.createElement('audio');
  8253. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  8254. + sid + '_' + APP.RTC.getStreamID(stream);
  8255. element.id = id;
  8256. if (!RTCBrowserType.isIExplorer()) {
  8257. element.autoplay = true;
  8258. }
  8259. element.oncontextmenu = function () { return false; };
  8260. return element;
  8261. };
  8262. /**
  8263. * Updates the data for the indicator
  8264. * @param id the id of the indicator
  8265. * @param percent the percent for connection quality
  8266. * @param object the data
  8267. */
  8268. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8269. if(this.connectionIndicator)
  8270. this.connectionIndicator.updateConnectionQuality(percent, object);
  8271. }
  8272. SmallVideo.prototype.hideIndicator = function () {
  8273. if(this.connectionIndicator)
  8274. this.connectionIndicator.hideIndicator();
  8275. }
  8276. /**
  8277. * Shows audio muted indicator over small videos.
  8278. * @param {string} isMuted
  8279. */
  8280. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8281. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8282. if (!isMuted) {
  8283. if (audioMutedSpan.length > 0) {
  8284. audioMutedSpan.popover('hide');
  8285. audioMutedSpan.remove();
  8286. }
  8287. }
  8288. else {
  8289. if(audioMutedSpan.length == 0 ) {
  8290. audioMutedSpan = document.createElement('span');
  8291. audioMutedSpan.className = 'audioMuted';
  8292. UIUtil.setTooltip(audioMutedSpan,
  8293. "videothumbnail.mute",
  8294. "top");
  8295. this.container.appendChild(audioMutedSpan);
  8296. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8297. var mutedIndicator = document.createElement('i');
  8298. mutedIndicator.className = 'icon-mic-disabled';
  8299. audioMutedSpan.appendChild(mutedIndicator);
  8300. }
  8301. this.updateIconPositions();
  8302. }
  8303. this.isMuted = isMuted;
  8304. };
  8305. /**
  8306. * Shows video muted indicator over small videos.
  8307. */
  8308. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8309. this.showAvatar(isMuted);
  8310. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8311. if (isMuted === false) {
  8312. if (videoMutedSpan.length > 0) {
  8313. videoMutedSpan.remove();
  8314. }
  8315. }
  8316. else {
  8317. if(videoMutedSpan.length == 0) {
  8318. videoMutedSpan = document.createElement('span');
  8319. videoMutedSpan.className = 'videoMuted';
  8320. this.container.appendChild(videoMutedSpan);
  8321. var mutedIndicator = document.createElement('i');
  8322. mutedIndicator.className = 'icon-camera-disabled';
  8323. UIUtil.setTooltip(mutedIndicator,
  8324. "videothumbnail.videomute",
  8325. "top");
  8326. videoMutedSpan.appendChild(mutedIndicator);
  8327. //translate texts for muted indicator
  8328. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8329. }
  8330. this.updateIconPositions();
  8331. }
  8332. };
  8333. SmallVideo.prototype.enableDominantSpeaker = function (isEnable)
  8334. {
  8335. var displayName = this.resourceJid;
  8336. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8337. if (nameSpan.length > 0)
  8338. displayName = nameSpan.html();
  8339. console.log("UI enable dominant speaker",
  8340. displayName,
  8341. this.resourceJid,
  8342. isEnable);
  8343. if (!this.container) {
  8344. return;
  8345. }
  8346. var video = $('#' + this.videoSpanId + '>' + APP.RTC.getVideoElementName());
  8347. if (video && video.length > 0) {
  8348. if (isEnable) {
  8349. this.showDisplayName(LargeVideo.isLargeVideoOnTop());
  8350. if (!this.container.classList.contains("dominantspeaker"))
  8351. this.container.classList.add("dominantspeaker");
  8352. }
  8353. else {
  8354. this.showDisplayName(false);
  8355. if (this.container.classList.contains("dominantspeaker"))
  8356. this.container.classList.remove("dominantspeaker");
  8357. }
  8358. }
  8359. this.showAvatar();
  8360. };
  8361. SmallVideo.prototype.updateIconPositions = function () {
  8362. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8363. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8364. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8365. if(connectionIndicator.length > 0
  8366. && connectionIndicator[0].style.display != "none") {
  8367. audioMutedSpan.css({right: "23px"});
  8368. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8369. }
  8370. else
  8371. {
  8372. audioMutedSpan.css({right: "0px"});
  8373. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8374. }
  8375. }
  8376. /**
  8377. * Creates the element indicating the moderator(owner) of the conference.
  8378. *
  8379. * @param parentElement the parent element where the owner indicator will
  8380. * be added
  8381. */
  8382. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8383. // Show moderator indicator
  8384. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8385. if (!indicatorSpan || indicatorSpan.length === 0) {
  8386. indicatorSpan = document.createElement('span');
  8387. indicatorSpan.className = 'focusindicator';
  8388. this.container.appendChild(indicatorSpan);
  8389. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8390. }
  8391. if (indicatorSpan.children().length !== 0)
  8392. return;
  8393. var moderatorIndicator = document.createElement('i');
  8394. moderatorIndicator.className = 'fa fa-star';
  8395. indicatorSpan[0].appendChild(moderatorIndicator);
  8396. UIUtil.setTooltip(indicatorSpan[0],
  8397. "videothumbnail.moderator",
  8398. "top");
  8399. //translates text in focus indicators
  8400. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8401. }
  8402. SmallVideo.prototype.getSrc = function () {
  8403. var videoElement = APP.RTC.getVideoElementName();
  8404. return APP.RTC.getVideoSrc(
  8405. $('#' + this.videoSpanId).find(videoElement).get(0));
  8406. },
  8407. SmallVideo.prototype.focus = function(isFocused)
  8408. {
  8409. if(!isFocused) {
  8410. this.container.classList.remove("videoContainerFocused");
  8411. }
  8412. else
  8413. {
  8414. this.container.classList.add("videoContainerFocused");
  8415. }
  8416. }
  8417. SmallVideo.prototype.hasVideo = function () {
  8418. return $("#" + this.videoSpanId).find(
  8419. APP.RTC.getVideoElementName()).length !== 0;
  8420. }
  8421. /**
  8422. * Hides or shows the user's avatar
  8423. * @param show whether we should show the avatar or not
  8424. * video because there is no dominant speaker and no focused speaker
  8425. */
  8426. SmallVideo.prototype.showAvatar = function (show) {
  8427. if (!this.hasAvatar)
  8428. return;
  8429. var videoElem = APP.RTC.getVideoElementName();
  8430. var video = $('#' + this.videoSpanId).find(videoElem);
  8431. var avatar = $('#avatar_' + this.resourceJid);
  8432. if (show === undefined || show === null) {
  8433. if (!this.isLocal &&
  8434. !this.VideoLayout.isInLastN(this.resourceJid)) {
  8435. show = true;
  8436. }
  8437. else
  8438. {
  8439. show = APP.RTC.isVideoMuted(this.peerJid);
  8440. }
  8441. }
  8442. if (LargeVideo.showAvatar(this.resourceJid, show))
  8443. {
  8444. setVisibility(avatar, false);
  8445. setVisibility(video, false);
  8446. } else {
  8447. if (video && video.length > 0) {
  8448. setVisibility(video, !show);
  8449. }
  8450. setVisibility(avatar, show);
  8451. }
  8452. };
  8453. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8454. var thumbnail = $('#' + this.videoSpanId);
  8455. var avatar = $('#avatar_' + this.resourceJid);
  8456. this.hasAvatar = true;
  8457. // set the avatar in the thumbnail
  8458. if (avatar && avatar.length > 0) {
  8459. avatar[0].src = thumbUrl;
  8460. } else {
  8461. if (thumbnail && thumbnail.length > 0) {
  8462. avatar = document.createElement('img');
  8463. avatar.id = 'avatar_' + this.resourceJid;
  8464. avatar.className = 'userAvatar';
  8465. avatar.src = thumbUrl;
  8466. thumbnail.append(avatar);
  8467. }
  8468. }
  8469. }
  8470. module.exports = SmallVideo;
  8471. },{"../../RTC/RTCBrowserType":8,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8472. var AudioLevels = require("../audio_levels/AudioLevels");
  8473. var Avatar = require("../avatar/Avatar");
  8474. var ContactList = require("../side_pannels/contactlist/ContactList");
  8475. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8476. var UIEvents = require("../../../service/UI/UIEvents");
  8477. var RTC = require("../../RTC/RTC");
  8478. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8479. var RemoteVideo = require("./RemoteVideo");
  8480. var LargeVideo = require("./LargeVideo");
  8481. var LocalVideo = require("./LocalVideo");
  8482. var remoteVideos = {};
  8483. var localVideoThumbnail = null;
  8484. var currentDominantSpeaker = null;
  8485. var lastNCount = config.channelLastN;
  8486. var localLastNCount = config.channelLastN;
  8487. var localLastNSet = [];
  8488. var lastNEndpointsCache = [];
  8489. var lastNPickupJid = null;
  8490. var eventEmitter = null;
  8491. /**
  8492. * Currently focused video jid
  8493. * @type {String}
  8494. */
  8495. var focusedVideoResourceJid = null;
  8496. var VideoLayout = (function (my) {
  8497. my.init = function (emitter) {
  8498. eventEmitter = emitter;
  8499. localVideoThumbnail = new LocalVideo(VideoLayout);
  8500. VideoLayout.resizeLargeVideoContainer();
  8501. LargeVideo.init(VideoLayout, emitter);
  8502. };
  8503. my.isInLastN = function(resource) {
  8504. return lastNCount < 0 // lastN is disabled, return true
  8505. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  8506. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  8507. };
  8508. my.changeLocalStream = function (stream, isMuted) {
  8509. VideoLayout.changeLocalVideo(stream, isMuted);
  8510. };
  8511. my.changeLocalAudio = function(stream, isMuted) {
  8512. if (isMuted)
  8513. APP.UI.setAudioMuted(true, true);
  8514. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8515. var localAudio = document.getElementById('localAudio');
  8516. // Writing volume not allowed in IE
  8517. if (!RTCBrowserType.isIExplorer()) {
  8518. localAudio.autoplay = true;
  8519. localAudio.volume = 0;
  8520. }
  8521. };
  8522. my.changeLocalVideo = function(stream, isMuted) {
  8523. // Set default display name.
  8524. localVideoThumbnail.setDisplayName();
  8525. localVideoThumbnail.createConnectionIndicator();
  8526. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8527. localVideoThumbnail.changeVideo(stream, isMuted);
  8528. LargeVideo.updateLargeVideo(
  8529. APP.xmpp.myResource(),
  8530. /* force update only before conference starts */
  8531. !APP.xmpp.isConferenceInProgress());
  8532. };
  8533. my.mucJoined = function () {
  8534. var myResourceJid = APP.xmpp.myResource();
  8535. localVideoThumbnail.joined(APP.xmpp.myJid());
  8536. if (!LargeVideo.getResourceJid())
  8537. LargeVideo.updateLargeVideo(myResourceJid, true);
  8538. };
  8539. /**
  8540. * Adds or removes icons for not available camera and microphone.
  8541. * @param resourceJid the jid of user
  8542. * @param devices available devices
  8543. */
  8544. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8545. if(!devices)
  8546. return;
  8547. if(!resourceJid)
  8548. {
  8549. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8550. }
  8551. else
  8552. {
  8553. if(remoteVideos[resourceJid])
  8554. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8555. }
  8556. }
  8557. /**
  8558. * Checks if removed video is currently displayed and tries to display
  8559. * another one instead.
  8560. * @param removedVideoSrc src stream identifier of the video.
  8561. */
  8562. my.updateRemovedVideo = function(resourceJid) {
  8563. var videoElem = RTC.getVideoElementName();
  8564. if (resourceJid === LargeVideo.getResourceJid()) {
  8565. // this is currently displayed as large
  8566. // pick the last visible video in the row
  8567. // if nobody else is left, this picks the local video
  8568. var pick
  8569. = $('#remoteVideos>' +
  8570. 'span[id!="mixedstream"]:visible:last>' + videoElem).get(0);
  8571. if (!pick) {
  8572. console.info("Last visible video no longer exists");
  8573. pick = $('#remoteVideos>' +
  8574. 'span[id!="mixedstream"]>' + videoElem).get(0);
  8575. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  8576. // Try local video
  8577. console.info("Fallback to local video...");
  8578. pick = $('#remoteVideos>span>span>' + videoElem).get(0);
  8579. }
  8580. }
  8581. // mute if localvideo
  8582. if (pick) {
  8583. var container = pick.parentNode;
  8584. } else {
  8585. console.warn("Failed to elect large video");
  8586. container = $('#remoteVideos>span[id!="mixedstream"]:visible:last').get(0);
  8587. }
  8588. var jid = null;
  8589. if(container)
  8590. {
  8591. if(container.id == "localVideoWrapper")
  8592. {
  8593. jid = APP.xmpp.myResource();
  8594. }
  8595. else
  8596. {
  8597. jid = VideoLayout.getPeerContainerResourceJid(container);
  8598. }
  8599. }
  8600. else
  8601. return;
  8602. LargeVideo.updateLargeVideo(jid);
  8603. }
  8604. };
  8605. my.onRemoteStreamAdded = function (stream) {
  8606. if (stream.peerjid) {
  8607. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8608. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8609. remoteVideos[resourceJid].addRemoteStreamElement(
  8610. stream.sid,
  8611. stream.getOriginalStream(),
  8612. stream.ssrc);
  8613. }
  8614. };
  8615. my.getLargeVideoJid = function () {
  8616. return LargeVideo.getResourceJid();
  8617. };
  8618. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8619. resourceJid) {
  8620. if(focusedVideoResourceJid) {
  8621. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8622. if(oldSmallVideo)
  8623. oldSmallVideo.focus(false);
  8624. }
  8625. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8626. // Unlock current focused.
  8627. if (focusedVideoResourceJid === resourceJid)
  8628. {
  8629. focusedVideoResourceJid = null;
  8630. // Enable the currently set dominant speaker.
  8631. if (currentDominantSpeaker) {
  8632. if(smallVideo && smallVideo.hasVideo())
  8633. {
  8634. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8635. }
  8636. }
  8637. if (!noPinnedEndpointChangedEvent) {
  8638. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8639. }
  8640. return;
  8641. }
  8642. // Lock new video
  8643. focusedVideoResourceJid = resourceJid;
  8644. // Update focused/pinned interface.
  8645. if (resourceJid)
  8646. {
  8647. if(smallVideo)
  8648. smallVideo.focus(true);
  8649. if (!noPinnedEndpointChangedEvent) {
  8650. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8651. }
  8652. }
  8653. if (LargeVideo.getResourceJid() === resourceJid &&
  8654. LargeVideo.isLargeVideoOnTop()) {
  8655. return;
  8656. }
  8657. // Triggers a "video.selected" event. The "false" parameter indicates
  8658. // this isn't a prezi.
  8659. $(document).trigger("video.selected", [false]);
  8660. LargeVideo.updateLargeVideo(resourceJid);
  8661. // Writing volume not allowed in IE
  8662. if (!RTCBrowserType.isIExplorer()) {
  8663. $('audio').each(function (idx, el) {
  8664. el.volume = 0;
  8665. el.volume = 1;
  8666. });
  8667. }
  8668. };
  8669. /**
  8670. * Checks if container for participant identified by given peerJid exists
  8671. * in the document and creates it eventually.
  8672. *
  8673. * @param peerJid peer Jid to check.
  8674. * @param userId user email or id for setting the avatar
  8675. *
  8676. * @return Returns <tt>true</tt> if the peer container exists,
  8677. * <tt>false</tt> - otherwise
  8678. */
  8679. my.ensurePeerContainerExists = function(peerJid, userId) {
  8680. ContactList.ensureAddContact(peerJid, userId);
  8681. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8682. if(!remoteVideos[resourceJid])
  8683. {
  8684. remoteVideos[resourceJid] = new RemoteVideo(peerJid, VideoLayout);
  8685. Avatar.setUserAvatar(peerJid, userId);
  8686. // In case this is not currently in the last n we don't show it.
  8687. if (localLastNCount
  8688. && localLastNCount > 0
  8689. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  8690. remoteVideos[resourceJid].showPeerContainer('hide');
  8691. }
  8692. else
  8693. VideoLayout.resizeThumbnails();
  8694. }
  8695. };
  8696. my.inputDisplayNameHandler = function (name) {
  8697. localVideoThumbnail.inputDisplayNameHandler(name);
  8698. };
  8699. my.videoactive = function (videoelem, resourceJid) {
  8700. videoelem.show();
  8701. VideoLayout.resizeThumbnails();
  8702. // Update the large video to the last added video only if there's no
  8703. // current dominant, focused speaker or prezi playing or update it to
  8704. // the current dominant speaker.
  8705. if ((!focusedVideoResourceJid &&
  8706. !currentDominantSpeaker &&
  8707. !require("../prezi/Prezi").isPresentationVisible()) ||
  8708. (resourceJid &&
  8709. currentDominantSpeaker === resourceJid)) {
  8710. LargeVideo.updateLargeVideo(resourceJid, true);
  8711. }
  8712. }
  8713. /**
  8714. * Shows the presence status message for the given video.
  8715. */
  8716. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8717. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8718. };
  8719. /**
  8720. * Shows a visual indicator for the moderator of the conference.
  8721. */
  8722. my.showModeratorIndicator = function () {
  8723. var isModerator = APP.xmpp.isModerator();
  8724. if (isModerator) {
  8725. localVideoThumbnail.createModeratorIndicatorElement();
  8726. }
  8727. var members = APP.xmpp.getMembers();
  8728. Object.keys(members).forEach(function (jid) {
  8729. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8730. // Skip server side focus
  8731. return;
  8732. }
  8733. var resourceJid = Strophe.getResourceFromJid(jid);
  8734. var member = members[jid];
  8735. if (member.role === 'moderator') {
  8736. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8737. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8738. } else if (isModerator) {
  8739. // We are moderator, but user is not - add menu
  8740. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8741. remoteVideos[resourceJid].addRemoteVideoMenu();
  8742. }
  8743. }
  8744. });
  8745. };
  8746. /*
  8747. * Shows or hides the audio muted indicator over the local thumbnail video.
  8748. * @param {boolean} isMuted
  8749. */
  8750. my.showLocalAudioIndicator = function(isMuted) {
  8751. localVideoThumbnail.showAudioIndicator(isMuted);
  8752. };
  8753. /**
  8754. * Resizes the large video container.
  8755. */
  8756. my.resizeLargeVideoContainer = function () {
  8757. LargeVideo.resize();
  8758. VideoLayout.resizeThumbnails();
  8759. LargeVideo.position();
  8760. };
  8761. /**
  8762. * Resizes thumbnails.
  8763. */
  8764. my.resizeThumbnails = function(animate) {
  8765. var videoSpaceWidth = $('#remoteVideos').width();
  8766. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8767. var width = thumbnailSize[0];
  8768. var height = thumbnailSize[1];
  8769. $('.userAvatar').css('left', (width - height) / 2);
  8770. if(animate)
  8771. {
  8772. $('#remoteVideos').animate({
  8773. height: height
  8774. },
  8775. {
  8776. queue: false,
  8777. duration: 500
  8778. });
  8779. $('#remoteVideos>span').animate({
  8780. height: height,
  8781. width: width
  8782. },
  8783. {
  8784. queue: false,
  8785. duration: 500,
  8786. complete: function () {
  8787. $(document).trigger(
  8788. "remotevideo.resized",
  8789. [width,
  8790. height]);
  8791. }
  8792. });
  8793. }
  8794. else
  8795. {
  8796. // size videos so that while keeping AR and max height, we have a
  8797. // nice fit
  8798. $('#remoteVideos').height(height);
  8799. $('#remoteVideos>span').width(width);
  8800. $('#remoteVideos>span').height(height);
  8801. $(document).trigger("remotevideo.resized", [width, height]);
  8802. }
  8803. };
  8804. /**
  8805. * Calculates the thumbnail size.
  8806. *
  8807. * @param videoSpaceWidth the width of the video space
  8808. */
  8809. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8810. // Calculate the available height, which is the inner window height minus
  8811. // 39px for the header minus 2px for the delimiter lines on the top and
  8812. // bottom of the large video, minus the 36px space inside the remoteVideos
  8813. // container used for highlighting shadow.
  8814. var availableHeight = 100;
  8815. var numvids = $('#remoteVideos>span:visible').length;
  8816. if (localLastNCount && localLastNCount > 0) {
  8817. numvids = Math.min(localLastNCount + 1, numvids);
  8818. }
  8819. // Remove the 3px borders arround videos and border around the remote
  8820. // videos area and the 4 pixels between the local video and the others
  8821. //TODO: Find out where the 4 pixels come from and remove them
  8822. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8823. var availableWidth = availableWinWidth / numvids;
  8824. var aspectRatio = 16.0 / 9.0;
  8825. var maxHeight = Math.min(160, availableHeight);
  8826. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  8827. if (availableHeight < availableWidth / aspectRatio) {
  8828. availableWidth = Math.floor(availableHeight * aspectRatio);
  8829. }
  8830. return [availableWidth, availableHeight];
  8831. };
  8832. /**
  8833. * Returns the corresponding resource jid to the given peer container
  8834. * DOM element.
  8835. *
  8836. * @return the corresponding resource jid to the given peer container
  8837. * DOM element
  8838. */
  8839. my.getPeerContainerResourceJid = function (containerElement) {
  8840. var i = containerElement.id.indexOf('participant_');
  8841. if (i >= 0)
  8842. return containerElement.id.substring(i + 12);
  8843. };
  8844. my.getPeerVideoSel = function (peerResourceJid) {
  8845. return $('#participant_' + peerResourceJid +
  8846. '>' + APP.RTC.getVideoElementName());
  8847. };
  8848. /**
  8849. * On contact list item clicked.
  8850. */
  8851. $(ContactList).bind('contactclicked', function(event, jid) {
  8852. if (!jid) {
  8853. return;
  8854. }
  8855. if (jid == APP.xmpp.myJid()) {
  8856. $("#localVideoContainer").click();
  8857. return;
  8858. }
  8859. var resource = Strophe.getResourceFromJid(jid);
  8860. var videoSel = VideoLayout.getPeerVideoSel(resource);
  8861. if (videoSel.length > 0) {
  8862. var videoThumb = videoSel[0];
  8863. // It is not always the case that a videoThumb exists (if there is
  8864. // no actual video).
  8865. if (RTC.getVideoSrc(videoThumb)) {
  8866. // We have a video src, great! Let's update the large video
  8867. // now.
  8868. VideoLayout.handleVideoThumbClicked(
  8869. false,
  8870. Strophe.getResourceFromJid(jid));
  8871. } else {
  8872. // If we don't have a video src for jid, there's absolutely
  8873. // no point in calling handleVideoThumbClicked; Quite
  8874. // simply, it won't work because it needs an src to attach
  8875. // to the large video.
  8876. //
  8877. // Instead, we trigger the pinned endpoint changed event to
  8878. // let the bridge adjust its lastN set for myjid and store
  8879. // the pinned user in the lastNPickupJid variable to be
  8880. // picked up later by the lastN changed event handler.
  8881. lastNPickupJid = jid;
  8882. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  8883. Strophe.getResourceFromJid(jid));
  8884. }
  8885. }
  8886. });
  8887. /**
  8888. * On audio muted event.
  8889. */
  8890. my.onAudioMute = function (jid, isMuted) {
  8891. var resourceJid = Strophe.getResourceFromJid(jid);
  8892. if (resourceJid === APP.xmpp.myResource()) {
  8893. localVideoThumbnail.showAudioIndicator(isMuted);
  8894. } else {
  8895. VideoLayout.ensurePeerContainerExists(jid);
  8896. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  8897. if (APP.xmpp.isModerator()) {
  8898. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  8899. }
  8900. }
  8901. };
  8902. /**
  8903. * On video muted event.
  8904. */
  8905. my.onVideoMute = function (jid, value) {
  8906. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, value))
  8907. return;
  8908. if (jid === APP.xmpp.myJid()) {
  8909. localVideoThumbnail.showVideoIndicator(value);
  8910. } else {
  8911. var resource = Strophe.getResourceFromJid(jid);
  8912. VideoLayout.ensurePeerContainerExists(jid);
  8913. remoteVideos[resource].showVideoIndicator(value);
  8914. var el = VideoLayout.getPeerVideoSel(resource);
  8915. if (!value)
  8916. el.show();
  8917. else
  8918. el.hide();
  8919. }
  8920. };
  8921. /**
  8922. * Display name changed.
  8923. */
  8924. my.onDisplayNameChanged =
  8925. function (jid, displayName, status) {
  8926. if (jid === 'localVideoContainer'
  8927. || jid === APP.xmpp.myJid()) {
  8928. localVideoThumbnail.setDisplayName(displayName);
  8929. } else {
  8930. VideoLayout.ensurePeerContainerExists(jid);
  8931. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  8932. displayName,
  8933. status);
  8934. }
  8935. };
  8936. /**
  8937. * On dominant speaker changed event.
  8938. */
  8939. my.onDominantSpeakerChanged = function (resourceJid) {
  8940. // We ignore local user events.
  8941. if (resourceJid === APP.xmpp.myResource())
  8942. return;
  8943. var members = APP.xmpp.getMembers();
  8944. // Update the current dominant speaker.
  8945. if (resourceJid !== currentDominantSpeaker) {
  8946. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  8947. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  8948. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  8949. !members[currentJID].displayName)) {
  8950. remoteVideos[resourceJid].setDisplayName(null);
  8951. }
  8952. if(resourceJid && (!members || !members[newJID] ||
  8953. !members[newJID].displayName)) {
  8954. remoteVideos[resourceJid].setDisplayName(null,
  8955. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  8956. }
  8957. currentDominantSpeaker = resourceJid;
  8958. } else {
  8959. return;
  8960. }
  8961. // Obtain container for new dominant speaker.
  8962. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  8963. // Local video will not have container found, but that's ok
  8964. // since we don't want to switch to local video.
  8965. if (!focusedVideoResourceJid && videoSel.length)
  8966. {
  8967. // Update the large video if the video source is already available,
  8968. // otherwise wait for the "videoactive.jingle" event.
  8969. if (videoSel[0].currentTime > 0) {
  8970. LargeVideo.updateLargeVideo(resourceJid);
  8971. }
  8972. }
  8973. };
  8974. /**
  8975. * On last N change event.
  8976. *
  8977. * @param lastNEndpoints the list of last N endpoints
  8978. * @param endpointsEnteringLastN the list currently entering last N
  8979. * endpoints
  8980. */
  8981. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  8982. endpointsEnteringLastN,
  8983. stream) {
  8984. if (lastNCount !== lastNEndpoints.length)
  8985. lastNCount = lastNEndpoints.length;
  8986. lastNEndpointsCache = lastNEndpoints;
  8987. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  8988. //
  8989. // If LastN drops to, say, 2, because of adaptivity, then E should see
  8990. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  8991. // so E sees them. C is only in E's local LastN set.
  8992. //
  8993. // If F starts talking and LastN = 3, then E should see thumbnails for
  8994. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  8995. // enters E's local LastN ejecting C.
  8996. // Increase the local LastN set size, if necessary.
  8997. if (lastNCount > localLastNCount) {
  8998. localLastNCount = lastNCount;
  8999. }
  9000. // Update the local LastN set preserving the order in which the
  9001. // endpoints appeared in the LastN/local LastN set.
  9002. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9003. for (var i = 0; i < localLastNSet.length; i++) {
  9004. if (nextLocalLastNSet.length >= localLastNCount) {
  9005. break;
  9006. }
  9007. var resourceJid = localLastNSet[i];
  9008. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9009. nextLocalLastNSet.push(resourceJid);
  9010. }
  9011. }
  9012. localLastNSet = nextLocalLastNSet;
  9013. var updateLargeVideo = false;
  9014. // Handle LastN/local LastN changes.
  9015. $('#remoteVideos>span').each(function( index, element ) {
  9016. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9017. var isReceived = true;
  9018. if (resourceJid
  9019. && lastNEndpoints.indexOf(resourceJid) < 0
  9020. && localLastNSet.indexOf(resourceJid) < 0) {
  9021. console.log("Remove from last N", resourceJid);
  9022. remoteVideos[resourceJid].showPeerContainer('hide');
  9023. isReceived = false;
  9024. } else if (resourceJid
  9025. && $('#participant_' + resourceJid).is(':visible')
  9026. && lastNEndpoints.indexOf(resourceJid) < 0
  9027. && localLastNSet.indexOf(resourceJid) >= 0) {
  9028. remoteVideos[resourceJid].showPeerContainer('avatar');
  9029. isReceived = false;
  9030. }
  9031. if (!isReceived) {
  9032. // resourceJid has dropped out of the server side lastN set, so
  9033. // it is no longer being received. If resourceJid was being
  9034. // displayed in the large video we have to switch to another
  9035. // user.
  9036. if (!updateLargeVideo && resourceJid === LargeVideo.getResourceJid()) {
  9037. updateLargeVideo = true;
  9038. }
  9039. }
  9040. });
  9041. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9042. endpointsEnteringLastN = lastNEndpoints;
  9043. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9044. endpointsEnteringLastN.forEach(function (resourceJid) {
  9045. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9046. remoteVideos[resourceJid].showPeerContainer('show');
  9047. if (!isVisible) {
  9048. console.log("Add to last N", resourceJid);
  9049. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9050. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9051. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9052. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9053. if (lastNPickupJid == mediaStream.peerjid) {
  9054. // Clean up the lastN pickup jid.
  9055. lastNPickupJid = null;
  9056. // Don't fire the events again, they've already
  9057. // been fired in the contact list click handler.
  9058. VideoLayout.handleVideoThumbClicked(
  9059. false,
  9060. Strophe.getResourceFromJid(mediaStream.peerjid));
  9061. updateLargeVideo = false;
  9062. }
  9063. remoteVideos[resourceJid].waitForPlayback(mediaStream.stream);
  9064. }
  9065. });
  9066. }
  9067. // The endpoint that was being shown in the large video has dropped out
  9068. // of the lastN set and there was no lastN pickup jid. We need to update
  9069. // the large video now.
  9070. if (updateLargeVideo) {
  9071. var resource, container, src;
  9072. var myResource
  9073. = APP.xmpp.myResource();
  9074. // Find out which endpoint to show in the large video.
  9075. for (var i = 0; i < lastNEndpoints.length; i++) {
  9076. resource = lastNEndpoints[i];
  9077. if (!resource || resource === myResource)
  9078. continue;
  9079. // videoSrcToSsrc needs to be update for this call to succeed.
  9080. LargeVideo.updateLargeVideo(resource);
  9081. break;
  9082. }
  9083. }
  9084. };
  9085. /**
  9086. * Updates local stats
  9087. * @param percent
  9088. * @param object
  9089. */
  9090. my.updateLocalConnectionStats = function (percent, object) {
  9091. var resolution = null;
  9092. if(object.resolution !== null)
  9093. {
  9094. resolution = object.resolution;
  9095. object.resolution = resolution[APP.xmpp.myJid()];
  9096. delete resolution[APP.xmpp.myJid()];
  9097. }
  9098. localVideoThumbnail.updateStatsIndicator(percent, object);
  9099. for(var jid in resolution)
  9100. {
  9101. if(resolution[jid] === null)
  9102. continue;
  9103. var resourceJid = Strophe.getResourceFromJid(jid);
  9104. if(remoteVideos[resourceJid] && remoteVideos[resourceJid].connectionIndicator)
  9105. {
  9106. remoteVideos[resourceJid].connectionIndicator.updateResolution(resolution[jid]);
  9107. }
  9108. }
  9109. };
  9110. /**
  9111. * Updates remote stats.
  9112. * @param jid the jid associated with the stats
  9113. * @param percent the connection quality percent
  9114. * @param object the stats data
  9115. */
  9116. my.updateConnectionStats = function (jid, percent, object) {
  9117. var resourceJid = Strophe.getResourceFromJid(jid);
  9118. if(remoteVideos[resourceJid])
  9119. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9120. };
  9121. /**
  9122. * Removes the connection
  9123. * @param jid
  9124. */
  9125. my.removeConnectionIndicator = function (jid) {
  9126. remoteVideos[Strophe.getResourceFromJid(jid)].removeConnectionIndicator();
  9127. };
  9128. /**
  9129. * Hides the connection indicator
  9130. * @param jid
  9131. */
  9132. my.hideConnectionIndicator = function (jid) {
  9133. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9134. };
  9135. /**
  9136. * Hides all the indicators
  9137. */
  9138. my.onStatsStop = function () {
  9139. for(var video in remoteVideos)
  9140. {
  9141. remoteVideos[video].hideIndicator();
  9142. }
  9143. localVideoThumbnail.hideIndicator();
  9144. };
  9145. my.participantLeft = function (jid) {
  9146. // Unlock large video
  9147. var resourceJid = Strophe.getResourceFromJid(jid);
  9148. if (focusedVideoResourceJid === resourceJid)
  9149. {
  9150. console.info("Focused video owner has left the conference");
  9151. focusedVideoResourceJid = null;
  9152. }
  9153. };
  9154. my.onVideoTypeChanged = function (jid) {
  9155. LargeVideo.onVideoTypeChanged(jid);
  9156. };
  9157. my.showMore = function (jid) {
  9158. if(APP.xmpp.myJid = jid)
  9159. {
  9160. localVideoThumbnail.connectionIndicator.showMore();
  9161. }
  9162. else
  9163. {
  9164. remoteVideos[Strophe.getResourceFromJid(jid)].connectionIndicator.showMore();
  9165. }
  9166. };
  9167. my.addPreziContainer = function (id) {
  9168. return RemoteVideo.createContainer(id);
  9169. };
  9170. my.setLargeVideoVisible = function (isVisible) {
  9171. LargeVideo.setLargeVideoVisible(isVisible);
  9172. if(!isVisible && focusedVideoResourceJid)
  9173. {
  9174. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9175. if(smallVideo)
  9176. smallVideo.focus(false);
  9177. smallVideo.showAvatar();
  9178. focusedVideoResourceJid = null;
  9179. }
  9180. };
  9181. /**
  9182. * Resizes the video area
  9183. * @param completeFunction a function to be called when the video space is resized
  9184. */
  9185. my.resizeVideoArea = function(isVisible, completeFunction) {
  9186. LargeVideo.resizeVideoAreaAnimated(isVisible, completeFunction);
  9187. VideoLayout.resizeThumbnails(true);
  9188. };
  9189. my.getSmallVideo = function (resourceJid) {
  9190. if(resourceJid == APP.xmpp.myResource())
  9191. {
  9192. return localVideoThumbnail;
  9193. }
  9194. else
  9195. {
  9196. if(!remoteVideos[resourceJid])
  9197. return null;
  9198. return remoteVideos[resourceJid];
  9199. }
  9200. };
  9201. my.userAvatarChanged = function(resourceJid, thumbUrl)
  9202. {
  9203. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9204. if(smallVideo)
  9205. smallVideo.avatarChanged(thumbUrl);
  9206. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9207. };
  9208. return my;
  9209. }(VideoLayout || {}));
  9210. module.exports = VideoLayout;
  9211. },{"../../../service/RTC/MediaStreamTypes":98,"../../../service/UI/UIEvents":102,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  9212. //var nouns = [
  9213. //];
  9214. var pluralNouns = [
  9215. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9216. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9217. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9218. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9219. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9220. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9221. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9222. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9223. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9224. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9225. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9226. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9227. ];
  9228. //var places = [
  9229. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9230. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9231. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9232. // "Bridge"
  9233. //];
  9234. var verbs = [
  9235. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9236. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9237. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9238. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9239. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9240. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9241. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9242. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9243. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9244. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9245. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9246. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9247. ];
  9248. var adverbs = [
  9249. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9250. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9251. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9252. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9253. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9254. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9255. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9256. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9257. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9258. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9259. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9260. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9261. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9262. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9263. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9264. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9265. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9266. ];
  9267. var adjectives = [
  9268. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9269. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9270. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9271. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9272. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9273. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9274. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9275. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9276. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9277. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9278. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9279. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9280. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9281. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9282. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9283. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9284. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9285. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9286. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9287. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9288. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9289. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9290. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9291. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9292. "Zealous"
  9293. ];
  9294. //var pronouns = [
  9295. //];
  9296. //var conjunctions = [
  9297. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9298. //];
  9299. /*
  9300. * Maps a string (category name) to the array of words from that category.
  9301. */
  9302. var CATEGORIES =
  9303. {
  9304. //"_NOUN_": nouns,
  9305. "_PLURALNOUN_": pluralNouns,
  9306. //"_PLACE_": places,
  9307. "_VERB_": verbs,
  9308. "_ADVERB_": adverbs,
  9309. "_ADJECTIVE_": adjectives
  9310. //"_PRONOUN_": pronouns,
  9311. //"_CONJUNCTION_": conjunctions,
  9312. };
  9313. var PATTERNS = [
  9314. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9315. // BeautifulFungiOrSpaghetti
  9316. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9317. // AmazinglyScaryToy
  9318. //"_ADVERB__ADJECTIVE__NOUN_",
  9319. // NeitherTrashNorRifle
  9320. //"Neither_NOUN_Nor_NOUN_",
  9321. //"Either_NOUN_Or_NOUN_",
  9322. // EitherCopulateOrInvestigate
  9323. //"Either_VERB_Or_VERB_",
  9324. //"Neither_VERB_Nor_VERB_",
  9325. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9326. //"The_ADVERB__ADJECTIVE__NOUN_",
  9327. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9328. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9329. // WolvesComputeBadly
  9330. //"_PLURALNOUN__VERB__ADVERB_",
  9331. // UniteFacilitateAndMerge
  9332. //"_VERB__VERB_And_VERB_",
  9333. //NastyWitchesAtThePub
  9334. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9335. ];
  9336. /*
  9337. * Returns a random element from the array 'arr'
  9338. */
  9339. function randomElement(arr)
  9340. {
  9341. return arr[Math.floor(Math.random() * arr.length)];
  9342. }
  9343. /*
  9344. * Returns true if the string 's' contains one of the
  9345. * template strings.
  9346. */
  9347. function hasTemplate(s)
  9348. {
  9349. for (var template in CATEGORIES){
  9350. if (s.indexOf(template) >= 0){
  9351. return true;
  9352. }
  9353. }
  9354. }
  9355. /**
  9356. * Generates new room name.
  9357. */
  9358. var RoomNameGenerator = {
  9359. generateRoomWithoutSeparator: function()
  9360. {
  9361. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  9362. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  9363. var name = randomElement(PATTERNS);
  9364. var word;
  9365. while (hasTemplate(name)){
  9366. for (var template in CATEGORIES){
  9367. word = randomElement(CATEGORIES[template]);
  9368. name = name.replace(template, word);
  9369. }
  9370. }
  9371. return name;
  9372. }
  9373. }
  9374. module.exports = RoomNameGenerator;
  9375. },{}],41:[function(require,module,exports){
  9376. var animateTimeout, updateTimeout;
  9377. var RoomNameGenerator = require("./RoomnameGenerator");
  9378. function enter_room()
  9379. {
  9380. var val = $("#enter_room_field").val();
  9381. if(!val) {
  9382. val = $("#enter_room_field").attr("room_name");
  9383. }
  9384. if (val) {
  9385. window.location.pathname = "/" + val;
  9386. }
  9387. }
  9388. function animate(word) {
  9389. var currentVal = $("#enter_room_field").attr("placeholder");
  9390. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9391. animateTimeout = setTimeout(function() {
  9392. animate(word.substring(1, word.length))
  9393. }, 70);
  9394. }
  9395. function update_roomname()
  9396. {
  9397. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9398. $("#enter_room_field").attr("room_name", word);
  9399. $("#enter_room_field").attr("placeholder", "");
  9400. clearTimeout(animateTimeout);
  9401. animate(word);
  9402. updateTimeout = setTimeout(update_roomname, 10000);
  9403. }
  9404. function setupWelcomePage()
  9405. {
  9406. $("#videoconference_page").hide();
  9407. $("#domain_name").text(
  9408. window.location.protocol + "//" + window.location.host + "/");
  9409. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9410. var leftWatermarkDiv
  9411. = $("#welcome_page_header div[class='watermark leftwatermark']");
  9412. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  9413. {
  9414. leftWatermarkDiv.css({display: 'block'});
  9415. leftWatermarkDiv.parent().get(0).href
  9416. = interfaceConfig.JITSI_WATERMARK_LINK;
  9417. }
  9418. }
  9419. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9420. var rightWatermarkDiv
  9421. = $("#welcome_page_header div[class='watermark rightwatermark']");
  9422. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9423. rightWatermarkDiv.css({display: 'block'});
  9424. rightWatermarkDiv.parent().get(0).href
  9425. = interfaceConfig.BRAND_WATERMARK_LINK;
  9426. rightWatermarkDiv.get(0).style.backgroundImage
  9427. = "url(images/rightwatermark.png)";
  9428. }
  9429. }
  9430. if (interfaceConfig.SHOW_POWERED_BY) {
  9431. $("#welcome_page_header>a[class='poweredby']")
  9432. .css({display: 'block'});
  9433. }
  9434. $("#enter_room_button").click(function()
  9435. {
  9436. enter_room();
  9437. });
  9438. $("#enter_room_field").keydown(function (event) {
  9439. if (event.keyCode === 13 /* enter */) {
  9440. enter_room();
  9441. }
  9442. });
  9443. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  9444. var updateTimeout;
  9445. var animateTimeout;
  9446. $("#reload_roomname").click(function () {
  9447. clearTimeout(updateTimeout);
  9448. clearTimeout(animateTimeout);
  9449. update_roomname();
  9450. });
  9451. $("#reload_roomname").show();
  9452. update_roomname();
  9453. }
  9454. $("#disable_welcome").click(function () {
  9455. window.localStorage.welcomePageDisabled
  9456. = $("#disable_welcome").is(":checked");
  9457. });
  9458. }
  9459. module.exports = setupWelcomePage;
  9460. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9461. var params = {};
  9462. function getConfigParamsFromUrl() {
  9463. if(!location.hash)
  9464. return {};
  9465. var hash = location.hash.substr(1);
  9466. var result = {};
  9467. hash.split("&").forEach(function(part) {
  9468. var item = part.split("=");
  9469. result[item[0]] = JSON.parse(
  9470. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9471. });
  9472. return result;
  9473. }
  9474. params = getConfigParamsFromUrl();
  9475. var URLProcessor = {
  9476. setConfigParametersFromUrl: function () {
  9477. for(var k in params)
  9478. {
  9479. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9480. continue;
  9481. var v = params[k];
  9482. var confKey = k.substr(7);
  9483. if(config[confKey] && typeof config[confKey] !== typeof v)
  9484. {
  9485. console.warn("The type of " + k +
  9486. " is wrong. That parameter won't be updated in config.js.");
  9487. continue;
  9488. }
  9489. config[confKey] = v;
  9490. }
  9491. }
  9492. };
  9493. module.exports = URLProcessor;
  9494. },{}],43:[function(require,module,exports){
  9495. var EventEmitter = require("events");
  9496. var eventEmitter = new EventEmitter();
  9497. var CQEvents = require("../../service/connectionquality/CQEvents");
  9498. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9499. /**
  9500. * local stats
  9501. * @type {{}}
  9502. */
  9503. var stats = {};
  9504. /**
  9505. * remote stats
  9506. * @type {{}}
  9507. */
  9508. var remoteStats = {};
  9509. /**
  9510. * Interval for sending statistics to other participants
  9511. * @type {null}
  9512. */
  9513. var sendIntervalId = null;
  9514. /**
  9515. * Start statistics sending.
  9516. */
  9517. function startSendingStats() {
  9518. sendStats();
  9519. sendIntervalId = setInterval(sendStats, 10000);
  9520. }
  9521. /**
  9522. * Sends statistics to other participants
  9523. */
  9524. function sendStats() {
  9525. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9526. }
  9527. /**
  9528. * Converts statistics to format for sending through XMPP
  9529. * @param stats the statistics
  9530. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9531. */
  9532. function convertToMUCStats(stats) {
  9533. return {
  9534. "bitrate_download": stats.bitrate.download,
  9535. "bitrate_upload": stats.bitrate.upload,
  9536. "packetLoss_total": stats.packetLoss.total,
  9537. "packetLoss_download": stats.packetLoss.download,
  9538. "packetLoss_upload": stats.packetLoss.upload
  9539. };
  9540. }
  9541. /**
  9542. * Converts statitistics to format used by VideoLayout
  9543. * @param stats
  9544. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9545. */
  9546. function parseMUCStats(stats) {
  9547. return {
  9548. bitrate: {
  9549. download: stats.bitrate_download,
  9550. upload: stats.bitrate_upload
  9551. },
  9552. packetLoss: {
  9553. total: stats.packetLoss_total,
  9554. download: stats.packetLoss_download,
  9555. upload: stats.packetLoss_upload
  9556. }
  9557. };
  9558. }
  9559. var ConnectionQuality = {
  9560. init: function () {
  9561. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9562. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9563. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9564. },
  9565. /**
  9566. * Updates the local statistics
  9567. * @param data new statistics
  9568. */
  9569. updateLocalStats: function (data) {
  9570. stats = data;
  9571. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9572. if (sendIntervalId == null) {
  9573. startSendingStats();
  9574. }
  9575. },
  9576. /**
  9577. * Updates remote statistics
  9578. * @param jid the jid associated with the statistics
  9579. * @param data the statistics
  9580. */
  9581. updateRemoteStats: function (jid, data) {
  9582. if (data == null || data.packetLoss_total == null) {
  9583. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9584. return;
  9585. }
  9586. remoteStats[jid] = parseMUCStats(data);
  9587. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9588. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9589. },
  9590. /**
  9591. * Stops statistics sending.
  9592. */
  9593. stopSendingStats: function () {
  9594. clearInterval(sendIntervalId);
  9595. sendIntervalId = null;
  9596. //notify UI about stopping statistics gathering
  9597. eventEmitter.emit(CQEvents.STOP);
  9598. },
  9599. /**
  9600. * Returns the local statistics.
  9601. */
  9602. getStats: function () {
  9603. return stats;
  9604. },
  9605. addListener: function (type, listener) {
  9606. eventEmitter.on(type, listener);
  9607. }
  9608. };
  9609. module.exports = ConnectionQuality;
  9610. },{"../../service/connectionquality/CQEvents":104,"../../service/xmpp/XMPPEvents":108,"events":109}],44:[function(require,module,exports){
  9611. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9612. getUserMediaWithConstraints */
  9613. /**
  9614. * Indicates that desktop stream is currently in use(for toggle purpose).
  9615. * @type {boolean}
  9616. */
  9617. var isUsingScreenStream = false;
  9618. /**
  9619. * Indicates that switch stream operation is in progress and prevent from
  9620. * triggering new events.
  9621. * @type {boolean}
  9622. */
  9623. var switchInProgress = false;
  9624. /**
  9625. * Method used to get screen sharing stream.
  9626. *
  9627. * @type {function (stream_callback, failure_callback}
  9628. */
  9629. var obtainDesktopStream = null;
  9630. /**
  9631. * Indicates whether desktop sharing extension is installed.
  9632. * @type {boolean}
  9633. */
  9634. var extInstalled = false;
  9635. /**
  9636. * Indicates whether update of desktop sharing extension is required.
  9637. * @type {boolean}
  9638. */
  9639. var extUpdateRequired = false;
  9640. var AdapterJS = require("../RTC/adapter.screenshare");
  9641. var EventEmitter = require("events");
  9642. var eventEmitter = new EventEmitter();
  9643. var DesktopSharingEventTypes
  9644. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9645. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9646. var RTCEvents = require("../../service/RTC/RTCEvents");
  9647. /**
  9648. * Method obtains desktop stream from WebRTC 'screen' source.
  9649. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9650. */
  9651. function obtainWebRTCScreen(streamCallback, failCallback) {
  9652. APP.RTC.getUserMediaWithConstraints(
  9653. ['screen'],
  9654. streamCallback,
  9655. failCallback
  9656. );
  9657. }
  9658. /**
  9659. * Constructs inline install URL for Chrome desktop streaming extension.
  9660. * The 'chromeExtensionId' must be defined in config.js.
  9661. * @returns {string}
  9662. */
  9663. function getWebStoreInstallUrl()
  9664. {
  9665. return "https://chrome.google.com/webstore/detail/" +
  9666. config.chromeExtensionId;
  9667. }
  9668. /**
  9669. * Checks whether extension update is required.
  9670. * @param minVersion minimal required version
  9671. * @param extVersion current extension version
  9672. * @returns {boolean}
  9673. */
  9674. function isUpdateRequired(minVersion, extVersion)
  9675. {
  9676. try
  9677. {
  9678. var s1 = minVersion.split('.');
  9679. var s2 = extVersion.split('.');
  9680. var len = Math.max(s1.length, s2.length);
  9681. for (var i = 0; i < len; i++)
  9682. {
  9683. var n1 = 0,
  9684. n2 = 0;
  9685. if (i < s1.length)
  9686. n1 = parseInt(s1[i]);
  9687. if (i < s2.length)
  9688. n2 = parseInt(s2[i]);
  9689. if (isNaN(n1) || isNaN(n2))
  9690. {
  9691. return true;
  9692. }
  9693. else if (n1 !== n2)
  9694. {
  9695. return n1 > n2;
  9696. }
  9697. }
  9698. // will happen if boths version has identical numbers in
  9699. // their components (even if one of them is longer, has more components)
  9700. return false;
  9701. }
  9702. catch (e)
  9703. {
  9704. console.error("Failed to parse extension version", e);
  9705. APP.UI.messageHandler.showError("dialog.error",
  9706. "dialog.detectext");
  9707. return true;
  9708. }
  9709. }
  9710. function checkChromeExtInstalled(callback) {
  9711. if (!chrome.runtime) {
  9712. // No API, so no extension for sure
  9713. callback(false, false);
  9714. return;
  9715. }
  9716. chrome.runtime.sendMessage(
  9717. config.chromeExtensionId,
  9718. { getVersion: true },
  9719. function (response) {
  9720. if (!response || !response.version) {
  9721. // Communication failure - assume that no endpoint exists
  9722. console.warn(
  9723. "Extension not installed?: ", chrome.runtime.lastError);
  9724. callback(false, false);
  9725. return;
  9726. }
  9727. // Check installed extension version
  9728. var extVersion = response.version;
  9729. console.log('Extension version is: ' + extVersion);
  9730. var updateRequired
  9731. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  9732. callback(!updateRequired, updateRequired);
  9733. }
  9734. );
  9735. }
  9736. function doGetStreamFromExtension(streamCallback, failCallback) {
  9737. // Sends 'getStream' msg to the extension.
  9738. // Extension id must be defined in the config.
  9739. chrome.runtime.sendMessage(
  9740. config.chromeExtensionId,
  9741. { getStream: true, sources: config.desktopSharingSources },
  9742. function (response) {
  9743. if (!response) {
  9744. failCallback(chrome.runtime.lastError);
  9745. return;
  9746. }
  9747. console.log("Response from extension: " + response);
  9748. if (response.streamId) {
  9749. APP.RTC.getUserMediaWithConstraints(
  9750. ['desktop'],
  9751. function (stream) {
  9752. streamCallback(stream);
  9753. },
  9754. failCallback,
  9755. null, null, null,
  9756. response.streamId);
  9757. } else {
  9758. failCallback("Extension failed to get the stream");
  9759. }
  9760. }
  9761. );
  9762. }
  9763. /**
  9764. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  9765. * stream for returned stream token.
  9766. */
  9767. function obtainScreenFromExtension(streamCallback, failCallback) {
  9768. if (extInstalled) {
  9769. doGetStreamFromExtension(streamCallback, failCallback);
  9770. } else {
  9771. if (extUpdateRequired) {
  9772. alert(
  9773. 'Jitsi Desktop Streamer requires update. ' +
  9774. 'Changes will take effect after next Chrome restart.');
  9775. }
  9776. chrome.webstore.install(
  9777. getWebStoreInstallUrl(),
  9778. function (arg) {
  9779. console.log("Extension installed successfully", arg);
  9780. extInstalled = true;
  9781. // We need to give a moment for the endpoint to become available
  9782. window.setTimeout(function () {
  9783. doGetStreamFromExtension(streamCallback, failCallback);
  9784. }, 500);
  9785. },
  9786. function (arg) {
  9787. console.log("Failed to install the extension", arg);
  9788. failCallback(arg);
  9789. APP.UI.messageHandler.showError("dialog.error",
  9790. "dialog.failtoinstall");
  9791. }
  9792. );
  9793. }
  9794. }
  9795. /**
  9796. * Call this method to toggle desktop sharing feature.
  9797. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  9798. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  9799. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  9800. * enabled), pass any other string or nothing in order to disable this
  9801. * feature completely.
  9802. */
  9803. function setDesktopSharing(method) {
  9804. obtainDesktopStream = null;
  9805. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  9806. // care about 'method' parameter
  9807. if (RTCBrowserType.isTemasysPluginUsed()) {
  9808. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  9809. console.info("Screensharing not supported by this plugin version");
  9810. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  9811. console.info(
  9812. "Screensharing not available with Temasys plugin on this site");
  9813. } else {
  9814. obtainDesktopStream = obtainWebRTCScreen;
  9815. console.info("Using Temasys plugin for desktop sharing");
  9816. }
  9817. } else if (RTCBrowserType.isChrome()) {
  9818. if (method == "ext") {
  9819. if (RTCBrowserType.getChromeVersion() >= 34) {
  9820. obtainDesktopStream = obtainScreenFromExtension;
  9821. console.info("Using Chrome extension for desktop sharing");
  9822. initChromeExtension();
  9823. } else {
  9824. console.info("Chrome extension not supported until ver 34");
  9825. }
  9826. } else if (method == "webrtc") {
  9827. obtainDesktopStream = obtainWebRTCScreen;
  9828. console.info("Using Chrome WebRTC for desktop sharing");
  9829. }
  9830. }
  9831. if (!obtainDesktopStream) {
  9832. console.info("Desktop sharing disabled");
  9833. }
  9834. }
  9835. /**
  9836. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  9837. * config.js to support inline installs. Host site must be selected as main
  9838. * website of published extension.
  9839. */
  9840. function initInlineInstalls()
  9841. {
  9842. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  9843. }
  9844. function initChromeExtension() {
  9845. // Initialize Chrome extension inline installs
  9846. initInlineInstalls();
  9847. // Check if extension is installed
  9848. checkChromeExtInstalled(function (installed, updateRequired) {
  9849. extInstalled = installed;
  9850. extUpdateRequired = updateRequired;
  9851. console.info(
  9852. "Chrome extension installed: " + extInstalled +
  9853. " updateRequired: " + extUpdateRequired);
  9854. });
  9855. }
  9856. function getVideoStreamFailed(error) {
  9857. console.error("Failed to obtain the stream to switch to", error);
  9858. switchInProgress = false;
  9859. isUsingScreenStream = false;
  9860. newStreamCreated(null);
  9861. }
  9862. function getDesktopStreamFailed(error) {
  9863. console.error("Failed to obtain the stream to switch to", error);
  9864. switchInProgress = false;
  9865. }
  9866. function streamSwitchDone() {
  9867. switchInProgress = false;
  9868. eventEmitter.emit(
  9869. DesktopSharingEventTypes.SWITCHING_DONE,
  9870. isUsingScreenStream);
  9871. }
  9872. function newStreamCreated(stream)
  9873. {
  9874. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  9875. stream, isUsingScreenStream, streamSwitchDone);
  9876. }
  9877. function onEndedHandler(stream) {
  9878. if (!switchInProgress && isUsingScreenStream) {
  9879. APP.desktopsharing.toggleScreenSharing();
  9880. }
  9881. //FIXME: to be verified
  9882. if (stream.removeEventListener) {
  9883. stream.removeEventListener('ended', onEndedHandler);
  9884. } else {
  9885. stream.detachEvent('ended', onEndedHandler);
  9886. }
  9887. }
  9888. // Called when RTC finishes initialization
  9889. function onWebRtcReady() {
  9890. setDesktopSharing(config.desktopSharing);
  9891. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  9892. }
  9893. module.exports = {
  9894. isUsingScreenStream: function () {
  9895. return isUsingScreenStream;
  9896. },
  9897. /**
  9898. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  9899. * and enabled.
  9900. */
  9901. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  9902. init: function () {
  9903. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  9904. },
  9905. addListener: function (listener, type)
  9906. {
  9907. eventEmitter.on(type, listener);
  9908. },
  9909. removeListener: function (listener, type) {
  9910. eventEmitter.removeListener(type, listener);
  9911. },
  9912. /*
  9913. * Toggles screen sharing.
  9914. */
  9915. toggleScreenSharing: function () {
  9916. if (switchInProgress || !obtainDesktopStream) {
  9917. console.warn("Switch in progress or no method defined");
  9918. return;
  9919. }
  9920. switchInProgress = true;
  9921. if (!isUsingScreenStream)
  9922. {
  9923. // Switch to desktop stream
  9924. obtainDesktopStream(
  9925. function (stream) {
  9926. // We now use screen stream
  9927. isUsingScreenStream = true;
  9928. // Hook 'ended' event to restore camera
  9929. // when screen stream stops
  9930. //FIXME: to be verified
  9931. if (stream.addEventListener) {
  9932. stream.addEventListener('ended', function () {
  9933. onEndedHandler(stream);
  9934. });
  9935. } else {
  9936. stream.attachEvent('ended', function () {
  9937. onEndedHandler(stream);
  9938. });
  9939. }
  9940. newStreamCreated(stream);
  9941. },
  9942. getDesktopStreamFailed);
  9943. } else {
  9944. // Disable screen stream
  9945. APP.RTC.getUserMediaWithConstraints(
  9946. ['video'],
  9947. function (stream) {
  9948. // We are now using camera stream
  9949. isUsingScreenStream = false;
  9950. newStreamCreated(stream);
  9951. },
  9952. getVideoStreamFailed, config.resolution || '360'
  9953. );
  9954. }
  9955. }
  9956. };
  9957. },{"../../service/RTC/RTCEvents":99,"../../service/desktopsharing/DesktopSharingEventTypes":105,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":109}],45:[function(require,module,exports){
  9958. //maps keycode to character, id of popover for given function and function
  9959. var shortcuts = {};
  9960. function initShortcutHandlers() {
  9961. shortcuts = {
  9962. 67: {
  9963. character: "C",
  9964. id: "toggleChatPopover",
  9965. function: APP.UI.toggleChat
  9966. },
  9967. 70: {
  9968. character: "F",
  9969. id: "filmstripPopover",
  9970. function: APP.UI.toggleFilmStrip
  9971. },
  9972. 77: {
  9973. character: "M",
  9974. id: "mutePopover",
  9975. function: APP.UI.toggleAudio
  9976. },
  9977. 84: {
  9978. character: "T",
  9979. function: function() {
  9980. if(!APP.RTC.localAudio.isMuted()) {
  9981. APP.UI.toggleAudio();
  9982. }
  9983. }
  9984. },
  9985. 86: {
  9986. character: "V",
  9987. id: "toggleVideoPopover",
  9988. function: APP.UI.toggleVideo
  9989. }
  9990. };
  9991. }
  9992. var KeyboardShortcut = {
  9993. init: function () {
  9994. initShortcutHandlers();
  9995. window.onkeyup = function(e) {
  9996. var keycode = e.which;
  9997. if(!($(":focus").is("input[type=text]") ||
  9998. $(":focus").is("input[type=password]") ||
  9999. $(":focus").is("textarea"))) {
  10000. if (typeof shortcuts[keycode] === "object") {
  10001. shortcuts[keycode].function();
  10002. }
  10003. else if (keycode >= "0".charCodeAt(0) &&
  10004. keycode <= "9".charCodeAt(0)) {
  10005. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10006. }
  10007. //esc while the smileys are visible hides them
  10008. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10009. APP.UI.toggleSmileys();
  10010. }
  10011. };
  10012. window.onkeydown = function(e) {
  10013. if(!($(":focus").is("input[type=text]") ||
  10014. $(":focus").is("input[type=password]") ||
  10015. $(":focus").is("textarea"))) {
  10016. if(e.which === "T".charCodeAt(0)) {
  10017. if(APP.RTC.localAudio.isMuted()) {
  10018. APP.UI.toggleAudio();
  10019. }
  10020. }
  10021. }
  10022. };
  10023. var self = this;
  10024. $('body').popover({ selector: '[data-toggle=popover]',
  10025. trigger: 'click hover',
  10026. content: function() {
  10027. return this.getAttribute("content") +
  10028. self.getShortcut(this.getAttribute("shortcut"));
  10029. }
  10030. });
  10031. },
  10032. /**
  10033. *
  10034. * @param id indicates the popover associated with the shortcut
  10035. * @returns {string} the keyboard shortcut used for the id given
  10036. */
  10037. getShortcut: function (id) {
  10038. for (var keycode in shortcuts) {
  10039. if (shortcuts.hasOwnProperty(keycode)) {
  10040. if (shortcuts[keycode].id === id) {
  10041. return " (" + shortcuts[keycode].character + ")";
  10042. }
  10043. }
  10044. }
  10045. return "";
  10046. }
  10047. };
  10048. module.exports = KeyboardShortcut;
  10049. },{}],46:[function(require,module,exports){
  10050. /* global APP */
  10051. /**
  10052. * This module is meant to (eventually) contain and manage all information
  10053. * about members/participants of the conference, so that other modules don't
  10054. * have to do it on their own, and so that other modules can access members'
  10055. * information from a single place.
  10056. *
  10057. * Currently this module only manages information about the support of jingle
  10058. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10059. * be added as needed.
  10060. */
  10061. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10062. var Events = require("../../service/members/Events");
  10063. var EventEmitter = require("events");
  10064. var eventEmitter = new EventEmitter();
  10065. /**
  10066. * The actual container.
  10067. */
  10068. var members = {};
  10069. /**
  10070. * There is at least one member that supports DTMF (i.e. is jigasi).
  10071. */
  10072. var atLeastOneDtmf = false;
  10073. function registerListeners() {
  10074. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10075. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10076. }
  10077. /**
  10078. * Handles a new member joining the MUC.
  10079. */
  10080. function onMucMemberJoined(jid, id, displayName) {
  10081. var member = {
  10082. displayName: displayName
  10083. };
  10084. APP.xmpp.getConnection().disco.info(
  10085. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10086. members[jid] = member;
  10087. }
  10088. /**
  10089. * Handles a member leaving the MUC.
  10090. */
  10091. function onMucMemberLeft(jid) {
  10092. delete members[jid];
  10093. updateAtLeastOneDtmf();
  10094. }
  10095. /**
  10096. * Handles the reception of a disco#info packet from a particular JID.
  10097. * @param jid the JID sending the packet.
  10098. * @param iq the packet.
  10099. */
  10100. function onDiscoInfoReceived(jid, iq) {
  10101. if (!members[jid])
  10102. return;
  10103. var supportsDtmf
  10104. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10105. updateDtmf(jid, supportsDtmf);
  10106. }
  10107. /**
  10108. * Updates the 'supportsDtmf' field for a member.
  10109. * @param jid the jid of the member.
  10110. * @param newValue the new value for the 'supportsDtmf' field.
  10111. */
  10112. function updateDtmf(jid, newValue) {
  10113. var oldValue = members[jid].supportsDtmf;
  10114. members[jid].supportsDtmf = newValue;
  10115. if (newValue != oldValue) {
  10116. updateAtLeastOneDtmf();
  10117. }
  10118. }
  10119. /**
  10120. * Checks each member's 'supportsDtmf' field and updates
  10121. * 'atLastOneSupportsDtmf'.
  10122. */
  10123. function updateAtLeastOneDtmf(){
  10124. var newAtLeastOneDtmf = false;
  10125. for (var key in members) {
  10126. if (typeof members[key].supportsDtmf !== 'undefined'
  10127. && members[key].supportsDtmf) {
  10128. newAtLeastOneDtmf= true;
  10129. break;
  10130. }
  10131. }
  10132. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10133. atLeastOneDtmf = newAtLeastOneDtmf;
  10134. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10135. }
  10136. }
  10137. /**
  10138. * Exported interface.
  10139. */
  10140. var Members = {
  10141. start: function(){
  10142. registerListeners();
  10143. },
  10144. addListener: function(type, listener)
  10145. {
  10146. eventEmitter.on(type, listener);
  10147. },
  10148. removeListener: function (type, listener) {
  10149. eventEmitter.removeListener(type, listener);
  10150. },
  10151. size: function () {
  10152. return Object.keys(members).length;
  10153. },
  10154. getMembers: function () {
  10155. return members;
  10156. }
  10157. };
  10158. module.exports = Members;
  10159. },{"../../service/members/Events":106,"../../service/xmpp/XMPPEvents":108,"events":109}],47:[function(require,module,exports){
  10160. var email = '';
  10161. var displayName = '';
  10162. var userId;
  10163. var language = null;
  10164. function supportsLocalStorage() {
  10165. try {
  10166. return 'localStorage' in window && window.localStorage !== null;
  10167. } catch (e) {
  10168. console.log("localstorage is not supported");
  10169. return false;
  10170. }
  10171. }
  10172. function generateUniqueId() {
  10173. function _p8() {
  10174. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10175. }
  10176. return _p8() + _p8() + _p8() + _p8();
  10177. }
  10178. if (supportsLocalStorage()) {
  10179. if (!window.localStorage.jitsiMeetId) {
  10180. window.localStorage.jitsiMeetId = generateUniqueId();
  10181. console.log("generated id", window.localStorage.jitsiMeetId);
  10182. }
  10183. userId = window.localStorage.jitsiMeetId || '';
  10184. email = window.localStorage.email || '';
  10185. displayName = window.localStorage.displayname || '';
  10186. language = window.localStorage.language;
  10187. } else {
  10188. console.log("local storage is not supported");
  10189. userId = generateUniqueId();
  10190. }
  10191. var Settings =
  10192. {
  10193. setDisplayName: function (newDisplayName) {
  10194. displayName = newDisplayName;
  10195. window.localStorage.displayname = displayName;
  10196. return displayName;
  10197. },
  10198. setEmail: function (newEmail)
  10199. {
  10200. email = newEmail;
  10201. window.localStorage.email = newEmail;
  10202. return email;
  10203. },
  10204. getSettings: function () {
  10205. return {
  10206. email: email,
  10207. displayName: displayName,
  10208. uid: userId,
  10209. language: language
  10210. };
  10211. },
  10212. setLanguage: function (lang) {
  10213. language = lang;
  10214. window.localStorage.language = lang;
  10215. }
  10216. };
  10217. module.exports = Settings;
  10218. },{}],48:[function(require,module,exports){
  10219. var callStats = null;
  10220. function initCallback (err, msg) {
  10221. console.log("Initializing Status: err="+err+" msg="+msg);
  10222. }
  10223. var CallStats = {
  10224. init: function (jingleSession) {
  10225. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10226. return;
  10227. callStats = new callstats($,io,jsSHA);
  10228. this.session = jingleSession;
  10229. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10230. this.userID = APP.xmpp.myResource();
  10231. var roomJid = APP.UI.getRoomName();
  10232. this.confID = roomJid? Strophe.getNodeFromJid(roomJid) : null;
  10233. //userID is generated or given by the origin server
  10234. callStats.initialize(config.callStatsID,
  10235. config.callStatsSecret,
  10236. this.userID,
  10237. initCallback);
  10238. var usage = callStats.fabricUsage.unbundled;
  10239. if(config.useBundle)
  10240. usage = callStats.fabricUsage.multiplex;
  10241. callStats.addNewFabric(this.peerconnection,
  10242. Strophe.getResourceFromJid(jingleSession.peerjid),
  10243. usage,
  10244. this.confID,
  10245. this.pcCallback.bind(this));
  10246. },
  10247. pcCallback: function (err, msg) {
  10248. if(!callStats)
  10249. return;
  10250. console.log("Monitoring status: "+ err + " msg: " + msg);
  10251. callStats.sendFabricEvent(this.peerconnection,
  10252. callStats.fabricEvent.fabricSetup, this.confID);
  10253. },
  10254. sendMuteEvent: function (mute, type) {
  10255. if(!callStats)
  10256. return;
  10257. var event = null;
  10258. if(type === "video")
  10259. {
  10260. event = (mute? callStats.fabricEvent.videoPause :
  10261. callStats.fabricEvent.videoResume);
  10262. }
  10263. else
  10264. {
  10265. event = (mute? callStats.fabricEvent.audioMute :
  10266. callStats.fabricEvent.audioUnmute);
  10267. }
  10268. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10269. },
  10270. sendTerminateEvent: function () {
  10271. if(!callStats)
  10272. return;
  10273. callStats.sendFabricEvent(this.peerconnection,
  10274. callStats.fabricEvent.fabricTerminated, this.confID);
  10275. },
  10276. sendSetupFailedEvent: function () {
  10277. if(!callStats)
  10278. return;
  10279. callStats.sendFabricEvent(this.peerconnection,
  10280. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10281. }
  10282. };
  10283. module.exports = CallStats;
  10284. },{}],49:[function(require,module,exports){
  10285. /**
  10286. * Provides statistics for the local stream.
  10287. */
  10288. /**
  10289. * Size of the webaudio analizer buffer.
  10290. * @type {number}
  10291. */
  10292. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  10293. /**
  10294. * Value of the webaudio analizer smoothing time parameter.
  10295. * @type {number}
  10296. */
  10297. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  10298. /**
  10299. * Converts time domain data array to audio level.
  10300. * @param array the time domain data array.
  10301. * @returns {number} the audio level
  10302. */
  10303. function timeDomainDataToAudioLevel(samples) {
  10304. var maxVolume = 0;
  10305. var length = samples.length;
  10306. for (var i = 0; i < length; i++) {
  10307. if (maxVolume < samples[i])
  10308. maxVolume = samples[i];
  10309. }
  10310. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10311. };
  10312. /**
  10313. * Animates audio level change
  10314. * @param newLevel the new audio level
  10315. * @param lastLevel the last audio level
  10316. * @returns {Number} the audio level to be set
  10317. */
  10318. function animateLevel(newLevel, lastLevel)
  10319. {
  10320. var value = 0;
  10321. var diff = lastLevel - newLevel;
  10322. if(diff > 0.2)
  10323. {
  10324. value = lastLevel - 0.2;
  10325. }
  10326. else if(diff < -0.4)
  10327. {
  10328. value = lastLevel + 0.4;
  10329. }
  10330. else
  10331. {
  10332. value = newLevel;
  10333. }
  10334. return parseFloat(value.toFixed(3));
  10335. }
  10336. /**
  10337. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10338. *
  10339. * @param stream the local stream
  10340. * @param interval stats refresh interval given in ms.
  10341. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  10342. * update.
  10343. * @constructor
  10344. */
  10345. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10346. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10347. this.stream = stream;
  10348. this.intervalId = null;
  10349. this.intervalMilis = interval;
  10350. this.eventEmitter = eventEmitter;
  10351. this.audioLevel = 0;
  10352. this.statisticsService = statisticsService;
  10353. }
  10354. /**
  10355. * Starts the collecting the statistics.
  10356. */
  10357. LocalStatsCollector.prototype.start = function () {
  10358. if (config.disableAudioLevels || !window.AudioContext)
  10359. return;
  10360. var context = new AudioContext();
  10361. var analyser = context.createAnalyser();
  10362. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  10363. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  10364. var source = context.createMediaStreamSource(this.stream);
  10365. source.connect(analyser);
  10366. var self = this;
  10367. this.intervalId = setInterval(
  10368. function () {
  10369. var array = new Uint8Array(analyser.frequencyBinCount);
  10370. analyser.getByteTimeDomainData(array);
  10371. var audioLevel = timeDomainDataToAudioLevel(array);
  10372. if(audioLevel != self.audioLevel) {
  10373. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10374. self.eventEmitter.emit(
  10375. "statistics.audioLevel",
  10376. self.statisticsService.LOCAL_JID,
  10377. self.audioLevel);
  10378. }
  10379. },
  10380. this.intervalMilis
  10381. );
  10382. };
  10383. /**
  10384. * Stops collecting the statistics.
  10385. */
  10386. LocalStatsCollector.prototype.stop = function () {
  10387. if (this.intervalId) {
  10388. clearInterval(this.intervalId);
  10389. this.intervalId = null;
  10390. }
  10391. };
  10392. module.exports = LocalStatsCollector;
  10393. },{}],50:[function(require,module,exports){
  10394. /* global ssrc2jid */
  10395. /* jshint -W117 */
  10396. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10397. /**
  10398. * Calculates packet lost percent using the number of lost packets and the
  10399. * number of all packet.
  10400. * @param lostPackets the number of lost packets
  10401. * @param totalPackets the number of all packets.
  10402. * @returns {number} packet loss percent
  10403. */
  10404. function calculatePacketLoss(lostPackets, totalPackets) {
  10405. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10406. return 0;
  10407. return Math.round((lostPackets/totalPackets)*100);
  10408. }
  10409. function getStatValue(item, name) {
  10410. var browserType = RTCBrowserType.getBrowserType();
  10411. if (!keyMap[browserType][name])
  10412. throw "The property isn't supported!";
  10413. var key = keyMap[browserType][name];
  10414. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10415. item.stat(key) : item[key];
  10416. }
  10417. /**
  10418. * Peer statistics data holder.
  10419. * @constructor
  10420. */
  10421. function PeerStats()
  10422. {
  10423. this.ssrc2Loss = {};
  10424. this.ssrc2AudioLevel = {};
  10425. this.ssrc2bitrate = {};
  10426. this.ssrc2resolution = {};
  10427. }
  10428. /**
  10429. * The bandwidth
  10430. * @type {{}}
  10431. */
  10432. PeerStats.bandwidth = {};
  10433. /**
  10434. * The bit rate
  10435. * @type {{}}
  10436. */
  10437. PeerStats.bitrate = {};
  10438. /**
  10439. * The packet loss rate
  10440. * @type {{}}
  10441. */
  10442. PeerStats.packetLoss = null;
  10443. /**
  10444. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10445. * represented by this instance.
  10446. * @param ssrc audio or video RTP stream SSRC.
  10447. * @param lossRate new packet loss rate value to be set.
  10448. */
  10449. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10450. {
  10451. this.ssrc2Loss[ssrc] = lossRate;
  10452. };
  10453. /**
  10454. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10455. * represented by this instance.
  10456. * @param ssrc audio or video RTP stream SSRC.
  10457. * @param resolution new resolution value to be set.
  10458. */
  10459. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10460. {
  10461. if(resolution === null && this.ssrc2resolution[ssrc])
  10462. {
  10463. delete this.ssrc2resolution[ssrc];
  10464. }
  10465. else if(resolution !== null)
  10466. this.ssrc2resolution[ssrc] = resolution;
  10467. };
  10468. /**
  10469. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10470. * represented by this instance.
  10471. * @param ssrc audio or video RTP stream SSRC.
  10472. * @param bitrate new bitrate value to be set.
  10473. */
  10474. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10475. {
  10476. if(this.ssrc2bitrate[ssrc])
  10477. {
  10478. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10479. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10480. }
  10481. else {
  10482. this.ssrc2bitrate[ssrc] = bitrate;
  10483. }
  10484. };
  10485. /**
  10486. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10487. * the stream which belongs to the peer represented by this instance.
  10488. * @param ssrc RTP stream SSRC for which current audio level value will be
  10489. * updated.
  10490. * @param audioLevel the new audio level value to be set. Value is truncated to
  10491. * fit the range from 0 to 1.
  10492. */
  10493. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10494. {
  10495. // Range limit 0 - 1
  10496. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10497. };
  10498. function formatAudioLevel(audioLevel) {
  10499. return Math.min(Math.max(audioLevel, 0), 1);
  10500. }
  10501. /**
  10502. * Array with the transport information.
  10503. * @type {Array}
  10504. */
  10505. PeerStats.transport = [];
  10506. /**
  10507. * <tt>StatsCollector</tt> registers for stats updates of given
  10508. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10509. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10510. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10511. * instance as an event source.
  10512. *
  10513. * @param peerconnection webRTC peer connection object.
  10514. * @param interval stats refresh interval given in ms.
  10515. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10516. * called on stats update.
  10517. * @constructor
  10518. */
  10519. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10520. {
  10521. this.peerconnection = peerconnection;
  10522. this.baselineAudioLevelsReport = null;
  10523. this.currentAudioLevelsReport = null;
  10524. this.currentStatsReport = null;
  10525. this.baselineStatsReport = null;
  10526. this.audioLevelsIntervalId = null;
  10527. this.eventEmitter = eventEmitter;
  10528. /**
  10529. * Gather PeerConnection stats once every this many milliseconds.
  10530. */
  10531. this.GATHER_INTERVAL = 15000;
  10532. /**
  10533. * Log stats via the focus once every this many milliseconds.
  10534. */
  10535. this.LOG_INTERVAL = 60000;
  10536. /**
  10537. * Gather stats and store them in this.statsToBeLogged.
  10538. */
  10539. this.gatherStatsIntervalId = null;
  10540. /**
  10541. * Send the stats already saved in this.statsToBeLogged to be logged via
  10542. * the focus.
  10543. */
  10544. this.logStatsIntervalId = null;
  10545. /**
  10546. * Stores the statistics which will be send to the focus to be logged.
  10547. */
  10548. this.statsToBeLogged =
  10549. {
  10550. timestamps: [],
  10551. stats: {}
  10552. };
  10553. // Updates stats interval
  10554. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10555. this.statsIntervalId = null;
  10556. this.statsIntervalMilis = statsInterval;
  10557. // Map of jids to PeerStats
  10558. this.jid2stats = {};
  10559. }
  10560. module.exports = StatsCollector;
  10561. /**
  10562. * Stops stats updates.
  10563. */
  10564. StatsCollector.prototype.stop = function () {
  10565. if (this.audioLevelsIntervalId) {
  10566. clearInterval(this.audioLevelsIntervalId);
  10567. this.audioLevelsIntervalId = null;
  10568. }
  10569. if (this.statsIntervalId)
  10570. {
  10571. clearInterval(this.statsIntervalId);
  10572. this.statsIntervalId = null;
  10573. }
  10574. if(this.logStatsIntervalId)
  10575. {
  10576. clearInterval(this.logStatsIntervalId);
  10577. this.logStatsIntervalId = null;
  10578. }
  10579. if(this.gatherStatsIntervalId)
  10580. {
  10581. clearInterval(this.gatherStatsIntervalId);
  10582. this.gatherStatsIntervalId = null;
  10583. }
  10584. };
  10585. /**
  10586. * Callback passed to <tt>getStats</tt> method.
  10587. * @param error an error that occurred on <tt>getStats</tt> call.
  10588. */
  10589. StatsCollector.prototype.errorCallback = function (error)
  10590. {
  10591. console.error("Get stats error", error);
  10592. this.stop();
  10593. };
  10594. /**
  10595. * Starts stats updates.
  10596. */
  10597. StatsCollector.prototype.start = function ()
  10598. {
  10599. var self = this;
  10600. if(!config.disableAudioLevels) {
  10601. this.audioLevelsIntervalId = setInterval(
  10602. function () {
  10603. // Interval updates
  10604. self.peerconnection.getStats(
  10605. function (report) {
  10606. var results = null;
  10607. if (!report || !report.result ||
  10608. typeof report.result != 'function') {
  10609. results = report;
  10610. }
  10611. else {
  10612. results = report.result();
  10613. }
  10614. //console.error("Got interval report", results);
  10615. self.currentAudioLevelsReport = results;
  10616. self.processAudioLevelReport();
  10617. self.baselineAudioLevelsReport =
  10618. self.currentAudioLevelsReport;
  10619. },
  10620. self.errorCallback
  10621. );
  10622. },
  10623. self.audioLevelsIntervalMilis
  10624. );
  10625. }
  10626. if(!config.disableStats && !navigator.mozGetUserMedia) {
  10627. this.statsIntervalId = setInterval(
  10628. function () {
  10629. // Interval updates
  10630. self.peerconnection.getStats(
  10631. function (report) {
  10632. var results = null;
  10633. if (!report || !report.result ||
  10634. typeof report.result != 'function') {
  10635. //firefox
  10636. results = report;
  10637. }
  10638. else {
  10639. //chrome
  10640. results = report.result();
  10641. }
  10642. //console.error("Got interval report", results);
  10643. self.currentStatsReport = results;
  10644. try {
  10645. self.processStatsReport();
  10646. }
  10647. catch (e) {
  10648. console.error("Unsupported key:" + e, e);
  10649. }
  10650. self.baselineStatsReport = self.currentStatsReport;
  10651. },
  10652. self.errorCallback
  10653. );
  10654. },
  10655. self.statsIntervalMilis
  10656. );
  10657. }
  10658. if (config.logStats && !navigator.mozGetUserMedia) {
  10659. this.gatherStatsIntervalId = setInterval(
  10660. function () {
  10661. self.peerconnection.getStats(
  10662. function (report) {
  10663. self.addStatsToBeLogged(report.result());
  10664. },
  10665. function () {
  10666. }
  10667. );
  10668. },
  10669. this.GATHER_INTERVAL
  10670. );
  10671. this.logStatsIntervalId = setInterval(
  10672. function() { self.logStats(); },
  10673. this.LOG_INTERVAL);
  10674. }
  10675. };
  10676. /**
  10677. * Checks whether a certain record should be included in the logged statistics.
  10678. */
  10679. function acceptStat(reportId, reportType, statName) {
  10680. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10681. return false;
  10682. if (reportType == "ssrc") {
  10683. if (statName == "googTrackId" ||
  10684. statName == "transportId" ||
  10685. statName == "ssrc")
  10686. return false;
  10687. }
  10688. return true;
  10689. }
  10690. /**
  10691. * Checks whether a certain record should be included in the logged statistics.
  10692. */
  10693. function acceptReport(id, type) {
  10694. if (id.substring(0, 15) == "googCertificate" ||
  10695. id.substring(0, 9) == "googTrack" ||
  10696. id.substring(0, 20) == "googLibjingleSession")
  10697. return false;
  10698. if (type == "googComponent")
  10699. return false;
  10700. return true;
  10701. }
  10702. /**
  10703. * Converts the stats to the format used for logging, and saves the data in
  10704. * this.statsToBeLogged.
  10705. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10706. */
  10707. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10708. var self = this;
  10709. var num_records = this.statsToBeLogged.timestamps.length;
  10710. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10711. reports.map(function (report) {
  10712. if (!acceptReport(report.id, report.type))
  10713. return;
  10714. var stat = self.statsToBeLogged.stats[report.id];
  10715. if (!stat) {
  10716. stat = self.statsToBeLogged.stats[report.id] = {};
  10717. }
  10718. stat.type = report.type;
  10719. report.names().map(function (name) {
  10720. if (!acceptStat(report.id, report.type, name))
  10721. return;
  10722. var values = stat[name];
  10723. if (!values) {
  10724. values = stat[name] = [];
  10725. }
  10726. while (values.length < num_records) {
  10727. values.push(null);
  10728. }
  10729. values.push(report.stat(name));
  10730. });
  10731. });
  10732. };
  10733. StatsCollector.prototype.logStats = function () {
  10734. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10735. return;
  10736. // Reset the stats
  10737. this.statsToBeLogged.stats = {};
  10738. this.statsToBeLogged.timestamps = [];
  10739. };
  10740. var keyMap = {};
  10741. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10742. "ssrc": "ssrc",
  10743. "packetsReceived": "packetsReceived",
  10744. "packetsLost": "packetsLost",
  10745. "packetsSent": "packetsSent",
  10746. "bytesReceived": "bytesReceived",
  10747. "bytesSent": "bytesSent"
  10748. };
  10749. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10750. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10751. "sendBandwidth": "googAvailableSendBandwidth",
  10752. "remoteAddress": "googRemoteAddress",
  10753. "transportType": "googTransportType",
  10754. "localAddress": "googLocalAddress",
  10755. "activeConnection": "googActiveConnection",
  10756. "ssrc": "ssrc",
  10757. "packetsReceived": "packetsReceived",
  10758. "packetsSent": "packetsSent",
  10759. "packetsLost": "packetsLost",
  10760. "bytesReceived": "bytesReceived",
  10761. "bytesSent": "bytesSent",
  10762. "googFrameHeightReceived": "googFrameHeightReceived",
  10763. "googFrameWidthReceived": "googFrameWidthReceived",
  10764. "googFrameHeightSent": "googFrameHeightSent",
  10765. "googFrameWidthSent": "googFrameWidthSent",
  10766. "audioInputLevel": "audioInputLevel",
  10767. "audioOutputLevel": "audioOutputLevel"
  10768. };
  10769. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  10770. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  10771. /**
  10772. * Stats processing logic.
  10773. */
  10774. StatsCollector.prototype.processStatsReport = function () {
  10775. if (!this.baselineStatsReport) {
  10776. return;
  10777. }
  10778. for (var idx in this.currentStatsReport) {
  10779. var now = this.currentStatsReport[idx];
  10780. try {
  10781. if (getStatValue(now, 'receiveBandwidth') ||
  10782. getStatValue(now, 'sendBandwidth')) {
  10783. PeerStats.bandwidth = {
  10784. "download": Math.round(
  10785. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10786. "upload": Math.round(
  10787. (getStatValue(now, 'sendBandwidth')) / 1000)
  10788. };
  10789. }
  10790. }
  10791. catch(e){/*not supported*/}
  10792. if(now.type == 'googCandidatePair')
  10793. {
  10794. var ip, type, localIP, active;
  10795. try {
  10796. ip = getStatValue(now, 'remoteAddress');
  10797. type = getStatValue(now, "transportType");
  10798. localIP = getStatValue(now, "localAddress");
  10799. active = getStatValue(now, "activeConnection");
  10800. }
  10801. catch(e){/*not supported*/}
  10802. if(!ip || !type || !localIP || active != "true")
  10803. continue;
  10804. var addressSaved = false;
  10805. for(var i = 0; i < PeerStats.transport.length; i++)
  10806. {
  10807. if(PeerStats.transport[i].ip == ip &&
  10808. PeerStats.transport[i].type == type &&
  10809. PeerStats.transport[i].localip == localIP)
  10810. {
  10811. addressSaved = true;
  10812. }
  10813. }
  10814. if(addressSaved)
  10815. continue;
  10816. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10817. continue;
  10818. }
  10819. if(now.type == "candidatepair")
  10820. {
  10821. if(now.state == "succeeded")
  10822. continue;
  10823. var local = this.currentStatsReport[now.localCandidateId];
  10824. var remote = this.currentStatsReport[now.remoteCandidateId];
  10825. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10826. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10827. }
  10828. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10829. now.type != "inboundrtp") {
  10830. continue;
  10831. }
  10832. var before = this.baselineStatsReport[idx];
  10833. if (!before) {
  10834. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10835. continue;
  10836. }
  10837. var ssrc = getStatValue(now, 'ssrc');
  10838. if(!ssrc)
  10839. continue;
  10840. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10841. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10842. console.warn("No jid for ssrc: " + ssrc);
  10843. continue;
  10844. }
  10845. var jidStats = this.jid2stats[jid];
  10846. if (!jidStats) {
  10847. jidStats = new PeerStats();
  10848. this.jid2stats[jid] = jidStats;
  10849. }
  10850. var isDownloadStream = true;
  10851. var key = 'packetsReceived';
  10852. if (!getStatValue(now, key))
  10853. {
  10854. isDownloadStream = false;
  10855. key = 'packetsSent';
  10856. if (!getStatValue(now, key))
  10857. {
  10858. console.warn("No packetsReceived nor packetSent stat found");
  10859. continue;
  10860. }
  10861. }
  10862. var packetsNow = getStatValue(now, key);
  10863. if(!packetsNow || packetsNow < 0)
  10864. packetsNow = 0;
  10865. var packetsBefore = getStatValue(before, key);
  10866. if(!packetsBefore || packetsBefore < 0)
  10867. packetsBefore = 0;
  10868. var packetRate = packetsNow - packetsBefore;
  10869. if(!packetRate || packetRate < 0)
  10870. packetRate = 0;
  10871. var currentLoss = getStatValue(now, 'packetsLost');
  10872. if(!currentLoss || currentLoss < 0)
  10873. currentLoss = 0;
  10874. var previousLoss = getStatValue(before, 'packetsLost');
  10875. if(!previousLoss || previousLoss < 0)
  10876. previousLoss = 0;
  10877. var lossRate = currentLoss - previousLoss;
  10878. if(!lossRate || lossRate < 0)
  10879. lossRate = 0;
  10880. var packetsTotal = (packetRate + lossRate);
  10881. jidStats.setSsrcLoss(ssrc,
  10882. {"packetsTotal": packetsTotal,
  10883. "packetsLost": lossRate,
  10884. "isDownloadStream": isDownloadStream});
  10885. var bytesReceived = 0, bytesSent = 0;
  10886. if(getStatValue(now, "bytesReceived"))
  10887. {
  10888. bytesReceived = getStatValue(now, "bytesReceived") -
  10889. getStatValue(before, "bytesReceived");
  10890. }
  10891. if(getStatValue(now, "bytesSent"))
  10892. {
  10893. bytesSent = getStatValue(now, "bytesSent") -
  10894. getStatValue(before, "bytesSent");
  10895. }
  10896. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10897. if(bytesReceived <= 0 || time <= 0)
  10898. {
  10899. bytesReceived = 0;
  10900. }
  10901. else
  10902. {
  10903. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10904. }
  10905. if(bytesSent <= 0 || time <= 0)
  10906. {
  10907. bytesSent = 0;
  10908. }
  10909. else
  10910. {
  10911. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10912. }
  10913. jidStats.setSsrcBitrate(ssrc, {
  10914. "download": bytesReceived,
  10915. "upload": bytesSent});
  10916. var resolution = {height: null, width: null};
  10917. try {
  10918. if (getStatValue(now, "googFrameHeightReceived") &&
  10919. getStatValue(now, "googFrameWidthReceived")) {
  10920. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10921. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10922. }
  10923. else if (getStatValue(now, "googFrameHeightSent") &&
  10924. getStatValue(now, "googFrameWidthSent")) {
  10925. resolution.height = getStatValue(now, "googFrameHeightSent");
  10926. resolution.width = getStatValue(now, "googFrameWidthSent");
  10927. }
  10928. }
  10929. catch(e){/*not supported*/}
  10930. if(resolution.height && resolution.width)
  10931. {
  10932. jidStats.setSsrcResolution(ssrc, resolution);
  10933. }
  10934. else
  10935. {
  10936. jidStats.setSsrcResolution(ssrc, null);
  10937. }
  10938. }
  10939. var self = this;
  10940. // Jid stats
  10941. var totalPackets = {download: 0, upload: 0};
  10942. var lostPackets = {download: 0, upload: 0};
  10943. var bitrateDownload = 0;
  10944. var bitrateUpload = 0;
  10945. var resolutions = {};
  10946. Object.keys(this.jid2stats).forEach(
  10947. function (jid)
  10948. {
  10949. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10950. function (ssrc)
  10951. {
  10952. var type = "upload";
  10953. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10954. type = "download";
  10955. totalPackets[type] +=
  10956. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10957. lostPackets[type] +=
  10958. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10959. }
  10960. );
  10961. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10962. function (ssrc) {
  10963. bitrateDownload +=
  10964. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10965. bitrateUpload +=
  10966. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10967. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10968. }
  10969. );
  10970. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10971. }
  10972. );
  10973. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10974. PeerStats.packetLoss = {
  10975. total:
  10976. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10977. totalPackets.download + totalPackets.upload),
  10978. download:
  10979. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10980. upload:
  10981. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10982. };
  10983. this.eventEmitter.emit("statistics.connectionstats",
  10984. {
  10985. "bitrate": PeerStats.bitrate,
  10986. "packetLoss": PeerStats.packetLoss,
  10987. "bandwidth": PeerStats.bandwidth,
  10988. "resolution": resolutions,
  10989. "transport": PeerStats.transport
  10990. });
  10991. PeerStats.transport = [];
  10992. };
  10993. /**
  10994. * Stats processing logic.
  10995. */
  10996. StatsCollector.prototype.processAudioLevelReport = function ()
  10997. {
  10998. if (!this.baselineAudioLevelsReport)
  10999. {
  11000. return;
  11001. }
  11002. for (var idx in this.currentAudioLevelsReport)
  11003. {
  11004. var now = this.currentAudioLevelsReport[idx];
  11005. if (now.type != 'ssrc')
  11006. {
  11007. continue;
  11008. }
  11009. var before = this.baselineAudioLevelsReport[idx];
  11010. if (!before)
  11011. {
  11012. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11013. continue;
  11014. }
  11015. var ssrc = getStatValue(now, 'ssrc');
  11016. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11017. if (!jid)
  11018. {
  11019. if((Date.now() - now.timestamp) < 3000)
  11020. console.warn("No jid for ssrc: " + ssrc);
  11021. continue;
  11022. }
  11023. var jidStats = this.jid2stats[jid];
  11024. if (!jidStats)
  11025. {
  11026. jidStats = new PeerStats();
  11027. this.jid2stats[jid] = jidStats;
  11028. }
  11029. // Audio level
  11030. var audioLevel = null;
  11031. try {
  11032. audioLevel = getStatValue(now, 'audioInputLevel');
  11033. if (!audioLevel)
  11034. audioLevel = getStatValue(now, 'audioOutputLevel');
  11035. }
  11036. catch(e) {/*not supported*/
  11037. console.warn("Audio Levels are not available in the statistics.");
  11038. clearInterval(this.audioLevelsIntervalId);
  11039. return;
  11040. }
  11041. if (audioLevel)
  11042. {
  11043. // TODO: can't find specs about what this value really is,
  11044. // but it seems to vary between 0 and around 32k.
  11045. audioLevel = audioLevel / 32767;
  11046. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11047. if(jid != APP.xmpp.myJid())
  11048. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11049. }
  11050. }
  11051. };
  11052. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11053. /**
  11054. * Created by hristo on 8/4/14.
  11055. */
  11056. var LocalStats = require("./LocalStatsCollector.js");
  11057. var RTPStats = require("./RTPStatsCollector.js");
  11058. var EventEmitter = require("events");
  11059. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11060. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11061. var CallStats = require("./CallStats");
  11062. var RTCEvents = require("../../service/RTC/RTCEvents");
  11063. var eventEmitter = new EventEmitter();
  11064. var localStats = null;
  11065. var rtpStats = null;
  11066. function stopLocal()
  11067. {
  11068. if(localStats)
  11069. {
  11070. localStats.stop();
  11071. localStats = null;
  11072. }
  11073. }
  11074. function stopRemote()
  11075. {
  11076. if(rtpStats)
  11077. {
  11078. rtpStats.stop();
  11079. eventEmitter.emit("statistics.stop");
  11080. rtpStats = null;
  11081. }
  11082. }
  11083. function startRemoteStats (peerconnection) {
  11084. if(rtpStats)
  11085. {
  11086. rtpStats.stop();
  11087. rtpStats = null;
  11088. }
  11089. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11090. rtpStats.start();
  11091. }
  11092. function onStreamCreated(stream)
  11093. {
  11094. if(stream.getOriginalStream().getAudioTracks().length === 0)
  11095. return;
  11096. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11097. eventEmitter);
  11098. localStats.start();
  11099. }
  11100. function onDisposeConference(onUnload) {
  11101. CallStats.sendTerminateEvent();
  11102. stopRemote();
  11103. if(onUnload) {
  11104. stopLocal();
  11105. eventEmitter.removeAllListeners();
  11106. }
  11107. }
  11108. var statistics =
  11109. {
  11110. /**
  11111. * Indicates that this audio level is for local jid.
  11112. * @type {string}
  11113. */
  11114. LOCAL_JID: 'local',
  11115. addAudioLevelListener: function(listener)
  11116. {
  11117. eventEmitter.on("statistics.audioLevel", listener);
  11118. },
  11119. removeAudioLevelListener: function(listener)
  11120. {
  11121. eventEmitter.removeListener("statistics.audioLevel", listener);
  11122. },
  11123. addConnectionStatsListener: function(listener)
  11124. {
  11125. eventEmitter.on("statistics.connectionstats", listener);
  11126. },
  11127. removeConnectionStatsListener: function(listener)
  11128. {
  11129. eventEmitter.removeListener("statistics.connectionstats", listener);
  11130. },
  11131. addRemoteStatsStopListener: function(listener)
  11132. {
  11133. eventEmitter.on("statistics.stop", listener);
  11134. },
  11135. removeRemoteStatsStopListener: function(listener)
  11136. {
  11137. eventEmitter.removeListener("statistics.stop", listener);
  11138. },
  11139. stop: function () {
  11140. stopLocal();
  11141. stopRemote();
  11142. if(eventEmitter)
  11143. {
  11144. eventEmitter.removeAllListeners();
  11145. }
  11146. },
  11147. stopRemoteStatistics: function()
  11148. {
  11149. stopRemote();
  11150. },
  11151. start: function () {
  11152. APP.RTC.addStreamListener(onStreamCreated,
  11153. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11154. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11155. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11156. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11157. startRemoteStats(event.peerconnection);
  11158. // CallStats.init(event);
  11159. });
  11160. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11161. CallStats.init(session);
  11162. })
  11163. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11164. CallStats.sendMuteEvent(mute, "audio");
  11165. });
  11166. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11167. CallStats.sendSetupFailedEvent();
  11168. })
  11169. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11170. CallStats.sendMuteEvent(mute, "video");
  11171. });
  11172. }
  11173. };
  11174. module.exports = statistics;
  11175. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes.js":101,"../../service/xmpp/XMPPEvents":108,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":109}],52:[function(require,module,exports){
  11176. var i18n = require("i18next-client");
  11177. var languages = require("../../service/translation/languages");
  11178. var Settings = require("../settings/Settings");
  11179. var DEFAULT_LANG = languages.EN;
  11180. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11181. return value.replace("__app__", interfaceConfig.APP_NAME);
  11182. });
  11183. var defaultOptions = {
  11184. detectLngQS: "lang",
  11185. useCookie: false,
  11186. fallbackLng: DEFAULT_LANG,
  11187. load: "unspecific",
  11188. resGetPath: 'lang/__ns__-__lng__.json',
  11189. ns: {
  11190. namespaces: ['main', 'languages'],
  11191. defaultNs: 'main'
  11192. },
  11193. lngWhitelist : languages.getLanguages(),
  11194. fallbackOnNull: true,
  11195. fallbackOnEmpty: true,
  11196. useDataAttrOptions: true,
  11197. defaultValueFromContent: false,
  11198. app: interfaceConfig.APP_NAME,
  11199. getAsync: false,
  11200. defaultValueFromContent: false,
  11201. customLoad: function(lng, ns, options, done) {
  11202. var resPath = "lang/__ns__-__lng__.json";
  11203. if(lng === languages.EN)
  11204. resPath = "lang/__ns__.json";
  11205. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11206. i18n.functions.ajax({
  11207. url: url,
  11208. success: function(data, status, xhr) {
  11209. i18n.functions.log('loaded: ' + url);
  11210. done(null, data);
  11211. },
  11212. error : function(xhr, status, error) {
  11213. if ((status && status == 200) ||
  11214. (xhr && xhr.status && xhr.status == 200)) {
  11215. // file loaded but invalid json, stop waste time !
  11216. i18n.functions.error('There is a typo in: ' + url);
  11217. } else if ((status && status == 404) ||
  11218. (xhr && xhr.status && xhr.status == 404)) {
  11219. i18n.functions.log('Does not exist: ' + url);
  11220. } else {
  11221. var theStatus = status ? status :
  11222. ((xhr && xhr.status) ? xhr.status : null);
  11223. i18n.functions.log(theStatus + ' when loading ' + url);
  11224. }
  11225. done(error, {});
  11226. },
  11227. dataType: "json",
  11228. async : options.getAsync
  11229. });
  11230. }
  11231. // options for caching
  11232. // useLocalStorage: true,
  11233. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11234. };
  11235. function initCompleted(t)
  11236. {
  11237. $("[data-i18n]").i18n();
  11238. }
  11239. function checkForParameter() {
  11240. var query = window.location.search.substring(1);
  11241. var vars = query.split("&");
  11242. for (var i=0;i<vars.length;i++) {
  11243. var pair = vars[i].split("=");
  11244. if(pair[0] == "lang")
  11245. {
  11246. return pair[1];
  11247. }
  11248. }
  11249. return null;
  11250. }
  11251. module.exports = {
  11252. init: function (lang) {
  11253. var options = defaultOptions;
  11254. if(!lang)
  11255. {
  11256. lang = checkForParameter();
  11257. if(!lang)
  11258. {
  11259. var settings = Settings.getSettings();
  11260. if(settings)
  11261. lang = settings.language;
  11262. if(!lang && config.defaultLanguage)
  11263. {
  11264. lang = config.defaultLanguage;
  11265. }
  11266. }
  11267. }
  11268. if(lang) {
  11269. options.lng = lang;
  11270. }
  11271. i18n.init(options, initCompleted);
  11272. },
  11273. translateString: function (key, options) {
  11274. return i18n.t(key, options);
  11275. },
  11276. setLanguage: function (lang) {
  11277. if(!lang)
  11278. lang = DEFAULT_LANG;
  11279. i18n.setLng(lang, defaultOptions, initCompleted);
  11280. },
  11281. getCurrentLanguage: function () {
  11282. return i18n.lng();
  11283. },
  11284. translateElement: function (selector) {
  11285. selector.i18n();
  11286. },
  11287. generateTranslationHTML: function (key, options) {
  11288. var str = "<span data-i18n=\"" + key + "\"";
  11289. if(options)
  11290. {
  11291. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11292. }
  11293. str += ">";
  11294. str += this.translateString(key, options);
  11295. str += "</span>";
  11296. return str;
  11297. }
  11298. };
  11299. },{"../../service/translation/languages":107,"../settings/Settings":47,"i18next-client":68}],53:[function(require,module,exports){
  11300. /* jshint -W117 */
  11301. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11302. var SDPDiffer = require("./SDPDiffer");
  11303. var SDPUtil = require("./SDPUtil");
  11304. var SDP = require("./SDP");
  11305. var async = require("async");
  11306. var transform = require("sdp-transform");
  11307. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11308. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11309. // Jingle stuff
  11310. function JingleSession(me, sid, connection, service, eventEmitter) {
  11311. this.me = me;
  11312. this.sid = sid;
  11313. this.connection = connection;
  11314. this.initiator = null;
  11315. this.responder = null;
  11316. this.isInitiator = null;
  11317. this.peerjid = null;
  11318. this.state = null;
  11319. this.localSDP = null;
  11320. this.remoteSDP = null;
  11321. this.relayedStreams = [];
  11322. this.startTime = null;
  11323. this.stopTime = null;
  11324. this.media_constraints = null;
  11325. this.pc_constraints = null;
  11326. this.ice_config = {};
  11327. this.drip_container = [];
  11328. this.service = service;
  11329. this.usetrickle = true;
  11330. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11331. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11332. this.hadstuncandidate = false;
  11333. this.hadturncandidate = false;
  11334. this.lasticecandidate = false;
  11335. this.statsinterval = null;
  11336. this.reason = null;
  11337. this.addssrc = [];
  11338. this.removessrc = [];
  11339. this.pendingop = null;
  11340. this.switchstreams = false;
  11341. this.wait = true;
  11342. this.localStreamsSSRC = null;
  11343. this.ssrcOwners = {};
  11344. this.ssrcVideoTypes = {};
  11345. this.eventEmitter = eventEmitter;
  11346. /**
  11347. * The indicator which determines whether the (local) video has been muted
  11348. * in response to a user command in contrast to an automatic decision made
  11349. * by the application logic.
  11350. */
  11351. this.videoMuteByUser = false;
  11352. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11353. // We start with the queue paused. We resume it when the signaling state is
  11354. // stable and the ice connection state is connected.
  11355. this.modifySourcesQueue.pause();
  11356. }
  11357. JingleSession.prototype.updateModifySourcesQueue = function() {
  11358. var signalingState = this.peerconnection.signalingState;
  11359. var iceConnectionState = this.peerconnection.iceConnectionState;
  11360. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11361. this.modifySourcesQueue.resume();
  11362. } else {
  11363. this.modifySourcesQueue.pause();
  11364. }
  11365. };
  11366. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11367. var self = this;
  11368. if (this.state !== null) {
  11369. console.error('attempt to initiate on session ' + this.sid +
  11370. 'in state ' + this.state);
  11371. return;
  11372. }
  11373. this.isInitiator = isInitiator;
  11374. this.state = 'pending';
  11375. this.initiator = isInitiator ? this.me : peerjid;
  11376. this.responder = !isInitiator ? this.me : peerjid;
  11377. this.peerjid = peerjid;
  11378. this.hadstuncandidate = false;
  11379. this.hadturncandidate = false;
  11380. this.lasticecandidate = false;
  11381. this.peerconnection
  11382. = new TraceablePeerConnection(
  11383. this.connection.jingle.ice_config,
  11384. this.connection.jingle.pc_constraints,
  11385. this);
  11386. this.peerconnection.onicecandidate = function (event) {
  11387. self.sendIceCandidate(event.candidate);
  11388. };
  11389. this.peerconnection.onaddstream = function (event) {
  11390. if (event.stream.id !== 'default') {
  11391. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  11392. self.remoteStreamAdded(event);
  11393. } else {
  11394. // This is a recvonly stream. Clients that implement Unified Plan,
  11395. // such as Firefox use recvonly "streams/channels/tracks" for
  11396. // receiving remote stream/tracks, as opposed to Plan B where there
  11397. // are only 3 channels: audio, video and data.
  11398. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11399. }
  11400. };
  11401. this.peerconnection.onremovestream = function (event) {
  11402. // Remove the stream from remoteStreams
  11403. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11404. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11405. };
  11406. this.peerconnection.onsignalingstatechange = function (event) {
  11407. if (!(self && self.peerconnection)) return;
  11408. self.updateModifySourcesQueue();
  11409. };
  11410. this.peerconnection.oniceconnectionstatechange = function (event) {
  11411. if (!(self && self.peerconnection)) return;
  11412. self.updateModifySourcesQueue();
  11413. switch (self.peerconnection.iceConnectionState) {
  11414. case 'connected':
  11415. this.startTime = new Date();
  11416. break;
  11417. case 'disconnected':
  11418. this.stopTime = new Date();
  11419. break;
  11420. case 'failed':
  11421. self.eventEmitter(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11422. break;
  11423. }
  11424. onIceConnectionStateChange(self.sid, self);
  11425. };
  11426. this.peerconnection.onnegotiationneeded = function (event) {
  11427. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11428. };
  11429. // add any local and relayed stream
  11430. APP.RTC.localStreams.forEach(function(stream) {
  11431. self.peerconnection.addStream(stream.getOriginalStream());
  11432. });
  11433. this.relayedStreams.forEach(function(stream) {
  11434. self.peerconnection.addStream(stream);
  11435. });
  11436. };
  11437. function onIceConnectionStateChange(sid, session) {
  11438. switch (session.peerconnection.iceConnectionState) {
  11439. case 'checking':
  11440. session.timeChecking = (new Date()).getTime();
  11441. session.firstconnect = true;
  11442. break;
  11443. case 'completed': // on caller side
  11444. case 'connected':
  11445. if (session.firstconnect) {
  11446. session.firstconnect = false;
  11447. var metadata = {};
  11448. metadata.setupTime
  11449. = (new Date()).getTime() - session.timeChecking;
  11450. session.peerconnection.getStats(function (res) {
  11451. if(res && res.result) {
  11452. res.result().forEach(function (report) {
  11453. if (report.type == 'googCandidatePair' &&
  11454. report.stat('googActiveConnection') == 'true') {
  11455. metadata.localCandidateType
  11456. = report.stat('googLocalCandidateType');
  11457. metadata.remoteCandidateType
  11458. = report.stat('googRemoteCandidateType');
  11459. // log pair as well so we can get nice pie
  11460. // charts
  11461. metadata.candidatePair
  11462. = report.stat('googLocalCandidateType') +
  11463. ';' +
  11464. report.stat('googRemoteCandidateType');
  11465. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11466. {
  11467. metadata.ipv6 = true;
  11468. }
  11469. }
  11470. });
  11471. }
  11472. });
  11473. }
  11474. break;
  11475. }
  11476. }
  11477. JingleSession.prototype.getVideoType = function () {
  11478. return APP.desktopsharing.isUsingScreenStream() ? 'screen' : 'camera';
  11479. };
  11480. JingleSession.prototype.accept = function () {
  11481. this.state = 'active';
  11482. var pranswer = this.peerconnection.localDescription;
  11483. if (!pranswer || pranswer.type != 'pranswer') {
  11484. return;
  11485. }
  11486. console.log('going from pranswer to answer');
  11487. if (this.usetrickle) {
  11488. // remove candidates already sent from session-accept
  11489. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11490. for (var i = 0; i < lines.length; i++) {
  11491. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11492. }
  11493. }
  11494. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11495. // FIXME: change any inactive to sendrecv or whatever they were originally
  11496. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11497. }
  11498. var prsdp = new SDP(pranswer.sdp);
  11499. var accept = $iq({to: this.peerjid,
  11500. type: 'set'})
  11501. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11502. action: 'session-accept',
  11503. initiator: this.initiator,
  11504. responder: this.responder,
  11505. sid: this.sid });
  11506. // FIXME why do we generate session-accept in 3 different places ?
  11507. prsdp.toJingle(
  11508. accept,
  11509. this.initiator == this.me ? 'initiator' : 'responder',
  11510. this.localStreamsSSRC,
  11511. self.getVideoType());
  11512. var sdp = this.peerconnection.localDescription.sdp;
  11513. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11514. // FIXME: change any inactive to sendrecv or whatever they were originally
  11515. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11516. }
  11517. var self = this;
  11518. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11519. function () {
  11520. //console.log('setLocalDescription success');
  11521. self.setLocalDescription();
  11522. self.connection.sendIQ(accept,
  11523. function () {
  11524. var ack = {};
  11525. ack.source = 'answer';
  11526. $(document).trigger('ack.jingle', [self.sid, ack]);
  11527. },
  11528. function (stanza) {
  11529. var error = ($(stanza).find('error').length) ? {
  11530. code: $(stanza).find('error').attr('code'),
  11531. reason: $(stanza).find('error :first')[0].tagName
  11532. }:{};
  11533. error.source = 'answer';
  11534. JingleSession.onJingleError(self.sid, error);
  11535. },
  11536. 10000);
  11537. },
  11538. function (e) {
  11539. console.error('setLocalDescription failed', e);
  11540. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11541. }
  11542. );
  11543. };
  11544. JingleSession.prototype.terminate = function (reason) {
  11545. this.state = 'ended';
  11546. this.reason = reason;
  11547. this.peerconnection.close();
  11548. if (this.statsinterval !== null) {
  11549. window.clearInterval(this.statsinterval);
  11550. this.statsinterval = null;
  11551. }
  11552. };
  11553. JingleSession.prototype.active = function () {
  11554. return this.state == 'active';
  11555. };
  11556. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11557. var self = this;
  11558. if (candidate && !this.lasticecandidate) {
  11559. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11560. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11561. if (!(ice && jcand)) {
  11562. console.error('failed to get ice && jcand');
  11563. return;
  11564. }
  11565. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11566. if (jcand.type === 'srflx') {
  11567. this.hadstuncandidate = true;
  11568. } else if (jcand.type === 'relay') {
  11569. this.hadturncandidate = true;
  11570. }
  11571. if (this.usetrickle) {
  11572. if (this.usedrip) {
  11573. if (this.drip_container.length === 0) {
  11574. // start 20ms callout
  11575. window.setTimeout(function () {
  11576. if (self.drip_container.length === 0) return;
  11577. self.sendIceCandidates(self.drip_container);
  11578. self.drip_container = [];
  11579. }, 20);
  11580. }
  11581. this.drip_container.push(candidate);
  11582. return;
  11583. } else {
  11584. self.sendIceCandidate([candidate]);
  11585. }
  11586. }
  11587. } else {
  11588. //console.log('sendIceCandidate: last candidate.');
  11589. if (!this.usetrickle) {
  11590. //console.log('should send full offer now...');
  11591. //FIXME why do we generate session-accept in 3 different places ?
  11592. var init = $iq({to: this.peerjid,
  11593. type: 'set'})
  11594. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11595. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11596. initiator: this.initiator,
  11597. sid: this.sid});
  11598. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11599. var self = this;
  11600. var sendJingle = function (ssrc) {
  11601. if(!ssrc)
  11602. ssrc = {};
  11603. self.localSDP.toJingle(
  11604. init,
  11605. self.initiator == self.me ? 'initiator' : 'responder',
  11606. ssrc,
  11607. self.getVideoType());
  11608. self.connection.sendIQ(init,
  11609. function () {
  11610. //console.log('session initiate ack');
  11611. var ack = {};
  11612. ack.source = 'offer';
  11613. $(document).trigger('ack.jingle', [self.sid, ack]);
  11614. },
  11615. function (stanza) {
  11616. self.state = 'error';
  11617. self.peerconnection.close();
  11618. var error = ($(stanza).find('error').length) ? {
  11619. code: $(stanza).find('error').attr('code'),
  11620. reason: $(stanza).find('error :first')[0].tagName,
  11621. }:{};
  11622. error.source = 'offer';
  11623. JingleSession.onJingleError(self.sid, error);
  11624. },
  11625. 10000);
  11626. }
  11627. sendJingle();
  11628. }
  11629. this.lasticecandidate = true;
  11630. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11631. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11632. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11633. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11634. }
  11635. }
  11636. };
  11637. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11638. console.log('sendIceCandidates', candidates);
  11639. var cand = $iq({to: this.peerjid, type: 'set'})
  11640. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11641. action: 'transport-info',
  11642. initiator: this.initiator,
  11643. sid: this.sid});
  11644. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11645. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11646. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11647. if (cands.length > 0) {
  11648. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11649. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11650. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11651. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11652. }).c('transport', ice);
  11653. for (var i = 0; i < cands.length; i++) {
  11654. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11655. }
  11656. // add fingerprint
  11657. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11658. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11659. tmp.required = true;
  11660. cand.c(
  11661. 'fingerprint',
  11662. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11663. .t(tmp.fingerprint);
  11664. delete tmp.fingerprint;
  11665. cand.attrs(tmp);
  11666. cand.up();
  11667. }
  11668. cand.up(); // transport
  11669. cand.up(); // content
  11670. }
  11671. }
  11672. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11673. //console.log('was this the last candidate', this.lasticecandidate);
  11674. this.connection.sendIQ(cand,
  11675. function () {
  11676. var ack = {};
  11677. ack.source = 'transportinfo';
  11678. $(document).trigger('ack.jingle', [this.sid, ack]);
  11679. },
  11680. function (stanza) {
  11681. var error = ($(stanza).find('error').length) ? {
  11682. code: $(stanza).find('error').attr('code'),
  11683. reason: $(stanza).find('error :first')[0].tagName,
  11684. }:{};
  11685. error.source = 'transportinfo';
  11686. JingleSession.onJingleError(this.sid, error);
  11687. },
  11688. 10000);
  11689. };
  11690. JingleSession.prototype.sendOffer = function () {
  11691. //console.log('sendOffer...');
  11692. var self = this;
  11693. this.peerconnection.createOffer(function (sdp) {
  11694. self.createdOffer(sdp);
  11695. },
  11696. function (e) {
  11697. console.error('createOffer failed', e);
  11698. },
  11699. this.media_constraints
  11700. );
  11701. };
  11702. // FIXME createdOffer is never used in jitsi-meet
  11703. JingleSession.prototype.createdOffer = function (sdp) {
  11704. //console.log('createdOffer', sdp);
  11705. var self = this;
  11706. this.localSDP = new SDP(sdp.sdp);
  11707. //this.localSDP.mangle();
  11708. var sendJingle = function () {
  11709. var init = $iq({to: this.peerjid,
  11710. type: 'set'})
  11711. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11712. action: 'session-initiate',
  11713. initiator: this.initiator,
  11714. sid: this.sid});
  11715. self.localSDP.toJingle(
  11716. init,
  11717. this.initiator == this.me ? 'initiator' : 'responder',
  11718. this.localStreamsSSRC,
  11719. self.getVideoType());
  11720. self.connection.sendIQ(init,
  11721. function () {
  11722. var ack = {};
  11723. ack.source = 'offer';
  11724. $(document).trigger('ack.jingle', [self.sid, ack]);
  11725. },
  11726. function (stanza) {
  11727. self.state = 'error';
  11728. self.peerconnection.close();
  11729. var error = ($(stanza).find('error').length) ? {
  11730. code: $(stanza).find('error').attr('code'),
  11731. reason: $(stanza).find('error :first')[0].tagName,
  11732. }:{};
  11733. error.source = 'offer';
  11734. JingleSession.onJingleError(self.sid, error);
  11735. },
  11736. 10000);
  11737. }
  11738. sdp.sdp = this.localSDP.raw;
  11739. this.peerconnection.setLocalDescription(sdp,
  11740. function () {
  11741. if(self.usetrickle)
  11742. {
  11743. sendJingle();
  11744. }
  11745. self.setLocalDescription();
  11746. //console.log('setLocalDescription success');
  11747. },
  11748. function (e) {
  11749. console.error('setLocalDescription failed', e);
  11750. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11751. }
  11752. );
  11753. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11754. for (var i = 0; i < cands.length; i++) {
  11755. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11756. if (cand.type == 'srflx') {
  11757. this.hadstuncandidate = true;
  11758. } else if (cand.type == 'relay') {
  11759. this.hadturncandidate = true;
  11760. }
  11761. }
  11762. };
  11763. JingleSession.prototype.readSsrcInfo = function (contents) {
  11764. var self = this;
  11765. $(contents).each(function (idx, content) {
  11766. var name = $(content).attr('name');
  11767. var mediaType = this.getAttribute('name');
  11768. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11769. ssrcs.each(function () {
  11770. var ssrc = this.getAttribute('ssrc');
  11771. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  11772. function () {
  11773. var owner = this.getAttribute('owner');
  11774. var videoType = this.getAttribute('video-type');
  11775. self.ssrcOwners[ssrc] = owner;
  11776. self.ssrcVideoTypes[ssrc] = videoType;
  11777. }
  11778. );
  11779. });
  11780. });
  11781. };
  11782. JingleSession.prototype.getSsrcOwner = function (ssrc) {
  11783. return this.ssrcOwners[ssrc];
  11784. };
  11785. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11786. //console.log('setting remote description... ', desctype);
  11787. this.remoteSDP = new SDP('');
  11788. this.remoteSDP.fromJingle(elem);
  11789. this.readSsrcInfo($(elem).find(">content"));
  11790. if (this.peerconnection.remoteDescription !== null) {
  11791. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11792. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11793. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11794. for (var i = 0; i < pranswer.media.length; i++) {
  11795. // make sure we have ice ufrag and pwd
  11796. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11797. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11798. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11799. } else {
  11800. console.warn('no ice ufrag?');
  11801. }
  11802. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11803. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11804. } else {
  11805. console.warn('no ice pwd?');
  11806. }
  11807. }
  11808. // copy over candidates
  11809. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11810. for (var j = 0; j < lines.length; j++) {
  11811. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11812. }
  11813. }
  11814. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11815. }
  11816. }
  11817. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11818. this.peerconnection.setRemoteDescription(remotedesc,
  11819. function () {
  11820. //console.log('setRemoteDescription success');
  11821. },
  11822. function (e) {
  11823. console.error('setRemoteDescription error', e);
  11824. JingleSession.onJingleFatalError(self, e);
  11825. }
  11826. );
  11827. };
  11828. JingleSession.prototype.addIceCandidate = function (elem) {
  11829. var self = this;
  11830. if (this.peerconnection.signalingState == 'closed') {
  11831. return;
  11832. }
  11833. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11834. console.log('trickle ice candidate arriving before session accept...');
  11835. // create a PRANSWER for setRemoteDescription
  11836. if (!this.remoteSDP) {
  11837. var cobbled = 'v=0\r\n' +
  11838. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11839. 's=-\r\n' +
  11840. 't=0 0\r\n';
  11841. // first, take some things from the local description
  11842. for (var i = 0; i < this.localSDP.media.length; i++) {
  11843. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11844. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11845. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11846. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11847. }
  11848. cobbled += 'a=inactive\r\n';
  11849. }
  11850. this.remoteSDP = new SDP(cobbled);
  11851. }
  11852. // then add things like ice and dtls from remote candidate
  11853. elem.each(function () {
  11854. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11855. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11856. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11857. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11858. var tmp = $(this).find('transport');
  11859. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11860. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11861. tmp = $(this).find('transport>fingerprint');
  11862. if (tmp.length) {
  11863. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11864. } else {
  11865. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11866. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11867. }
  11868. break;
  11869. }
  11870. }
  11871. }
  11872. });
  11873. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11874. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11875. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11876. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11877. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11878. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11879. }).length == this.remoteSDP.media.length;
  11880. if (iscomplete) {
  11881. console.log('setting pranswer');
  11882. try {
  11883. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11884. function() {
  11885. },
  11886. function(e) {
  11887. console.log('setRemoteDescription pranswer failed', e.toString());
  11888. });
  11889. } catch (e) {
  11890. console.error('setting pranswer failed', e);
  11891. }
  11892. } else {
  11893. //console.log('not yet setting pranswer');
  11894. }
  11895. }
  11896. // operate on each content element
  11897. elem.each(function () {
  11898. // would love to deactivate this, but firefox still requires it
  11899. var idx = -1;
  11900. var i;
  11901. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11902. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11903. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11904. idx = i;
  11905. break;
  11906. }
  11907. }
  11908. if (idx == -1) { // fall back to localdescription
  11909. for (i = 0; i < self.localSDP.media.length; i++) {
  11910. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11911. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11912. idx = i;
  11913. break;
  11914. }
  11915. }
  11916. }
  11917. var name = $(this).attr('name');
  11918. // TODO: check ice-pwd and ice-ufrag?
  11919. $(this).find('transport>candidate').each(function () {
  11920. var line, candidate;
  11921. line = SDPUtil.candidateFromJingle(this);
  11922. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11923. sdpMid: name,
  11924. candidate: line});
  11925. try {
  11926. self.peerconnection.addIceCandidate(candidate);
  11927. } catch (e) {
  11928. console.error('addIceCandidate failed', e.toString(), line);
  11929. }
  11930. });
  11931. });
  11932. };
  11933. JingleSession.prototype.sendAnswer = function (provisional) {
  11934. //console.log('createAnswer', provisional);
  11935. var self = this;
  11936. this.peerconnection.createAnswer(
  11937. function (sdp) {
  11938. self.createdAnswer(sdp, provisional);
  11939. },
  11940. function (e) {
  11941. console.error('createAnswer failed', e);
  11942. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11943. },
  11944. this.media_constraints
  11945. );
  11946. };
  11947. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11948. //console.log('createAnswer callback');
  11949. var self = this;
  11950. this.localSDP = new SDP(sdp.sdp);
  11951. //this.localSDP.mangle();
  11952. this.usepranswer = provisional === true;
  11953. if (this.usetrickle) {
  11954. if (this.usepranswer) {
  11955. sdp.type = 'pranswer';
  11956. for (var i = 0; i < this.localSDP.media.length; i++) {
  11957. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11958. }
  11959. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11960. }
  11961. }
  11962. var self = this;
  11963. var sendJingle = function (ssrcs) {
  11964. // FIXME why do we generate session-accept in 3 different places ?
  11965. var accept = $iq({to: self.peerjid,
  11966. type: 'set'})
  11967. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11968. action: 'session-accept',
  11969. initiator: self.initiator,
  11970. responder: self.responder,
  11971. sid: self.sid });
  11972. self.localSDP.toJingle(
  11973. accept,
  11974. self.initiator == self.me ? 'initiator' : 'responder',
  11975. ssrcs,
  11976. self.getVideoType());
  11977. self.connection.sendIQ(accept,
  11978. function () {
  11979. var ack = {};
  11980. ack.source = 'answer';
  11981. $(document).trigger('ack.jingle', [self.sid, ack]);
  11982. },
  11983. function (stanza) {
  11984. var error = ($(stanza).find('error').length) ? {
  11985. code: $(stanza).find('error').attr('code'),
  11986. reason: $(stanza).find('error :first')[0].tagName,
  11987. }:{};
  11988. error.source = 'answer';
  11989. JingleSession.onJingleError(self.sid, error);
  11990. },
  11991. 10000);
  11992. }
  11993. sdp.sdp = this.localSDP.raw;
  11994. this.peerconnection.setLocalDescription(sdp,
  11995. function () {
  11996. //console.log('setLocalDescription success');
  11997. if (self.usetrickle && !self.usepranswer) {
  11998. sendJingle();
  11999. }
  12000. self.setLocalDescription();
  12001. },
  12002. function (e) {
  12003. console.error('setLocalDescription failed', e);
  12004. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12005. }
  12006. );
  12007. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12008. for (var j = 0; j < cands.length; j++) {
  12009. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12010. if (cand.type == 'srflx') {
  12011. this.hadstuncandidate = true;
  12012. } else if (cand.type == 'relay') {
  12013. this.hadturncandidate = true;
  12014. }
  12015. }
  12016. };
  12017. JingleSession.prototype.sendTerminate = function (reason, text) {
  12018. var self = this,
  12019. term = $iq({to: this.peerjid,
  12020. type: 'set'})
  12021. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12022. action: 'session-terminate',
  12023. initiator: this.initiator,
  12024. sid: this.sid})
  12025. .c('reason')
  12026. .c(reason || 'success');
  12027. if (text) {
  12028. term.up().c('text').t(text);
  12029. }
  12030. this.connection.sendIQ(term,
  12031. function () {
  12032. self.peerconnection.close();
  12033. self.peerconnection = null;
  12034. self.terminate();
  12035. var ack = {};
  12036. ack.source = 'terminate';
  12037. $(document).trigger('ack.jingle', [self.sid, ack]);
  12038. },
  12039. function (stanza) {
  12040. var error = ($(stanza).find('error').length) ? {
  12041. code: $(stanza).find('error').attr('code'),
  12042. reason: $(stanza).find('error :first')[0].tagName,
  12043. }:{};
  12044. $(document).trigger('ack.jingle', [self.sid, error]);
  12045. },
  12046. 10000);
  12047. if (this.statsinterval !== null) {
  12048. window.clearInterval(this.statsinterval);
  12049. this.statsinterval = null;
  12050. }
  12051. };
  12052. JingleSession.prototype.addSource = function (elem, fromJid) {
  12053. var self = this;
  12054. // FIXME: dirty waiting
  12055. if (!this.peerconnection.localDescription)
  12056. {
  12057. console.warn("addSource - localDescription not ready yet")
  12058. setTimeout(function()
  12059. {
  12060. self.addSource(elem, fromJid);
  12061. },
  12062. 200
  12063. );
  12064. return;
  12065. }
  12066. console.log('addssrc', new Date().getTime());
  12067. console.log('ice', this.peerconnection.iceConnectionState);
  12068. this.readSsrcInfo(elem);
  12069. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12070. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12071. $(elem).each(function (idx, content) {
  12072. var name = $(content).attr('name');
  12073. var lines = '';
  12074. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12075. var semantics = this.getAttribute('semantics');
  12076. var ssrcs = $(this).find('>source').map(function () {
  12077. return this.getAttribute('ssrc');
  12078. }).get();
  12079. if (ssrcs.length != 0) {
  12080. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12081. }
  12082. });
  12083. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12084. tmp.each(function () {
  12085. var ssrc = $(this).attr('ssrc');
  12086. if(mySdp.containsSSRC(ssrc)){
  12087. /**
  12088. * This happens when multiple participants change their streams at the same time and
  12089. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12090. * addssrc are scheduled for update IQ. See
  12091. */
  12092. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12093. return;
  12094. }
  12095. $(this).find('>parameter').each(function () {
  12096. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12097. if ($(this).attr('value') && $(this).attr('value').length)
  12098. lines += ':' + $(this).attr('value');
  12099. lines += '\r\n';
  12100. });
  12101. });
  12102. sdp.media.forEach(function(media, idx) {
  12103. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12104. return;
  12105. sdp.media[idx] += lines;
  12106. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12107. self.addssrc[idx] += lines;
  12108. });
  12109. sdp.raw = sdp.session + sdp.media.join('');
  12110. });
  12111. this.modifySourcesQueue.push(function() {
  12112. // When a source is added and if this is FF, a new channel is allocated
  12113. // for receiving the added source. We need to diffuse the SSRC of this
  12114. // new recvonly channel to the rest of the peers.
  12115. console.log('modify sources done');
  12116. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12117. console.log("SDPs", mySdp, newSdp);
  12118. self.notifyMySSRCUpdate(mySdp, newSdp);
  12119. });
  12120. };
  12121. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12122. var self = this;
  12123. // FIXME: dirty waiting
  12124. if (!this.peerconnection.localDescription)
  12125. {
  12126. console.warn("removeSource - localDescription not ready yet")
  12127. setTimeout(function()
  12128. {
  12129. self.removeSource(elem, fromJid);
  12130. },
  12131. 200
  12132. );
  12133. return;
  12134. }
  12135. console.log('removessrc', new Date().getTime());
  12136. console.log('ice', this.peerconnection.iceConnectionState);
  12137. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12138. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12139. $(elem).each(function (idx, content) {
  12140. var name = $(content).attr('name');
  12141. var lines = '';
  12142. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12143. var semantics = this.getAttribute('semantics');
  12144. var ssrcs = $(this).find('>source').map(function () {
  12145. return this.getAttribute('ssrc');
  12146. }).get();
  12147. if (ssrcs.length != 0) {
  12148. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12149. }
  12150. });
  12151. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12152. tmp.each(function () {
  12153. var ssrc = $(this).attr('ssrc');
  12154. // This should never happen, but can be useful for bug detection
  12155. if(mySdp.containsSSRC(ssrc)){
  12156. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12157. return;
  12158. }
  12159. $(this).find('>parameter').each(function () {
  12160. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12161. if ($(this).attr('value') && $(this).attr('value').length)
  12162. lines += ':' + $(this).attr('value');
  12163. lines += '\r\n';
  12164. });
  12165. });
  12166. sdp.media.forEach(function(media, idx) {
  12167. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12168. return;
  12169. sdp.media[idx] += lines;
  12170. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12171. self.removessrc[idx] += lines;
  12172. });
  12173. sdp.raw = sdp.session + sdp.media.join('');
  12174. });
  12175. this.modifySourcesQueue.push(function() {
  12176. // When a source is removed and if this is FF, the recvonly channel that
  12177. // receives the remote stream is deactivated . We need to diffuse the
  12178. // recvonly SSRC removal to the rest of the peers.
  12179. console.log('modify sources done');
  12180. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12181. console.log("SDPs", mySdp, newSdp);
  12182. self.notifyMySSRCUpdate(mySdp, newSdp);
  12183. });
  12184. };
  12185. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12186. var self = this;
  12187. if (this.peerconnection.signalingState == 'closed') return;
  12188. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12189. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12190. this.setLocalDescription();
  12191. if(successCallback){
  12192. successCallback();
  12193. }
  12194. queueCallback();
  12195. return;
  12196. }
  12197. // Reset switch streams flag
  12198. this.switchstreams = false;
  12199. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12200. // add sources
  12201. this.addssrc.forEach(function(lines, idx) {
  12202. sdp.media[idx] += lines;
  12203. });
  12204. this.addssrc = [];
  12205. // remove sources
  12206. this.removessrc.forEach(function(lines, idx) {
  12207. lines = lines.split('\r\n');
  12208. lines.pop(); // remove empty last element;
  12209. lines.forEach(function(line) {
  12210. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12211. });
  12212. });
  12213. this.removessrc = [];
  12214. sdp.raw = sdp.session + sdp.media.join('');
  12215. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12216. function() {
  12217. if(self.signalingState == 'closed') {
  12218. console.error("createAnswer attempt on closed state");
  12219. queueCallback("createAnswer attempt on closed state");
  12220. return;
  12221. }
  12222. self.peerconnection.createAnswer(
  12223. function(modifiedAnswer) {
  12224. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12225. if (self.pendingop !== null) {
  12226. var sdp = new SDP(modifiedAnswer.sdp);
  12227. if (sdp.media.length > 1) {
  12228. switch(self.pendingop) {
  12229. case 'mute':
  12230. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12231. break;
  12232. case 'unmute':
  12233. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12234. break;
  12235. }
  12236. sdp.raw = sdp.session + sdp.media.join('');
  12237. modifiedAnswer.sdp = sdp.raw;
  12238. }
  12239. self.pendingop = null;
  12240. }
  12241. // FIXME: pushing down an answer while ice connection state
  12242. // is still checking is bad...
  12243. //console.log(self.peerconnection.iceConnectionState);
  12244. // trying to work around another chrome bug
  12245. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12246. self.peerconnection.setLocalDescription(modifiedAnswer,
  12247. function() {
  12248. //console.log('modified setLocalDescription ok');
  12249. self.setLocalDescription();
  12250. if(successCallback){
  12251. successCallback();
  12252. }
  12253. queueCallback();
  12254. },
  12255. function(error) {
  12256. console.error('modified setLocalDescription failed', error);
  12257. queueCallback(error);
  12258. }
  12259. );
  12260. },
  12261. function(error) {
  12262. console.error('modified answer failed', error);
  12263. queueCallback(error);
  12264. }
  12265. );
  12266. },
  12267. function(error) {
  12268. console.error('modify failed', error);
  12269. queueCallback(error);
  12270. }
  12271. );
  12272. };
  12273. /**
  12274. * Switches video streams.
  12275. * @param new_stream new stream that will be used as video of this session.
  12276. * @param oldStream old video stream of this session.
  12277. * @param success_callback callback executed after successful stream switch.
  12278. */
  12279. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12280. var self = this;
  12281. // Remember SDP to figure out added/removed SSRCs
  12282. var oldSdp = null;
  12283. if(self.peerconnection) {
  12284. if(self.peerconnection.localDescription) {
  12285. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12286. }
  12287. self.peerconnection.removeStream(oldStream, true);
  12288. if(new_stream)
  12289. self.peerconnection.addStream(new_stream);
  12290. }
  12291. // Conference is not active
  12292. if(!oldSdp || !self.peerconnection) {
  12293. success_callback();
  12294. return;
  12295. }
  12296. self.switchstreams = true;
  12297. self.modifySourcesQueue.push(function() {
  12298. console.log('modify sources done');
  12299. success_callback();
  12300. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12301. console.log("SDPs", oldSdp, newSdp);
  12302. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12303. });
  12304. };
  12305. /**
  12306. * Figures out added/removed ssrcs and send update IQs.
  12307. * @param old_sdp SDP object for old description.
  12308. * @param new_sdp SDP object for new description.
  12309. */
  12310. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12311. if (!(this.peerconnection.signalingState == 'stable' &&
  12312. this.peerconnection.iceConnectionState == 'connected')){
  12313. console.log("Too early to send updates");
  12314. return;
  12315. }
  12316. // send source-remove IQ.
  12317. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12318. var remove = $iq({to: this.peerjid, type: 'set'})
  12319. .c('jingle', {
  12320. xmlns: 'urn:xmpp:jingle:1',
  12321. action: 'source-remove',
  12322. initiator: this.initiator,
  12323. sid: this.sid
  12324. }
  12325. );
  12326. var removed = sdpDiffer.toJingle(remove);
  12327. if (removed) {
  12328. this.connection.sendIQ(remove,
  12329. function (res) {
  12330. console.info('got remove result', res);
  12331. },
  12332. function (err) {
  12333. console.error('got remove error', err);
  12334. }
  12335. );
  12336. } else {
  12337. console.log('removal not necessary');
  12338. }
  12339. // send source-add IQ.
  12340. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12341. var add = $iq({to: this.peerjid, type: 'set'})
  12342. .c('jingle', {
  12343. xmlns: 'urn:xmpp:jingle:1',
  12344. action: 'source-add',
  12345. initiator: this.initiator,
  12346. sid: this.sid
  12347. }
  12348. );
  12349. var added = sdpDiffer.toJingle(add, this.getVideoType());
  12350. if (added) {
  12351. this.connection.sendIQ(add,
  12352. function (res) {
  12353. console.info('got add result', res);
  12354. },
  12355. function (err) {
  12356. console.error('got add error', err);
  12357. }
  12358. );
  12359. } else {
  12360. console.log('addition not necessary');
  12361. }
  12362. };
  12363. /**
  12364. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12365. *
  12366. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12367. * tracks; otherwise, <tt>false</tt>
  12368. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12369. * tracks have been enabled/disabled. The function may, optionally, return
  12370. * another function which is to be invoked after the whole mute/unmute operation
  12371. * has completed successfully.
  12372. * @param options an object which specifies optional arguments such as the
  12373. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12374. * specifies whether the method was initiated in response to a user command (in
  12375. * contrast to an automatic decision made by the application logic)
  12376. */
  12377. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12378. var byUser;
  12379. if (options) {
  12380. byUser = options.byUser;
  12381. if (typeof byUser === 'undefined') {
  12382. byUser = true;
  12383. }
  12384. } else {
  12385. byUser = true;
  12386. }
  12387. // The user's command to mute the (local) video takes precedence over any
  12388. // automatic decision made by the application logic.
  12389. if (byUser) {
  12390. this.videoMuteByUser = mute;
  12391. } else if (this.videoMuteByUser) {
  12392. return;
  12393. }
  12394. this.hardMuteVideo(mute);
  12395. var self = this;
  12396. var oldSdp = null;
  12397. if(self.peerconnection) {
  12398. if(self.peerconnection.localDescription) {
  12399. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12400. }
  12401. }
  12402. this.modifySourcesQueue.push(function() {
  12403. console.log('modify sources done');
  12404. callback(mute);
  12405. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12406. console.log("SDPs", oldSdp, newSdp);
  12407. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12408. });
  12409. };
  12410. JingleSession.prototype.hardMuteVideo = function (muted) {
  12411. this.pendingop = muted ? 'mute' : 'unmute';
  12412. };
  12413. JingleSession.prototype.sendMute = function (muted, content) {
  12414. var info = $iq({to: this.peerjid,
  12415. type: 'set'})
  12416. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12417. action: 'session-info',
  12418. initiator: this.initiator,
  12419. sid: this.sid });
  12420. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12421. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12422. if (content) {
  12423. info.attrs({'name': content});
  12424. }
  12425. this.connection.send(info);
  12426. };
  12427. JingleSession.prototype.sendRinging = function () {
  12428. var info = $iq({to: this.peerjid,
  12429. type: 'set'})
  12430. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12431. action: 'session-info',
  12432. initiator: this.initiator,
  12433. sid: this.sid });
  12434. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12435. this.connection.send(info);
  12436. };
  12437. JingleSession.prototype.getStats = function (interval) {
  12438. var self = this;
  12439. var recv = {audio: 0, video: 0};
  12440. var lost = {audio: 0, video: 0};
  12441. var lastrecv = {audio: 0, video: 0};
  12442. var lastlost = {audio: 0, video: 0};
  12443. var loss = {audio: 0, video: 0};
  12444. var delta = {audio: 0, video: 0};
  12445. this.statsinterval = window.setInterval(function () {
  12446. if (self && self.peerconnection && self.peerconnection.getStats) {
  12447. self.peerconnection.getStats(function (stats) {
  12448. var results = stats.result();
  12449. // TODO: there are so much statistics you can get from this..
  12450. for (var i = 0; i < results.length; ++i) {
  12451. if (results[i].type == 'ssrc') {
  12452. var packetsrecv = results[i].stat('packetsReceived');
  12453. var packetslost = results[i].stat('packetsLost');
  12454. if (packetsrecv && packetslost) {
  12455. packetsrecv = parseInt(packetsrecv, 10);
  12456. packetslost = parseInt(packetslost, 10);
  12457. if (results[i].stat('googFrameRateReceived')) {
  12458. lastlost.video = lost.video;
  12459. lastrecv.video = recv.video;
  12460. recv.video = packetsrecv;
  12461. lost.video = packetslost;
  12462. } else {
  12463. lastlost.audio = lost.audio;
  12464. lastrecv.audio = recv.audio;
  12465. recv.audio = packetsrecv;
  12466. lost.audio = packetslost;
  12467. }
  12468. }
  12469. }
  12470. }
  12471. delta.audio = recv.audio - lastrecv.audio;
  12472. delta.video = recv.video - lastrecv.video;
  12473. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12474. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12475. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12476. });
  12477. }
  12478. }, interval || 3000);
  12479. return this.statsinterval;
  12480. };
  12481. JingleSession.onJingleError = function (session, error)
  12482. {
  12483. console.error("Jingle error", error);
  12484. }
  12485. JingleSession.onJingleFatalError = function (session, error)
  12486. {
  12487. this.service.sessionTerminated = true;
  12488. this.connection.emuc.doLeave();
  12489. APP.UI.messageHandler.showError("dialog.sorry",
  12490. "dialog.internalError");
  12491. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12492. }
  12493. JingleSession.prototype.setLocalDescription = function () {
  12494. var self = this;
  12495. var newssrcs = [];
  12496. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12497. session.media.forEach(function (media) {
  12498. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12499. // TODO(gp) maybe exclude FID streams?
  12500. media.ssrcs.forEach(function (ssrc) {
  12501. if (ssrc.attribute !== 'cname') {
  12502. return;
  12503. }
  12504. newssrcs.push({
  12505. 'ssrc': ssrc.id,
  12506. 'type': media.type
  12507. });
  12508. });
  12509. }
  12510. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12511. {
  12512. newssrcs.push({
  12513. 'ssrc': self.localStreamsSSRC[media.type],
  12514. 'type': media.type
  12515. });
  12516. }
  12517. });
  12518. console.log('new ssrcs', newssrcs);
  12519. // Bind us as local SSRCs owner
  12520. if (newssrcs.length > 0) {
  12521. for (var i = 1; i <= newssrcs.length; i ++) {
  12522. var ssrc = newssrcs[i-1].ssrc;
  12523. var myJid = self.connection.emuc.myroomjid;
  12524. self.ssrcOwners[ssrc] = myJid;
  12525. if (newssrcs[i-1].type === 'video'){
  12526. self.ssrcVideoTypes[ssrc] = self.getVideoType();
  12527. }
  12528. }
  12529. }
  12530. }
  12531. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12532. function sendKeyframe(pc) {
  12533. console.log('sendkeyframe', pc.iceConnectionState);
  12534. if (pc.iceConnectionState !== 'connected') return; // safe...
  12535. var self = this;
  12536. pc.setRemoteDescription(
  12537. pc.remoteDescription,
  12538. function () {
  12539. pc.createAnswer(
  12540. function (modifiedAnswer) {
  12541. pc.setLocalDescription(
  12542. modifiedAnswer,
  12543. function () {
  12544. // noop
  12545. },
  12546. function (error) {
  12547. console.log('triggerKeyframe setLocalDescription failed', error);
  12548. APP.UI.messageHandler.showError();
  12549. }
  12550. );
  12551. },
  12552. function (error) {
  12553. console.log('triggerKeyframe createAnswer failed', error);
  12554. APP.UI.messageHandler.showError();
  12555. }
  12556. );
  12557. },
  12558. function (error) {
  12559. console.log('triggerKeyframe setRemoteDescription failed', error);
  12560. APP.UI.messageHandler.showError();
  12561. }
  12562. );
  12563. }
  12564. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12565. var self = this;
  12566. var thessrc;
  12567. var streamId = APP.RTC.getStreamID(data.stream);
  12568. // look up an associated JID for a stream id
  12569. if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12570. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12571. var ssrclines
  12572. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12573. ssrclines = ssrclines.filter(function (line) {
  12574. // NOTE(gp) previously we filtered on the mslabel, but that property
  12575. // is not always present.
  12576. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12577. if (RTCBrowserType.isTemasysPluginUsed()) {
  12578. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12579. } else {
  12580. return ((line.indexOf('msid:' + streamId) !== -1));
  12581. }
  12582. });
  12583. if (ssrclines.length) {
  12584. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12585. if (!self.ssrcOwners[thessrc]) {
  12586. console.error("No SSRC owner known for: " + thessrc);
  12587. return;
  12588. }
  12589. data.peerjid = self.ssrcOwners[thessrc];
  12590. data.videoType = self.ssrcVideoTypes[thessrc]
  12591. console.log('associated jid', self.ssrcOwners[thessrc],
  12592. thessrc, data.videoType);
  12593. }
  12594. }
  12595. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12596. var isVideo = data.stream.getVideoTracks().length > 0;
  12597. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12598. if (isVideo &&
  12599. data.peerjid && this.peerjid === data.peerjid &&
  12600. data.stream.getVideoTracks().length === 0 &&
  12601. APP.RTC.localVideo.getTracks().length > 0) {
  12602. window.setTimeout(function () {
  12603. sendKeyframe(self.peerconnection);
  12604. }, 3000);
  12605. }
  12606. }
  12607. module.exports = JingleSession;
  12608. },{"../../service/xmpp/XMPPEvents":108,"../RTC/RTCBrowserType":8,"./SDP":54,"./SDPDiffer":55,"./SDPUtil":56,"./TraceablePeerConnection":57,"async":67,"sdp-transform":95}],54:[function(require,module,exports){
  12609. /* jshint -W117 */
  12610. var SDPUtil = require("./SDPUtil");
  12611. // SDP STUFF
  12612. function SDP(sdp) {
  12613. this.media = sdp.split('\r\nm=');
  12614. for (var i = 1; i < this.media.length; i++) {
  12615. this.media[i] = 'm=' + this.media[i];
  12616. if (i != this.media.length - 1) {
  12617. this.media[i] += '\r\n';
  12618. }
  12619. }
  12620. this.session = this.media.shift() + '\r\n';
  12621. this.raw = this.session + this.media.join('');
  12622. }
  12623. /**
  12624. * Returns map of MediaChannel mapped per channel idx.
  12625. */
  12626. SDP.prototype.getMediaSsrcMap = function() {
  12627. var self = this;
  12628. var media_ssrcs = {};
  12629. var tmp;
  12630. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12631. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12632. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12633. var media = {
  12634. mediaindex: mediaindex,
  12635. mid: mid,
  12636. ssrcs: {},
  12637. ssrcGroups: []
  12638. };
  12639. media_ssrcs[mediaindex] = media;
  12640. tmp.forEach(function (line) {
  12641. var linessrc = line.substring(7).split(' ')[0];
  12642. // allocate new ChannelSsrc
  12643. if(!media.ssrcs[linessrc]) {
  12644. media.ssrcs[linessrc] = {
  12645. ssrc: linessrc,
  12646. lines: []
  12647. };
  12648. }
  12649. media.ssrcs[linessrc].lines.push(line);
  12650. });
  12651. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12652. tmp.forEach(function(line){
  12653. var semantics = line.substr(0, idx).substr(13);
  12654. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12655. if (ssrcs.length != 0) {
  12656. media.ssrcGroups.push({
  12657. semantics: semantics,
  12658. ssrcs: ssrcs
  12659. });
  12660. }
  12661. });
  12662. }
  12663. return media_ssrcs;
  12664. };
  12665. /**
  12666. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12667. * @param ssrc the ssrc to check.
  12668. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12669. */
  12670. SDP.prototype.containsSSRC = function(ssrc) {
  12671. var medias = this.getMediaSsrcMap();
  12672. var contains = false;
  12673. Object.keys(medias).forEach(function(mediaindex){
  12674. var media = medias[mediaindex];
  12675. //console.log("Check", channel, ssrc);
  12676. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12677. contains = true;
  12678. }
  12679. });
  12680. return contains;
  12681. };
  12682. // remove iSAC and CN from SDP
  12683. SDP.prototype.mangle = function () {
  12684. var i, j, mline, lines, rtpmap, newdesc;
  12685. for (i = 0; i < this.media.length; i++) {
  12686. lines = this.media[i].split('\r\n');
  12687. lines.pop(); // remove empty last element
  12688. mline = SDPUtil.parse_mline(lines.shift());
  12689. if (mline.media != 'audio')
  12690. continue;
  12691. newdesc = '';
  12692. mline.fmt.length = 0;
  12693. for (j = 0; j < lines.length; j++) {
  12694. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12695. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12696. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12697. continue;
  12698. mline.fmt.push(rtpmap.id);
  12699. newdesc += lines[j] + '\r\n';
  12700. } else {
  12701. newdesc += lines[j] + '\r\n';
  12702. }
  12703. }
  12704. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12705. this.media[i] += newdesc;
  12706. }
  12707. this.raw = this.session + this.media.join('');
  12708. };
  12709. // remove lines matching prefix from session section
  12710. SDP.prototype.removeSessionLines = function(prefix) {
  12711. var self = this;
  12712. var lines = SDPUtil.find_lines(this.session, prefix);
  12713. lines.forEach(function(line) {
  12714. self.session = self.session.replace(line + '\r\n', '');
  12715. });
  12716. this.raw = this.session + this.media.join('');
  12717. return lines;
  12718. }
  12719. // remove lines matching prefix from a media section specified by mediaindex
  12720. // TODO: non-numeric mediaindex could match mid
  12721. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12722. var self = this;
  12723. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12724. lines.forEach(function(line) {
  12725. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12726. });
  12727. this.raw = this.session + this.media.join('');
  12728. return lines;
  12729. }
  12730. // add content's to a jingle element
  12731. SDP.prototype.toJingle = function (elem, thecreator, ssrcs, videoType) {
  12732. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12733. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12734. var self = this;
  12735. // new bundle plan
  12736. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12737. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12738. for (i = 0; i < lines.length; i++) {
  12739. tmp = lines[i].split(' ');
  12740. var semantics = tmp.shift().substr(8);
  12741. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12742. for (j = 0; j < tmp.length; j++) {
  12743. elem.c('content', {name: tmp[j]}).up();
  12744. }
  12745. elem.up();
  12746. }
  12747. }
  12748. for (i = 0; i < this.media.length; i++) {
  12749. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12750. if (!(mline.media === 'audio' ||
  12751. mline.media === 'video' ||
  12752. mline.media === 'application'))
  12753. {
  12754. continue;
  12755. }
  12756. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12757. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12758. } else {
  12759. if(ssrcs && ssrcs[mline.media])
  12760. {
  12761. ssrc = ssrcs[mline.media];
  12762. }
  12763. else
  12764. ssrc = false;
  12765. }
  12766. elem.c('content', {creator: thecreator, name: mline.media});
  12767. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12768. // prefer identifier from a=mid if present
  12769. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12770. elem.attrs({ name: mid });
  12771. }
  12772. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12773. {
  12774. elem.c('description',
  12775. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12776. media: mline.media });
  12777. if (ssrc) {
  12778. elem.attrs({ssrc: ssrc});
  12779. }
  12780. for (j = 0; j < mline.fmt.length; j++) {
  12781. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12782. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12783. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12784. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12785. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12786. for (k = 0; k < tmp.length; k++) {
  12787. elem.c('parameter', tmp[k]).up();
  12788. }
  12789. }
  12790. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12791. elem.up();
  12792. }
  12793. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12794. elem.c('encryption', {required: 1});
  12795. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12796. crypto.forEach(function(line) {
  12797. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12798. });
  12799. elem.up(); // end of encryption
  12800. }
  12801. if (ssrc) {
  12802. // new style mapping
  12803. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12804. // FIXME: group by ssrc and support multiple different ssrcs
  12805. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12806. if(ssrclines.length > 0) {
  12807. ssrclines.forEach(function (line) {
  12808. idx = line.indexOf(' ');
  12809. var linessrc = line.substr(0, idx).substr(7);
  12810. if (linessrc != ssrc) {
  12811. elem.up();
  12812. ssrc = linessrc;
  12813. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12814. }
  12815. var kv = line.substr(idx + 1);
  12816. elem.c('parameter');
  12817. if (kv.indexOf(':') == -1) {
  12818. elem.attrs({ name: kv });
  12819. } else {
  12820. var k = kv.split(':', 2)[0];
  12821. elem.attrs({ name: k });
  12822. var v = kv.split(':', 2)[1];
  12823. v = SDPUtil.filter_special_chars(v);
  12824. elem.attrs({ value: v });
  12825. }
  12826. elem.up();
  12827. });
  12828. }
  12829. else
  12830. {
  12831. elem.up();
  12832. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12833. elem.c('parameter');
  12834. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12835. elem.up();
  12836. var msid = null;
  12837. if(mline.media == "audio")
  12838. {
  12839. msid = APP.RTC.localAudio.getId();
  12840. }
  12841. else
  12842. {
  12843. msid = APP.RTC.localVideo.getId();
  12844. }
  12845. if(msid != null)
  12846. {
  12847. msid = SDPUtil.filter_special_chars(msid);
  12848. elem.c('parameter');
  12849. elem.attrs({name: "msid", value:msid});
  12850. elem.up();
  12851. elem.c('parameter');
  12852. elem.attrs({name: "mslabel", value:msid});
  12853. elem.up();
  12854. elem.c('parameter');
  12855. elem.attrs({name: "label", value:msid});
  12856. elem.up();
  12857. }
  12858. }
  12859. // Video type
  12860. if (videoType && mline.media == "video") {
  12861. elem.c('ssrc-info',
  12862. {
  12863. xmlns: 'http://jitsi.org/jitmeet',
  12864. 'video-type': videoType
  12865. }).up();
  12866. }
  12867. elem.up();
  12868. // XEP-0339 handle ssrc-group attributes
  12869. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12870. ssrc_group_lines.forEach(function(line) {
  12871. idx = line.indexOf(' ');
  12872. var semantics = line.substr(0, idx).substr(13);
  12873. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12874. if (ssrcs.length != 0) {
  12875. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12876. ssrcs.forEach(function(ssrc) {
  12877. elem.c('source', { ssrc: ssrc })
  12878. .up();
  12879. });
  12880. elem.up();
  12881. }
  12882. });
  12883. }
  12884. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12885. elem.c('rtcp-mux').up();
  12886. }
  12887. // XEP-0293 -- map a=rtcp-fb:*
  12888. this.RtcpFbToJingle(i, elem, '*');
  12889. // XEP-0294
  12890. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12891. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12892. for (j = 0; j < lines.length; j++) {
  12893. tmp = SDPUtil.parse_extmap(lines[j]);
  12894. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12895. uri: tmp.uri,
  12896. id: tmp.value });
  12897. if (tmp.hasOwnProperty('direction')) {
  12898. switch (tmp.direction) {
  12899. case 'sendonly':
  12900. elem.attrs({senders: 'responder'});
  12901. break;
  12902. case 'recvonly':
  12903. elem.attrs({senders: 'initiator'});
  12904. break;
  12905. case 'sendrecv':
  12906. elem.attrs({senders: 'both'});
  12907. break;
  12908. case 'inactive':
  12909. elem.attrs({senders: 'none'});
  12910. break;
  12911. }
  12912. }
  12913. // TODO: handle params
  12914. elem.up();
  12915. }
  12916. }
  12917. elem.up(); // end of description
  12918. }
  12919. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12920. this.TransportToJingle(i, elem);
  12921. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12922. elem.attrs({senders: 'both'});
  12923. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12924. elem.attrs({senders: 'initiator'});
  12925. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12926. elem.attrs({senders: 'responder'});
  12927. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12928. elem.attrs({senders: 'none'});
  12929. }
  12930. if (mline.port == '0') {
  12931. // estos hack to reject an m-line
  12932. elem.attrs({senders: 'rejected'});
  12933. }
  12934. elem.up(); // end of content
  12935. }
  12936. elem.up();
  12937. return elem;
  12938. };
  12939. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12940. var i = mediaindex;
  12941. var tmp;
  12942. var self = this;
  12943. elem.c('transport');
  12944. // XEP-0343 DTLS/SCTP
  12945. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12946. {
  12947. var sctpmap = SDPUtil.find_line(
  12948. this.media[i], 'a=sctpmap:', self.session);
  12949. if (sctpmap)
  12950. {
  12951. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12952. elem.c('sctpmap',
  12953. {
  12954. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12955. number: sctpAttrs[0], /* SCTP port */
  12956. protocol: sctpAttrs[1], /* protocol */
  12957. });
  12958. // Optional stream count attribute
  12959. if (sctpAttrs.length > 2)
  12960. elem.attrs({ streams: sctpAttrs[2]});
  12961. elem.up();
  12962. }
  12963. }
  12964. // XEP-0320
  12965. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12966. fingerprints.forEach(function(line) {
  12967. tmp = SDPUtil.parse_fingerprint(line);
  12968. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12969. elem.c('fingerprint').t(tmp.fingerprint);
  12970. delete tmp.fingerprint;
  12971. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12972. if (line) {
  12973. tmp.setup = line.substr(8);
  12974. }
  12975. elem.attrs(tmp);
  12976. elem.up(); // end of fingerprint
  12977. });
  12978. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12979. if (tmp) {
  12980. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12981. elem.attrs(tmp);
  12982. // XEP-0176
  12983. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12984. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12985. lines.forEach(function (line) {
  12986. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12987. });
  12988. }
  12989. }
  12990. elem.up(); // end of transport
  12991. }
  12992. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12993. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12994. lines.forEach(function (line) {
  12995. var tmp = SDPUtil.parse_rtcpfb(line);
  12996. if (tmp.type == 'trr-int') {
  12997. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12998. elem.up();
  12999. } else {
  13000. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13001. if (tmp.params.length > 0) {
  13002. elem.attrs({'subtype': tmp.params[0]});
  13003. }
  13004. elem.up();
  13005. }
  13006. });
  13007. };
  13008. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13009. var media = '';
  13010. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13011. if (tmp.length) {
  13012. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13013. if (tmp.attr('value')) {
  13014. media += tmp.attr('value');
  13015. } else {
  13016. media += '0';
  13017. }
  13018. media += '\r\n';
  13019. }
  13020. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13021. tmp.each(function () {
  13022. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13023. if ($(this).attr('subtype')) {
  13024. media += ' ' + $(this).attr('subtype');
  13025. }
  13026. media += '\r\n';
  13027. });
  13028. return media;
  13029. };
  13030. // construct an SDP from a jingle stanza
  13031. SDP.prototype.fromJingle = function (jingle) {
  13032. var self = this;
  13033. this.raw = 'v=0\r\n' +
  13034. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13035. 's=-\r\n' +
  13036. 't=0 0\r\n';
  13037. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13038. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13039. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13040. var contents = $(group).find('>content').map(function (idx, content) {
  13041. return content.getAttribute('name');
  13042. }).get();
  13043. if (contents.length > 0) {
  13044. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13045. }
  13046. });
  13047. }
  13048. this.session = this.raw;
  13049. jingle.find('>content').each(function () {
  13050. var m = self.jingle2media($(this));
  13051. self.media.push(m);
  13052. });
  13053. // reconstruct msid-semantic -- apparently not necessary
  13054. /*
  13055. var msid = SDPUtil.parse_ssrc(this.raw);
  13056. if (msid.hasOwnProperty('mslabel')) {
  13057. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13058. }
  13059. */
  13060. this.raw = this.session + this.media.join('');
  13061. };
  13062. // translate a jingle content element into an an SDP media part
  13063. SDP.prototype.jingle2media = function (content) {
  13064. var media = '',
  13065. desc = content.find('description'),
  13066. ssrc = desc.attr('ssrc'),
  13067. self = this,
  13068. tmp;
  13069. var sctp = content.find(
  13070. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13071. tmp = { media: desc.attr('media') };
  13072. tmp.port = '1';
  13073. if (content.attr('senders') == 'rejected') {
  13074. // estos hack to reject an m-line.
  13075. tmp.port = '0';
  13076. }
  13077. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13078. if (sctp.length)
  13079. tmp.proto = 'DTLS/SCTP';
  13080. else
  13081. tmp.proto = 'RTP/SAVPF';
  13082. } else {
  13083. tmp.proto = 'RTP/AVPF';
  13084. }
  13085. if (!sctp.length)
  13086. {
  13087. tmp.fmt = desc.find('payload-type').map(
  13088. function () { return this.getAttribute('id'); }).get();
  13089. media += SDPUtil.build_mline(tmp) + '\r\n';
  13090. }
  13091. else
  13092. {
  13093. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13094. media += 'a=sctpmap:' + sctp.attr('number') +
  13095. ' ' + sctp.attr('protocol');
  13096. var streamCount = sctp.attr('streams');
  13097. if (streamCount)
  13098. media += ' ' + streamCount + '\r\n';
  13099. else
  13100. media += '\r\n';
  13101. }
  13102. media += 'c=IN IP4 0.0.0.0\r\n';
  13103. if (!sctp.length)
  13104. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13105. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13106. if (tmp.length) {
  13107. if (tmp.attr('ufrag')) {
  13108. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13109. }
  13110. if (tmp.attr('pwd')) {
  13111. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13112. }
  13113. tmp.find('>fingerprint').each(function () {
  13114. // FIXME: check namespace at some point
  13115. media += 'a=fingerprint:' + this.getAttribute('hash');
  13116. media += ' ' + $(this).text();
  13117. media += '\r\n';
  13118. if (this.getAttribute('setup')) {
  13119. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13120. }
  13121. });
  13122. }
  13123. switch (content.attr('senders')) {
  13124. case 'initiator':
  13125. media += 'a=sendonly\r\n';
  13126. break;
  13127. case 'responder':
  13128. media += 'a=recvonly\r\n';
  13129. break;
  13130. case 'none':
  13131. media += 'a=inactive\r\n';
  13132. break;
  13133. case 'both':
  13134. media += 'a=sendrecv\r\n';
  13135. break;
  13136. }
  13137. media += 'a=mid:' + content.attr('name') + '\r\n';
  13138. // <description><rtcp-mux/></description>
  13139. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13140. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13141. if (desc.find('rtcp-mux').length) {
  13142. media += 'a=rtcp-mux\r\n';
  13143. }
  13144. if (desc.find('encryption').length) {
  13145. desc.find('encryption>crypto').each(function () {
  13146. media += 'a=crypto:' + this.getAttribute('tag');
  13147. media += ' ' + this.getAttribute('crypto-suite');
  13148. media += ' ' + this.getAttribute('key-params');
  13149. if (this.getAttribute('session-params')) {
  13150. media += ' ' + this.getAttribute('session-params');
  13151. }
  13152. media += '\r\n';
  13153. });
  13154. }
  13155. desc.find('payload-type').each(function () {
  13156. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13157. if ($(this).find('>parameter').length) {
  13158. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13159. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13160. media += '\r\n';
  13161. }
  13162. // xep-0293
  13163. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13164. });
  13165. // xep-0293
  13166. media += self.RtcpFbFromJingle(desc, '*');
  13167. // xep-0294
  13168. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13169. tmp.each(function () {
  13170. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13171. });
  13172. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13173. media += SDPUtil.candidateFromJingle(this);
  13174. });
  13175. // XEP-0339 handle ssrc-group attributes
  13176. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13177. var semantics = this.getAttribute('semantics');
  13178. var ssrcs = $(this).find('>source').map(function() {
  13179. return this.getAttribute('ssrc');
  13180. }).get();
  13181. if (ssrcs.length != 0) {
  13182. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13183. }
  13184. });
  13185. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13186. tmp.each(function () {
  13187. var ssrc = this.getAttribute('ssrc');
  13188. $(this).find('>parameter').each(function () {
  13189. var name = this.getAttribute('name');
  13190. var value = this.getAttribute('value');
  13191. value = SDPUtil.filter_special_chars(value);
  13192. media += 'a=ssrc:' + ssrc + ' ' + name;
  13193. if (value && value.length)
  13194. media += ':' + value;
  13195. media += '\r\n';
  13196. });
  13197. });
  13198. return media;
  13199. };
  13200. module.exports = SDP;
  13201. },{"./SDPUtil":56}],55:[function(require,module,exports){
  13202. var SDPUtil = require("./SDPUtil");
  13203. function SDPDiffer(mySDP, otherSDP) {
  13204. this.mySDP = mySDP;
  13205. this.otherSDP = otherSDP;
  13206. }
  13207. /**
  13208. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13209. * @param otherSdp the other SDP to check ssrc with.
  13210. */
  13211. SDPDiffer.prototype.getNewMedia = function() {
  13212. // this could be useful in Array.prototype.
  13213. function arrayEquals(array) {
  13214. // if the other array is a falsy value, return
  13215. if (!array)
  13216. return false;
  13217. // compare lengths - can save a lot of time
  13218. if (this.length != array.length)
  13219. return false;
  13220. for (var i = 0, l=this.length; i < l; i++) {
  13221. // Check if we have nested arrays
  13222. if (this[i] instanceof Array && array[i] instanceof Array) {
  13223. // recurse into the nested arrays
  13224. if (!this[i].equals(array[i]))
  13225. return false;
  13226. }
  13227. else if (this[i] != array[i]) {
  13228. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13229. return false;
  13230. }
  13231. }
  13232. return true;
  13233. }
  13234. var myMedias = this.mySDP.getMediaSsrcMap();
  13235. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13236. var newMedia = {};
  13237. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13238. var myMedia = myMedias[othersMediaIdx];
  13239. var othersMedia = othersMedias[othersMediaIdx];
  13240. if(!myMedia && othersMedia) {
  13241. // Add whole channel
  13242. newMedia[othersMediaIdx] = othersMedia;
  13243. return;
  13244. }
  13245. // Look for new ssrcs accross the channel
  13246. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13247. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13248. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13249. if(!newMedia[othersMediaIdx]){
  13250. newMedia[othersMediaIdx] = {
  13251. mediaindex: othersMedia.mediaindex,
  13252. mid: othersMedia.mid,
  13253. ssrcs: {},
  13254. ssrcGroups: []
  13255. };
  13256. }
  13257. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13258. }
  13259. });
  13260. // Look for new ssrc groups across the channels
  13261. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13262. // try to match the other ssrc-group with an ssrc-group of ours
  13263. var matched = false;
  13264. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13265. var mySsrcGroup = myMedia.ssrcGroups[i];
  13266. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13267. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13268. matched = true;
  13269. break;
  13270. }
  13271. }
  13272. if (!matched) {
  13273. // Allocate channel if we've found an ssrc-group that doesn't
  13274. // exist in our channel
  13275. if(!newMedia[othersMediaIdx]){
  13276. newMedia[othersMediaIdx] = {
  13277. mediaindex: othersMedia.mediaindex,
  13278. mid: othersMedia.mid,
  13279. ssrcs: {},
  13280. ssrcGroups: []
  13281. };
  13282. }
  13283. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13284. }
  13285. });
  13286. });
  13287. return newMedia;
  13288. };
  13289. /**
  13290. * Sends SSRC update IQ.
  13291. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13292. * @param sid session identifier that will be put into the IQ.
  13293. * @param initiator initiator identifier.
  13294. * @param toJid destination Jid
  13295. * @param isAdd indicates if this is remove or add operation.
  13296. */
  13297. SDPDiffer.prototype.toJingle = function(modify, videoType) {
  13298. var sdpMediaSsrcs = this.getNewMedia();
  13299. var self = this;
  13300. // FIXME: only announce video ssrcs since we mix audio and dont need
  13301. // the audio ssrcs therefore
  13302. var modified = false;
  13303. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13304. modified = true;
  13305. var media = sdpMediaSsrcs[mediaindex];
  13306. modify.c('content', {name: media.mid});
  13307. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13308. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13309. // generate sources from lines
  13310. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13311. var mediaSsrc = media.ssrcs[ssrcNum];
  13312. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13313. modify.attrs({ssrc: mediaSsrc.ssrc});
  13314. // iterate over ssrc lines
  13315. mediaSsrc.lines.forEach(function (line) {
  13316. var idx = line.indexOf(' ');
  13317. var kv = line.substr(idx + 1);
  13318. modify.c('parameter');
  13319. if (kv.indexOf(':') == -1) {
  13320. modify.attrs({ name: kv });
  13321. } else {
  13322. var nv = kv.split(':', 2);
  13323. var name = nv[0];
  13324. var value = SDPUtil.filter_special_chars(nv[1]);
  13325. modify.attrs({ name: name });
  13326. modify.attrs({ value: value });
  13327. }
  13328. modify.up(); // end of parameter
  13329. });
  13330. // indicate video type
  13331. if (videoType && media.mid == 'video') {
  13332. modify.c('ssrc-info',
  13333. {
  13334. xmlns: 'http://jitsi.org/jitmeet',
  13335. 'video-type': videoType
  13336. })
  13337. .up();
  13338. }
  13339. modify.up(); // end of source
  13340. });
  13341. // generate source groups from lines
  13342. media.ssrcGroups.forEach(function(ssrcGroup) {
  13343. if (ssrcGroup.ssrcs.length != 0) {
  13344. modify.c('ssrc-group', {
  13345. semantics: ssrcGroup.semantics,
  13346. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13347. });
  13348. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13349. modify.c('source', { ssrc: ssrc })
  13350. .up(); // end of source
  13351. });
  13352. modify.up(); // end of ssrc-group
  13353. }
  13354. });
  13355. modify.up(); // end of description
  13356. modify.up(); // end of content
  13357. });
  13358. return modified;
  13359. };
  13360. module.exports = SDPDiffer;
  13361. },{"./SDPUtil":56}],56:[function(require,module,exports){
  13362. SDPUtil = {
  13363. filter_special_chars: function (text) {
  13364. return text.replace(/[\\\/\{,\}\+]/g, "");
  13365. },
  13366. iceparams: function (mediadesc, sessiondesc) {
  13367. var data = null;
  13368. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13369. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13370. data = {
  13371. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13372. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13373. };
  13374. }
  13375. return data;
  13376. },
  13377. parse_iceufrag: function (line) {
  13378. return line.substring(12);
  13379. },
  13380. build_iceufrag: function (frag) {
  13381. return 'a=ice-ufrag:' + frag;
  13382. },
  13383. parse_icepwd: function (line) {
  13384. return line.substring(10);
  13385. },
  13386. build_icepwd: function (pwd) {
  13387. return 'a=ice-pwd:' + pwd;
  13388. },
  13389. parse_mid: function (line) {
  13390. return line.substring(6);
  13391. },
  13392. parse_mline: function (line) {
  13393. var parts = line.substring(2).split(' '),
  13394. data = {};
  13395. data.media = parts.shift();
  13396. data.port = parts.shift();
  13397. data.proto = parts.shift();
  13398. if (parts[parts.length - 1] === '') { // trailing whitespace
  13399. parts.pop();
  13400. }
  13401. data.fmt = parts;
  13402. return data;
  13403. },
  13404. build_mline: function (mline) {
  13405. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13406. },
  13407. parse_rtpmap: function (line) {
  13408. var parts = line.substring(9).split(' '),
  13409. data = {};
  13410. data.id = parts.shift();
  13411. parts = parts[0].split('/');
  13412. data.name = parts.shift();
  13413. data.clockrate = parts.shift();
  13414. data.channels = parts.length ? parts.shift() : '1';
  13415. return data;
  13416. },
  13417. /**
  13418. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13419. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13420. * @returns [SCTP port number, protocol, streams]
  13421. */
  13422. parse_sctpmap: function (line)
  13423. {
  13424. var parts = line.substring(10).split(' ');
  13425. var sctpPort = parts[0];
  13426. var protocol = parts[1];
  13427. // Stream count is optional
  13428. var streamCount = parts.length > 2 ? parts[2] : null;
  13429. return [sctpPort, protocol, streamCount];// SCTP port
  13430. },
  13431. build_rtpmap: function (el) {
  13432. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13433. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13434. line += '/' + el.getAttribute('channels');
  13435. }
  13436. return line;
  13437. },
  13438. parse_crypto: function (line) {
  13439. var parts = line.substring(9).split(' '),
  13440. data = {};
  13441. data.tag = parts.shift();
  13442. data['crypto-suite'] = parts.shift();
  13443. data['key-params'] = parts.shift();
  13444. if (parts.length) {
  13445. data['session-params'] = parts.join(' ');
  13446. }
  13447. return data;
  13448. },
  13449. parse_fingerprint: function (line) { // RFC 4572
  13450. var parts = line.substring(14).split(' '),
  13451. data = {};
  13452. data.hash = parts.shift();
  13453. data.fingerprint = parts.shift();
  13454. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13455. return data;
  13456. },
  13457. parse_fmtp: function (line) {
  13458. var parts = line.split(' '),
  13459. i, key, value,
  13460. data = [];
  13461. parts.shift();
  13462. parts = parts.join(' ').split(';');
  13463. for (i = 0; i < parts.length; i++) {
  13464. key = parts[i].split('=')[0];
  13465. while (key.length && key[0] == ' ') {
  13466. key = key.substring(1);
  13467. }
  13468. value = parts[i].split('=')[1];
  13469. if (key && value) {
  13470. data.push({name: key, value: value});
  13471. } else if (key) {
  13472. // rfc 4733 (DTMF) style stuff
  13473. data.push({name: '', value: key});
  13474. }
  13475. }
  13476. return data;
  13477. },
  13478. parse_icecandidate: function (line) {
  13479. var candidate = {},
  13480. elems = line.split(' ');
  13481. candidate.foundation = elems[0].substring(12);
  13482. candidate.component = elems[1];
  13483. candidate.protocol = elems[2].toLowerCase();
  13484. candidate.priority = elems[3];
  13485. candidate.ip = elems[4];
  13486. candidate.port = elems[5];
  13487. // elems[6] => "typ"
  13488. candidate.type = elems[7];
  13489. candidate.generation = 0; // default value, may be overwritten below
  13490. for (var i = 8; i < elems.length; i += 2) {
  13491. switch (elems[i]) {
  13492. case 'raddr':
  13493. candidate['rel-addr'] = elems[i + 1];
  13494. break;
  13495. case 'rport':
  13496. candidate['rel-port'] = elems[i + 1];
  13497. break;
  13498. case 'generation':
  13499. candidate.generation = elems[i + 1];
  13500. break;
  13501. case 'tcptype':
  13502. candidate.tcptype = elems[i + 1];
  13503. break;
  13504. default: // TODO
  13505. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13506. }
  13507. }
  13508. candidate.network = '1';
  13509. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13510. return candidate;
  13511. },
  13512. build_icecandidate: function (cand) {
  13513. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13514. line += ' ';
  13515. switch (cand.type) {
  13516. case 'srflx':
  13517. case 'prflx':
  13518. case 'relay':
  13519. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13520. line += 'raddr';
  13521. line += ' ';
  13522. line += cand['rel-addr'];
  13523. line += ' ';
  13524. line += 'rport';
  13525. line += ' ';
  13526. line += cand['rel-port'];
  13527. line += ' ';
  13528. }
  13529. break;
  13530. }
  13531. if (cand.hasOwnAttribute('tcptype')) {
  13532. line += 'tcptype';
  13533. line += ' ';
  13534. line += cand.tcptype;
  13535. line += ' ';
  13536. }
  13537. line += 'generation';
  13538. line += ' ';
  13539. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13540. return line;
  13541. },
  13542. parse_ssrc: function (desc) {
  13543. // proprietary mapping of a=ssrc lines
  13544. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13545. // and parse according to that
  13546. var lines = desc.split('\r\n'),
  13547. data = {};
  13548. for (var i = 0; i < lines.length; i++) {
  13549. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13550. var idx = lines[i].indexOf(' ');
  13551. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13552. }
  13553. }
  13554. return data;
  13555. },
  13556. parse_rtcpfb: function (line) {
  13557. var parts = line.substr(10).split(' ');
  13558. var data = {};
  13559. data.pt = parts.shift();
  13560. data.type = parts.shift();
  13561. data.params = parts;
  13562. return data;
  13563. },
  13564. parse_extmap: function (line) {
  13565. var parts = line.substr(9).split(' ');
  13566. var data = {};
  13567. data.value = parts.shift();
  13568. if (data.value.indexOf('/') != -1) {
  13569. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13570. data.value = data.value.substr(0, data.value.indexOf('/'));
  13571. } else {
  13572. data.direction = 'both';
  13573. }
  13574. data.uri = parts.shift();
  13575. data.params = parts;
  13576. return data;
  13577. },
  13578. find_line: function (haystack, needle, sessionpart) {
  13579. var lines = haystack.split('\r\n');
  13580. for (var i = 0; i < lines.length; i++) {
  13581. if (lines[i].substring(0, needle.length) == needle) {
  13582. return lines[i];
  13583. }
  13584. }
  13585. if (!sessionpart) {
  13586. return false;
  13587. }
  13588. // search session part
  13589. lines = sessionpart.split('\r\n');
  13590. for (var j = 0; j < lines.length; j++) {
  13591. if (lines[j].substring(0, needle.length) == needle) {
  13592. return lines[j];
  13593. }
  13594. }
  13595. return false;
  13596. },
  13597. find_lines: function (haystack, needle, sessionpart) {
  13598. var lines = haystack.split('\r\n'),
  13599. needles = [];
  13600. for (var i = 0; i < lines.length; i++) {
  13601. if (lines[i].substring(0, needle.length) == needle)
  13602. needles.push(lines[i]);
  13603. }
  13604. if (needles.length || !sessionpart) {
  13605. return needles;
  13606. }
  13607. // search session part
  13608. lines = sessionpart.split('\r\n');
  13609. for (var j = 0; j < lines.length; j++) {
  13610. if (lines[j].substring(0, needle.length) == needle) {
  13611. needles.push(lines[j]);
  13612. }
  13613. }
  13614. return needles;
  13615. },
  13616. candidateToJingle: function (line) {
  13617. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13618. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13619. if (line.indexOf('candidate:') === 0) {
  13620. line = 'a=' + line;
  13621. } else if (line.substring(0, 12) != 'a=candidate:') {
  13622. console.log('parseCandidate called with a line that is not a candidate line');
  13623. console.log(line);
  13624. return null;
  13625. }
  13626. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13627. line = line.substring(0, line.length - 2);
  13628. var candidate = {},
  13629. elems = line.split(' '),
  13630. i;
  13631. if (elems[6] != 'typ') {
  13632. console.log('did not find typ in the right place');
  13633. console.log(line);
  13634. return null;
  13635. }
  13636. candidate.foundation = elems[0].substring(12);
  13637. candidate.component = elems[1];
  13638. candidate.protocol = elems[2].toLowerCase();
  13639. candidate.priority = elems[3];
  13640. candidate.ip = elems[4];
  13641. candidate.port = elems[5];
  13642. // elems[6] => "typ"
  13643. candidate.type = elems[7];
  13644. candidate.generation = '0'; // default, may be overwritten below
  13645. for (i = 8; i < elems.length; i += 2) {
  13646. switch (elems[i]) {
  13647. case 'raddr':
  13648. candidate['rel-addr'] = elems[i + 1];
  13649. break;
  13650. case 'rport':
  13651. candidate['rel-port'] = elems[i + 1];
  13652. break;
  13653. case 'generation':
  13654. candidate.generation = elems[i + 1];
  13655. break;
  13656. case 'tcptype':
  13657. candidate.tcptype = elems[i + 1];
  13658. break;
  13659. default: // TODO
  13660. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13661. }
  13662. }
  13663. candidate.network = '1';
  13664. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13665. return candidate;
  13666. },
  13667. candidateFromJingle: function (cand) {
  13668. var line = 'a=candidate:';
  13669. line += cand.getAttribute('foundation');
  13670. line += ' ';
  13671. line += cand.getAttribute('component');
  13672. line += ' ';
  13673. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13674. line += ' ';
  13675. line += cand.getAttribute('priority');
  13676. line += ' ';
  13677. line += cand.getAttribute('ip');
  13678. line += ' ';
  13679. line += cand.getAttribute('port');
  13680. line += ' ';
  13681. line += 'typ';
  13682. line += ' ' + cand.getAttribute('type');
  13683. line += ' ';
  13684. switch (cand.getAttribute('type')) {
  13685. case 'srflx':
  13686. case 'prflx':
  13687. case 'relay':
  13688. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13689. line += 'raddr';
  13690. line += ' ';
  13691. line += cand.getAttribute('rel-addr');
  13692. line += ' ';
  13693. line += 'rport';
  13694. line += ' ';
  13695. line += cand.getAttribute('rel-port');
  13696. line += ' ';
  13697. }
  13698. break;
  13699. }
  13700. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13701. line += 'tcptype';
  13702. line += ' ';
  13703. line += cand.getAttribute('tcptype');
  13704. line += ' ';
  13705. }
  13706. line += 'generation';
  13707. line += ' ';
  13708. line += cand.getAttribute('generation') || '0';
  13709. return line + '\r\n';
  13710. }
  13711. };
  13712. module.exports = SDPUtil;
  13713. },{}],57:[function(require,module,exports){
  13714. var RTC = require('../RTC/RTC');
  13715. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  13716. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13717. function TraceablePeerConnection(ice_config, constraints, session) {
  13718. var self = this;
  13719. var RTCPeerconnectionType = null;
  13720. if (RTCBrowserType.isFirefox()) {
  13721. RTCPeerconnectionType = mozRTCPeerConnection;
  13722. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  13723. RTCPeerconnectionType = RTCPeerConnection;
  13724. } else {
  13725. RTCPeerconnectionType = webkitRTCPeerConnection;
  13726. }
  13727. this.peerconnection = new RTCPeerconnectionType(ice_config, constraints);
  13728. this.updateLog = [];
  13729. this.stats = {};
  13730. this.statsinterval = null;
  13731. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13732. var Interop = require('sdp-interop').Interop;
  13733. this.interop = new Interop();
  13734. var Simulcast = require('sdp-simulcast');
  13735. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  13736. // override as desired
  13737. this.trace = function (what, info) {
  13738. /*console.warn('WTRACE', what, info);
  13739. if (info && RTCBrowserType.isIExplorer()) {
  13740. if (info.length > 1024) {
  13741. console.warn('WTRACE', what, info.substr(1024));
  13742. }
  13743. if (info.length > 2048) {
  13744. console.warn('WTRACE', what, info.substr(2048));
  13745. }
  13746. }*/
  13747. self.updateLog.push({
  13748. time: new Date(),
  13749. type: what,
  13750. value: info || ""
  13751. });
  13752. };
  13753. this.onicecandidate = null;
  13754. this.peerconnection.onicecandidate = function (event) {
  13755. // FIXME: this causes stack overflow with Temasys Plugin
  13756. if (!RTCBrowserType.isTemasysPluginUsed())
  13757. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13758. if (self.onicecandidate !== null) {
  13759. self.onicecandidate(event);
  13760. }
  13761. };
  13762. this.onaddstream = null;
  13763. this.peerconnection.onaddstream = function (event) {
  13764. self.trace('onaddstream', event.stream.id);
  13765. if (self.onaddstream !== null) {
  13766. self.onaddstream(event);
  13767. }
  13768. };
  13769. this.onremovestream = null;
  13770. this.peerconnection.onremovestream = function (event) {
  13771. self.trace('onremovestream', event.stream.id);
  13772. if (self.onremovestream !== null) {
  13773. self.onremovestream(event);
  13774. }
  13775. };
  13776. this.onsignalingstatechange = null;
  13777. this.peerconnection.onsignalingstatechange = function (event) {
  13778. self.trace('onsignalingstatechange', self.signalingState);
  13779. if (self.onsignalingstatechange !== null) {
  13780. self.onsignalingstatechange(event);
  13781. }
  13782. };
  13783. this.oniceconnectionstatechange = null;
  13784. this.peerconnection.oniceconnectionstatechange = function (event) {
  13785. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13786. if (self.oniceconnectionstatechange !== null) {
  13787. self.oniceconnectionstatechange(event);
  13788. }
  13789. };
  13790. this.onnegotiationneeded = null;
  13791. this.peerconnection.onnegotiationneeded = function (event) {
  13792. self.trace('onnegotiationneeded');
  13793. if (self.onnegotiationneeded !== null) {
  13794. self.onnegotiationneeded(event);
  13795. }
  13796. };
  13797. self.ondatachannel = null;
  13798. this.peerconnection.ondatachannel = function (event) {
  13799. self.trace('ondatachannel', event);
  13800. if (self.ondatachannel !== null) {
  13801. self.ondatachannel(event);
  13802. }
  13803. };
  13804. if (!navigator.mozGetUserMedia && this.maxstats) {
  13805. this.statsinterval = window.setInterval(function() {
  13806. self.peerconnection.getStats(function(stats) {
  13807. var results = stats.result();
  13808. for (var i = 0; i < results.length; ++i) {
  13809. //console.log(results[i].type, results[i].id, results[i].names())
  13810. var now = new Date();
  13811. results[i].names().forEach(function (name) {
  13812. var id = results[i].id + '-' + name;
  13813. if (!self.stats[id]) {
  13814. self.stats[id] = {
  13815. startTime: now,
  13816. endTime: now,
  13817. values: [],
  13818. times: []
  13819. };
  13820. }
  13821. self.stats[id].values.push(results[i].stat(name));
  13822. self.stats[id].times.push(now.getTime());
  13823. if (self.stats[id].values.length > self.maxstats) {
  13824. self.stats[id].values.shift();
  13825. self.stats[id].times.shift();
  13826. }
  13827. self.stats[id].endTime = now;
  13828. });
  13829. }
  13830. });
  13831. }, 1000);
  13832. }
  13833. };
  13834. dumpSDP = function(description) {
  13835. if (typeof description === 'undefined' || description == null) {
  13836. return '';
  13837. }
  13838. return 'type: ' + description.type + '\r\n' + description.sdp;
  13839. };
  13840. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  13841. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  13842. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  13843. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  13844. var desc = this.peerconnection.localDescription;
  13845. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  13846. // if we're running on FF, transform to Plan B first.
  13847. if (navigator.mozGetUserMedia) {
  13848. desc = this.interop.toPlanB(desc);
  13849. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  13850. }
  13851. return desc;
  13852. });
  13853. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13854. var desc = this.peerconnection.remoteDescription;
  13855. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  13856. // if we're running on FF, transform to Plan B first.
  13857. if (navigator.mozGetUserMedia) {
  13858. desc = this.interop.toPlanB(desc);
  13859. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13860. }
  13861. return desc;
  13862. });
  13863. }
  13864. TraceablePeerConnection.prototype.addStream = function (stream) {
  13865. this.trace('addStream', stream.id);
  13866. try
  13867. {
  13868. this.peerconnection.addStream(stream);
  13869. }
  13870. catch (e)
  13871. {
  13872. console.error(e);
  13873. return;
  13874. }
  13875. };
  13876. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13877. this.trace('removeStream', stream.id);
  13878. if(stopStreams) {
  13879. stream.getAudioTracks().forEach(function (track) {
  13880. // stop() not supported with IE
  13881. if (track.stop) {
  13882. track.stop();
  13883. }
  13884. });
  13885. stream.getVideoTracks().forEach(function (track) {
  13886. // stop() not supported with IE
  13887. if (track.stop) {
  13888. track.stop();
  13889. }
  13890. });
  13891. if (stream.stop) {
  13892. stream.stop();
  13893. }
  13894. }
  13895. try {
  13896. // FF doesn't support this yet.
  13897. if (this.peerconnection.removeStream)
  13898. this.peerconnection.removeStream(stream);
  13899. } catch (e) {
  13900. console.error(e);
  13901. }
  13902. };
  13903. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13904. this.trace('createDataChannel', label, opts);
  13905. return this.peerconnection.createDataChannel(label, opts);
  13906. };
  13907. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13908. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  13909. // if we're running on FF, transform to Plan A first.
  13910. if (navigator.mozGetUserMedia) {
  13911. description = this.interop.toUnifiedPlan(description);
  13912. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13913. }
  13914. var self = this;
  13915. this.peerconnection.setLocalDescription(description,
  13916. function () {
  13917. self.trace('setLocalDescriptionOnSuccess');
  13918. successCallback();
  13919. },
  13920. function (err) {
  13921. self.trace('setLocalDescriptionOnFailure', err);
  13922. failureCallback(err);
  13923. }
  13924. );
  13925. /*
  13926. if (this.statsinterval === null && this.maxstats > 0) {
  13927. // start gathering stats
  13928. }
  13929. */
  13930. };
  13931. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13932. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  13933. // TODO the focus should squeze or explode the remote simulcast
  13934. description = this.simulcast.mungeRemoteDescription(description);
  13935. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  13936. // if we're running on FF, transform to Plan A first.
  13937. if (navigator.mozGetUserMedia) {
  13938. description = this.interop.toUnifiedPlan(description);
  13939. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13940. }
  13941. var self = this;
  13942. this.peerconnection.setRemoteDescription(description,
  13943. function () {
  13944. self.trace('setRemoteDescriptionOnSuccess');
  13945. successCallback();
  13946. },
  13947. function (err) {
  13948. self.trace('setRemoteDescriptionOnFailure', err);
  13949. failureCallback(err);
  13950. }
  13951. );
  13952. /*
  13953. if (this.statsinterval === null && this.maxstats > 0) {
  13954. // start gathering stats
  13955. }
  13956. */
  13957. };
  13958. TraceablePeerConnection.prototype.close = function () {
  13959. this.trace('stop');
  13960. if (this.statsinterval !== null) {
  13961. window.clearInterval(this.statsinterval);
  13962. this.statsinterval = null;
  13963. }
  13964. this.peerconnection.close();
  13965. };
  13966. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13967. var self = this;
  13968. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13969. this.peerconnection.createOffer(
  13970. function (offer) {
  13971. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  13972. // if we're running on FF, transform to Plan B first.
  13973. // NOTE this is not tested because in meet the focus generates the
  13974. // offer.
  13975. if (navigator.mozGetUserMedia) {
  13976. offer = self.interop.toPlanB(offer);
  13977. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13978. }
  13979. if (config.enableSimulcast && self.simulcast.isSupported()) {
  13980. offer = self.simulcast.mungeLocalDescription(offer);
  13981. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  13982. }
  13983. successCallback(offer);
  13984. },
  13985. function(err) {
  13986. self.trace('createOfferOnFailure', err);
  13987. failureCallback(err);
  13988. },
  13989. constraints
  13990. );
  13991. };
  13992. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13993. var self = this;
  13994. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13995. this.peerconnection.createAnswer(
  13996. function (answer) {
  13997. self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
  13998. // if we're running on FF, transform to Plan A first.
  13999. if (navigator.mozGetUserMedia) {
  14000. answer = self.interop.toPlanB(answer);
  14001. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  14002. }
  14003. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14004. answer = self.simulcast.mungeLocalDescription(answer);
  14005. self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
  14006. }
  14007. successCallback(answer);
  14008. },
  14009. function(err) {
  14010. self.trace('createAnswerOnFailure', err);
  14011. failureCallback(err);
  14012. },
  14013. constraints
  14014. );
  14015. };
  14016. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  14017. var self = this;
  14018. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14019. this.peerconnection.addIceCandidate(candidate);
  14020. /* maybe later
  14021. this.peerconnection.addIceCandidate(candidate,
  14022. function () {
  14023. self.trace('addIceCandidateOnSuccess');
  14024. successCallback();
  14025. },
  14026. function (err) {
  14027. self.trace('addIceCandidateOnFailure', err);
  14028. failureCallback(err);
  14029. }
  14030. );
  14031. */
  14032. };
  14033. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14034. if (navigator.mozGetUserMedia) {
  14035. // ignore for now...
  14036. if(!errback)
  14037. errback = function () {
  14038. }
  14039. this.peerconnection.getStats(null,callback,errback);
  14040. } else {
  14041. this.peerconnection.getStats(callback);
  14042. }
  14043. };
  14044. module.exports = TraceablePeerConnection;
  14045. },{"../../service/xmpp/XMPPEvents":108,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"sdp-interop":89,"sdp-simulcast":92}],58:[function(require,module,exports){
  14046. /* global $, $iq, APP, config, connection, UI, messageHandler,
  14047. roomName, sessionTerminated, Strophe, Util */
  14048. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14049. var Settings = require("../settings/Settings");
  14050. var AuthenticationEvents
  14051. = require("../../service/authentication/AuthenticationEvents");
  14052. /**
  14053. * Contains logic responsible for enabling/disabling functionality available
  14054. * only to moderator users.
  14055. */
  14056. var connection = null;
  14057. var focusUserJid;
  14058. function createExpBackoffTimer(step) {
  14059. var count = 1;
  14060. return function (reset) {
  14061. // Reset call
  14062. if (reset) {
  14063. count = 1;
  14064. return;
  14065. }
  14066. // Calculate next timeout
  14067. var timeout = Math.pow(2, count - 1);
  14068. count += 1;
  14069. return timeout * step;
  14070. };
  14071. }
  14072. var getNextTimeout = createExpBackoffTimer(1000);
  14073. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14074. // External authentication stuff
  14075. var externalAuthEnabled = false;
  14076. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14077. // it will be enabled automatically if focus detects the component through
  14078. // service discovery.
  14079. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14080. var eventEmitter = null;
  14081. var Moderator = {
  14082. isModerator: function () {
  14083. return connection && connection.emuc.isModerator();
  14084. },
  14085. isPeerModerator: function (peerJid) {
  14086. return connection &&
  14087. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14088. },
  14089. isExternalAuthEnabled: function () {
  14090. return externalAuthEnabled;
  14091. },
  14092. isSipGatewayEnabled: function () {
  14093. return sipGatewayEnabled;
  14094. },
  14095. setConnection: function (con) {
  14096. connection = con;
  14097. },
  14098. init: function (xmpp, emitter) {
  14099. this.xmppService = xmpp;
  14100. eventEmitter = emitter;
  14101. // Message listener that talks to POPUP window
  14102. function listener(event) {
  14103. if (event.data && event.data.sessionId) {
  14104. if (event.origin !== window.location.origin) {
  14105. console.warn(
  14106. "Ignoring sessionId from different origin: " + event.origin);
  14107. return;
  14108. }
  14109. localStorage.setItem('sessionId', event.data.sessionId);
  14110. // After popup is closed we will authenticate
  14111. }
  14112. }
  14113. // Register
  14114. if (window.addEventListener) {
  14115. window.addEventListener("message", listener, false);
  14116. } else {
  14117. window.attachEvent("onmessage", listener);
  14118. }
  14119. },
  14120. onMucMemberLeft: function (jid) {
  14121. console.info("Someone left is it focus ? " + jid);
  14122. var resource = Strophe.getResourceFromJid(jid);
  14123. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14124. console.info(
  14125. "Focus has left the room - leaving conference");
  14126. //hangUp();
  14127. // We'd rather reload to have everything re-initialized
  14128. // FIXME: show some message before reload
  14129. location.reload();
  14130. }
  14131. },
  14132. setFocusUserJid: function (focusJid) {
  14133. if (!focusUserJid) {
  14134. focusUserJid = focusJid;
  14135. console.info("Focus jid set to: " + focusUserJid);
  14136. }
  14137. },
  14138. getFocusUserJid: function () {
  14139. return focusUserJid;
  14140. },
  14141. getFocusComponent: function () {
  14142. // Get focus component address
  14143. var focusComponent = config.hosts.focus;
  14144. // If not specified use default: 'focus.domain'
  14145. if (!focusComponent) {
  14146. focusComponent = 'focus.' + config.hosts.domain;
  14147. }
  14148. return focusComponent;
  14149. },
  14150. createConferenceIq: function (roomName) {
  14151. // Generate create conference IQ
  14152. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14153. // Session Id used for authentication
  14154. var sessionId = localStorage.getItem('sessionId');
  14155. var machineUID = Settings.getSettings().uid;
  14156. console.info(
  14157. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14158. elem.c('conference', {
  14159. xmlns: 'http://jitsi.org/protocol/focus',
  14160. room: roomName,
  14161. 'machine-uid': machineUID
  14162. });
  14163. if (sessionId) {
  14164. elem.attrs({ 'session-id': sessionId});
  14165. }
  14166. if (config.hosts.bridge !== undefined) {
  14167. elem.c(
  14168. 'property',
  14169. { name: 'bridge', value: config.hosts.bridge})
  14170. .up();
  14171. }
  14172. // Tell the focus we have Jigasi configured
  14173. if (config.hosts.call_control !== undefined) {
  14174. elem.c(
  14175. 'property',
  14176. { name: 'call_control', value: config.hosts.call_control})
  14177. .up();
  14178. }
  14179. if (config.channelLastN !== undefined) {
  14180. elem.c(
  14181. 'property',
  14182. { name: 'channelLastN', value: config.channelLastN})
  14183. .up();
  14184. }
  14185. if (config.adaptiveLastN !== undefined) {
  14186. elem.c(
  14187. 'property',
  14188. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14189. .up();
  14190. }
  14191. if (config.adaptiveSimulcast !== undefined) {
  14192. elem.c(
  14193. 'property',
  14194. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14195. .up();
  14196. }
  14197. if (config.openSctp !== undefined) {
  14198. elem.c(
  14199. 'property',
  14200. { name: 'openSctp', value: config.openSctp})
  14201. .up();
  14202. }
  14203. if(config.startAudioMuted !== undefined)
  14204. {
  14205. elem.c(
  14206. 'property',
  14207. { name: 'startAudioMuted', value: config.startAudioMuted})
  14208. .up();
  14209. }
  14210. if(config.startVideoMuted !== undefined)
  14211. {
  14212. elem.c(
  14213. 'property',
  14214. { name: 'startVideoMuted', value: config.startVideoMuted})
  14215. .up();
  14216. }
  14217. elem.c(
  14218. 'property',
  14219. { name: 'simulcastMode', value: 'rewriting'})
  14220. .up();
  14221. elem.up();
  14222. return elem;
  14223. },
  14224. parseSessionId: function (resultIq) {
  14225. var sessionId = $(resultIq).find('conference').attr('session-id');
  14226. if (sessionId) {
  14227. console.info('Received sessionId: ' + sessionId);
  14228. localStorage.setItem('sessionId', sessionId);
  14229. }
  14230. },
  14231. parseConfigOptions: function (resultIq) {
  14232. Moderator.setFocusUserJid(
  14233. $(resultIq).find('conference').attr('focusjid'));
  14234. var authenticationEnabled
  14235. = $(resultIq).find(
  14236. '>conference>property' +
  14237. '[name=\'authentication\'][value=\'true\']').length > 0;
  14238. console.info("Authentication enabled: " + authenticationEnabled);
  14239. externalAuthEnabled
  14240. = $(resultIq).find(
  14241. '>conference>property' +
  14242. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14243. console.info('External authentication enabled: ' + externalAuthEnabled);
  14244. if (!externalAuthEnabled) {
  14245. // We expect to receive sessionId in 'internal' authentication mode
  14246. Moderator.parseSessionId(resultIq);
  14247. }
  14248. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14249. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14250. authenticationEnabled, authIdentity);
  14251. // Check if focus has auto-detected Jigasi component(this will be also
  14252. // included if we have passed our host from the config)
  14253. if ($(resultIq).find(
  14254. '>conference>property' +
  14255. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14256. sipGatewayEnabled = true;
  14257. }
  14258. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14259. },
  14260. // FIXME: we need to show the fact that we're waiting for the focus
  14261. // to the user(or that focus is not available)
  14262. allocateConferenceFocus: function (roomName, callback) {
  14263. // Try to use focus user JID from the config
  14264. Moderator.setFocusUserJid(config.focusUserJid);
  14265. // Send create conference IQ
  14266. var iq = Moderator.createConferenceIq(roomName);
  14267. var self = this;
  14268. connection.sendIQ(
  14269. iq,
  14270. function (result) {
  14271. // Setup config options
  14272. Moderator.parseConfigOptions(result);
  14273. if ('true' === $(result).find('conference').attr('ready')) {
  14274. // Reset both timers
  14275. getNextTimeout(true);
  14276. getNextErrorTimeout(true);
  14277. // Exec callback
  14278. callback();
  14279. } else {
  14280. var waitMs = getNextTimeout();
  14281. console.info("Waiting for the focus... " + waitMs);
  14282. // Reset error timeout
  14283. getNextErrorTimeout(true);
  14284. window.setTimeout(
  14285. function () {
  14286. Moderator.allocateConferenceFocus(
  14287. roomName, callback);
  14288. }, waitMs);
  14289. }
  14290. },
  14291. function (error) {
  14292. // Invalid session ? remove and try again
  14293. // without session ID to get a new one
  14294. var invalidSession
  14295. = $(error).find('>error>session-invalid').length;
  14296. if (invalidSession) {
  14297. console.info("Session expired! - removing");
  14298. localStorage.removeItem("sessionId");
  14299. }
  14300. if ($(error).find('>error>graceful-shutdown').length) {
  14301. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14302. return;
  14303. }
  14304. // Check for error returned by the reservation system
  14305. var reservationErr = $(error).find('>error>reservation-error');
  14306. if (reservationErr.length) {
  14307. // Trigger error event
  14308. var errorCode = reservationErr.attr('error-code');
  14309. var errorMsg;
  14310. if ($(error).find('>error>text')) {
  14311. errorMsg = $(error).find('>error>text').text();
  14312. }
  14313. eventEmitter.emit(
  14314. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14315. return;
  14316. }
  14317. // Not authorized to create new room
  14318. if ($(error).find('>error>not-authorized').length) {
  14319. console.warn("Unauthorized to start the conference", error);
  14320. var toDomain
  14321. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14322. if (toDomain !== config.hosts.anonymousdomain) {
  14323. // FIXME: "is external" should come either from
  14324. // the focus or config.js
  14325. externalAuthEnabled = true;
  14326. }
  14327. eventEmitter.emit(
  14328. XMPPEvents.AUTHENTICATION_REQUIRED,
  14329. function () {
  14330. Moderator.allocateConferenceFocus(
  14331. roomName, callback);
  14332. });
  14333. return;
  14334. }
  14335. var waitMs = getNextErrorTimeout();
  14336. console.error("Focus error, retry after " + waitMs, error);
  14337. // Show message
  14338. var focusComponent = Moderator.getFocusComponent();
  14339. var retrySec = waitMs / 1000;
  14340. // FIXME: message is duplicated ?
  14341. // Do not show in case of session invalid
  14342. // which means just a retry
  14343. if (!invalidSession) {
  14344. APP.UI.messageHandler.notify(
  14345. null, "notify.focus",
  14346. 'disconnected', "notify.focusFail",
  14347. {component: focusComponent, ms: retrySec});
  14348. }
  14349. // Reset response timeout
  14350. getNextTimeout(true);
  14351. window.setTimeout(
  14352. function () {
  14353. Moderator.allocateConferenceFocus(roomName, callback);
  14354. }, waitMs);
  14355. }
  14356. );
  14357. },
  14358. getLoginUrl: function (roomName, urlCallback) {
  14359. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14360. iq.c('login-url', {
  14361. xmlns: 'http://jitsi.org/protocol/focus',
  14362. room: roomName,
  14363. 'machine-uid': Settings.getSettings().uid
  14364. });
  14365. connection.sendIQ(
  14366. iq,
  14367. function (result) {
  14368. var url = $(result).find('login-url').attr('url');
  14369. url = url = decodeURIComponent(url);
  14370. if (url) {
  14371. console.info("Got auth url: " + url);
  14372. urlCallback(url);
  14373. } else {
  14374. console.error(
  14375. "Failed to get auth url from the focus", result);
  14376. }
  14377. },
  14378. function (error) {
  14379. console.error("Get auth url error", error);
  14380. }
  14381. );
  14382. },
  14383. getPopupLoginUrl: function (roomName, urlCallback) {
  14384. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14385. iq.c('login-url', {
  14386. xmlns: 'http://jitsi.org/protocol/focus',
  14387. room: roomName,
  14388. 'machine-uid': Settings.getSettings().uid,
  14389. popup: true
  14390. });
  14391. connection.sendIQ(
  14392. iq,
  14393. function (result) {
  14394. var url = $(result).find('login-url').attr('url');
  14395. url = url = decodeURIComponent(url);
  14396. if (url) {
  14397. console.info("Got POPUP auth url: " + url);
  14398. urlCallback(url);
  14399. } else {
  14400. console.error(
  14401. "Failed to get POPUP auth url from the focus", result);
  14402. }
  14403. },
  14404. function (error) {
  14405. console.error('Get POPUP auth url error', error);
  14406. }
  14407. );
  14408. },
  14409. logout: function (callback) {
  14410. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14411. var sessionId = localStorage.getItem('sessionId');
  14412. if (!sessionId) {
  14413. callback();
  14414. return;
  14415. }
  14416. iq.c('logout', {
  14417. xmlns: 'http://jitsi.org/protocol/focus',
  14418. 'session-id': sessionId
  14419. });
  14420. connection.sendIQ(
  14421. iq,
  14422. function (result) {
  14423. var logoutUrl = $(result).find('logout').attr('logout-url');
  14424. if (logoutUrl) {
  14425. logoutUrl = decodeURIComponent(logoutUrl);
  14426. }
  14427. console.info("Log out OK, url: " + logoutUrl, result);
  14428. localStorage.removeItem('sessionId');
  14429. callback(logoutUrl);
  14430. },
  14431. function (error) {
  14432. console.error("Logout error", error);
  14433. }
  14434. );
  14435. }
  14436. };
  14437. module.exports = Moderator;
  14438. },{"../../service/authentication/AuthenticationEvents":103,"../../service/xmpp/XMPPEvents":108,"../settings/Settings":47}],59:[function(require,module,exports){
  14439. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  14440. Toolbar, Util */
  14441. var Moderator = require("./moderator");
  14442. var recordingToken = null;
  14443. var recordingEnabled;
  14444. /**
  14445. * Whether to use a jirecon component for recording, or use the videobridge
  14446. * through COLIBRI.
  14447. */
  14448. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14449. /**
  14450. * The ID of the jirecon recording session. Jirecon generates it when we
  14451. * initially start recording, and it needs to be used in subsequent requests
  14452. * to jirecon.
  14453. */
  14454. var jireconRid = null;
  14455. function setRecordingToken(token) {
  14456. recordingToken = token;
  14457. }
  14458. function setRecording(state, token, callback, connection) {
  14459. if (useJirecon){
  14460. setRecordingJirecon(state, token, callback, connection);
  14461. } else {
  14462. setRecordingColibri(state, token, callback, connection);
  14463. }
  14464. }
  14465. function setRecordingJirecon(state, token, callback, connection) {
  14466. if (state == recordingEnabled){
  14467. return;
  14468. }
  14469. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14470. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14471. action: state ? 'start' : 'stop',
  14472. mucjid: connection.emuc.roomjid});
  14473. if (!state){
  14474. iq.attrs({rid: jireconRid});
  14475. }
  14476. console.log('Start recording');
  14477. connection.sendIQ(
  14478. iq,
  14479. function (result) {
  14480. // TODO wait for an IQ with the real status, since this is
  14481. // provisional?
  14482. jireconRid = $(result).find('recording').attr('rid');
  14483. console.log('Recording ' + (state ? 'started' : 'stopped') +
  14484. '(jirecon)' + result);
  14485. recordingEnabled = state;
  14486. if (!state){
  14487. jireconRid = null;
  14488. }
  14489. callback(state);
  14490. },
  14491. function (error) {
  14492. console.log('Failed to start recording, error: ', error);
  14493. callback(recordingEnabled);
  14494. });
  14495. }
  14496. // Sends a COLIBRI message which enables or disables (according to 'state')
  14497. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14498. // with the new recording state, according to the IQ.
  14499. function setRecordingColibri(state, token, callback, connection) {
  14500. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14501. elem.c('conference', {
  14502. xmlns: 'http://jitsi.org/protocol/colibri'
  14503. });
  14504. elem.c('recording', {state: state, token: token});
  14505. connection.sendIQ(elem,
  14506. function (result) {
  14507. console.log('Set recording "', state, '". Result:', result);
  14508. var recordingElem = $(result).find('>conference>recording');
  14509. var newState = ('true' === recordingElem.attr('state'));
  14510. recordingEnabled = newState;
  14511. callback(newState);
  14512. },
  14513. function (error) {
  14514. console.warn(error);
  14515. callback(recordingEnabled);
  14516. }
  14517. );
  14518. }
  14519. var Recording = {
  14520. toggleRecording: function (tokenEmptyCallback,
  14521. startingCallback, startedCallback, connection) {
  14522. if (!Moderator.isModerator()) {
  14523. console.log(
  14524. 'non-focus, or conference not yet organized:' +
  14525. ' not enabling recording');
  14526. return;
  14527. }
  14528. var self = this;
  14529. // Jirecon does not (currently) support a token.
  14530. if (!recordingToken && !useJirecon) {
  14531. tokenEmptyCallback(function (value) {
  14532. setRecordingToken(value);
  14533. self.toggleRecording(tokenEmptyCallback,
  14534. startingCallback, startedCallback, connection);
  14535. });
  14536. return;
  14537. }
  14538. var oldState = recordingEnabled;
  14539. startingCallback(!oldState);
  14540. setRecording(!oldState,
  14541. recordingToken,
  14542. function (state) {
  14543. console.log("New recording state: ", state);
  14544. if (state === oldState) {
  14545. // FIXME: new focus:
  14546. // this will not work when moderator changes
  14547. // during active session. Then it will assume that
  14548. // recording status has changed to true, but it might have
  14549. // been already true(and we only received actual status from
  14550. // the focus).
  14551. //
  14552. // SO we start with status null, so that it is initialized
  14553. // here and will fail only after second click, so if invalid
  14554. // token was used we have to press the button twice before
  14555. // current status will be fetched and token will be reset.
  14556. //
  14557. // Reliable way would be to return authentication error.
  14558. // Or status update when moderator connects.
  14559. // Or we have to stop recording session when current
  14560. // moderator leaves the room.
  14561. // Failed to change, reset the token because it might
  14562. // have been wrong
  14563. setRecordingToken(null);
  14564. }
  14565. startedCallback(state);
  14566. },
  14567. connection
  14568. );
  14569. }
  14570. }
  14571. module.exports = Recording;
  14572. },{"./moderator":58}],60:[function(require,module,exports){
  14573. /* jshint -W117 */
  14574. /* a simple MUC connection plugin
  14575. * can only handle a single MUC room
  14576. */
  14577. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14578. var Moderator = require("./moderator");
  14579. var JingleSession = require("./JingleSession");
  14580. var bridgeIsDown = false;
  14581. module.exports = function(XMPP, eventEmitter) {
  14582. Strophe.addConnectionPlugin('emuc', {
  14583. connection: null,
  14584. roomjid: null,
  14585. myroomjid: null,
  14586. members: {},
  14587. list_members: [], // so we can elect a new focus
  14588. presMap: {},
  14589. preziMap: {},
  14590. joined: false,
  14591. isOwner: false,
  14592. role: null,
  14593. focusMucJid: null,
  14594. init: function (conn) {
  14595. this.connection = conn;
  14596. },
  14597. initPresenceMap: function (myroomjid) {
  14598. this.presMap['to'] = myroomjid;
  14599. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14600. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted())
  14601. {
  14602. this.addAudioInfoToPresence(true);
  14603. }
  14604. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted())
  14605. {
  14606. this.addVideoInfoToPresence(true);
  14607. }
  14608. },
  14609. doJoin: function (jid, password) {
  14610. this.myroomjid = jid;
  14611. console.info("Joined MUC as " + this.myroomjid);
  14612. this.initPresenceMap(this.myroomjid);
  14613. if (!this.roomjid) {
  14614. this.roomjid = Strophe.getBareJidFromJid(jid);
  14615. // add handlers (just once)
  14616. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14617. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14618. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14619. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14620. }
  14621. if (password !== undefined) {
  14622. this.presMap['password'] = password;
  14623. }
  14624. this.sendPresence();
  14625. },
  14626. doLeave: function () {
  14627. console.log("do leave", this.myroomjid);
  14628. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14629. this.presMap.length = 0;
  14630. this.connection.send(pres);
  14631. },
  14632. createNonAnonymousRoom: function () {
  14633. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  14634. var getForm = $iq({type: 'get', to: this.roomjid})
  14635. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  14636. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14637. var self = this;
  14638. this.connection.sendIQ(getForm, function (form) {
  14639. if (!$(form).find(
  14640. '>query>x[xmlns="jabber:x:data"]' +
  14641. '>field[var="muc#roomconfig_whois"]').length) {
  14642. console.error('non-anonymous rooms not supported');
  14643. return;
  14644. }
  14645. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  14646. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14647. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14648. formSubmit.c('field', {'var': 'FORM_TYPE'})
  14649. .c('value')
  14650. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14651. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  14652. .c('value').t('anyone').up().up();
  14653. self.connection.sendIQ(formSubmit);
  14654. }, function (error) {
  14655. console.error("Error getting room configuration form");
  14656. });
  14657. },
  14658. onPresence: function (pres) {
  14659. var from = pres.getAttribute('from');
  14660. // What is this for? A workaround for something?
  14661. if (pres.getAttribute('type')) {
  14662. return true;
  14663. }
  14664. // Parse etherpad tag.
  14665. var etherpad = $(pres).find('>etherpad');
  14666. if (etherpad.length) {
  14667. if (config.etherpad_base) {
  14668. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  14669. }
  14670. }
  14671. // Parse prezi tag.
  14672. var presentation = $(pres).find('>prezi');
  14673. if (presentation.length) {
  14674. var url = presentation.attr('url');
  14675. var current = presentation.find('>current').text();
  14676. console.log('presentation info received from', from, url);
  14677. if (this.preziMap[from] == null) {
  14678. this.preziMap[from] = url;
  14679. $(document).trigger('presentationadded.muc', [from, url, current]);
  14680. }
  14681. else {
  14682. $(document).trigger('gotoslide.muc', [from, url, current]);
  14683. }
  14684. }
  14685. else if (this.preziMap[from] != null) {
  14686. var url = this.preziMap[from];
  14687. delete this.preziMap[from];
  14688. $(document).trigger('presentationremoved.muc', [from, url]);
  14689. }
  14690. // Parse audio info tag.
  14691. var audioMuted = $(pres).find('>audiomuted');
  14692. if (audioMuted.length) {
  14693. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  14694. from, (audioMuted.text() === "true"));
  14695. }
  14696. // Parse video info tag.
  14697. var videoMuted = $(pres).find('>videomuted');
  14698. if (videoMuted.length) {
  14699. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  14700. from, (videoMuted.text() === "true"));
  14701. }
  14702. var startMuted = $(pres).find('>startmuted');
  14703. if (startMuted.length)
  14704. {
  14705. eventEmitter.emit(XMPPEvents.START_MUTED,
  14706. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  14707. }
  14708. var devices = $(pres).find('>devices');
  14709. if(devices.length)
  14710. {
  14711. var audio = devices.find('>audio');
  14712. var video = devices.find('>video');
  14713. var devicesValues = {audio: false, video: false};
  14714. if(audio.length && audio.text() === "true")
  14715. {
  14716. devicesValues.audio = true;
  14717. }
  14718. if(video.length && video.text() === "true")
  14719. {
  14720. devicesValues.video = true;
  14721. }
  14722. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  14723. Strophe.getResourceFromJid(from), devicesValues);
  14724. }
  14725. var stats = $(pres).find('>stats');
  14726. if (stats.length) {
  14727. var statsObj = {};
  14728. Strophe.forEachChild(stats[0], "stat", function (el) {
  14729. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  14730. });
  14731. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  14732. }
  14733. // Parse status.
  14734. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  14735. this.isOwner = true;
  14736. this.createNonAnonymousRoom();
  14737. }
  14738. // Parse roles.
  14739. var member = {};
  14740. member.show = $(pres).find('>show').text();
  14741. member.status = $(pres).find('>status').text();
  14742. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  14743. member.affiliation = tmp.attr('affiliation');
  14744. member.role = tmp.attr('role');
  14745. // Focus recognition
  14746. member.jid = tmp.attr('jid');
  14747. member.isFocus = false;
  14748. if (member.jid
  14749. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  14750. member.isFocus = true;
  14751. }
  14752. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  14753. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  14754. if (from == this.myroomjid) {
  14755. if (member.affiliation == 'owner') this.isOwner = true;
  14756. if (this.role !== member.role) {
  14757. this.role = member.role;
  14758. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  14759. from, member, pres, Moderator.isModerator());
  14760. }
  14761. if (!this.joined) {
  14762. this.joined = true;
  14763. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  14764. this.list_members.push(from);
  14765. }
  14766. } else if (this.members[from] === undefined) {
  14767. // new participant
  14768. this.members[from] = member;
  14769. this.list_members.push(from);
  14770. console.log('entered', from, member);
  14771. if (member.isFocus) {
  14772. this.focusMucJid = from;
  14773. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  14774. }
  14775. else {
  14776. var id = $(pres).find('>userId').text();
  14777. var email = $(pres).find('>email');
  14778. if (email.length > 0) {
  14779. id = email.text();
  14780. }
  14781. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  14782. }
  14783. } else {
  14784. // Presence update for existing participant
  14785. // Watch role change:
  14786. if (this.members[from].role != member.role) {
  14787. this.members[from].role = member.role;
  14788. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  14789. member.role, member.displayName);
  14790. }
  14791. }
  14792. // Always trigger presence to update bindings
  14793. this.parsePresence(from, member, pres);
  14794. // Trigger status message update
  14795. if (member.status) {
  14796. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  14797. }
  14798. return true;
  14799. },
  14800. onPresenceUnavailable: function (pres) {
  14801. var from = pres.getAttribute('from');
  14802. // room destroyed ?
  14803. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14804. '>destroy').length) {
  14805. var reason;
  14806. var reasonSelect = $(pres).find(
  14807. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14808. '>destroy>reason');
  14809. if (reasonSelect.length) {
  14810. reason = reasonSelect.text();
  14811. }
  14812. XMPP.disposeConference(false);
  14813. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  14814. return true;
  14815. }
  14816. // Status code 110 indicates that this notification is "self-presence".
  14817. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  14818. delete this.members[from];
  14819. this.list_members.splice(this.list_members.indexOf(from), 1);
  14820. this.onParticipantLeft(from);
  14821. }
  14822. // If the status code is 110 this means we're leaving and we would like
  14823. // to remove everyone else from our view, so we trigger the event.
  14824. else if (this.list_members.length > 1) {
  14825. for (var i = 0; i < this.list_members.length; i++) {
  14826. var member = this.list_members[i];
  14827. delete this.members[i];
  14828. this.list_members.splice(i, 1);
  14829. this.onParticipantLeft(member);
  14830. }
  14831. }
  14832. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  14833. $(document).trigger('kicked.muc', [from]);
  14834. if (this.myroomjid === from) {
  14835. XMPP.disposeConference(false);
  14836. eventEmitter.emit(XMPPEvents.KICKED);
  14837. }
  14838. }
  14839. return true;
  14840. },
  14841. onPresenceError: function (pres) {
  14842. var from = pres.getAttribute('from');
  14843. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14844. console.log('on password required', from);
  14845. var self = this;
  14846. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  14847. self.doJoin(from, value);
  14848. });
  14849. } else if ($(pres).find(
  14850. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14851. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  14852. if (toDomain === config.hosts.anonymousdomain) {
  14853. // enter the room by replying with 'not-authorized'. This would
  14854. // result in reconnection from authorized domain.
  14855. // We're either missing Jicofo/Prosody config for anonymous
  14856. // domains or something is wrong.
  14857. // XMPP.promptLogin();
  14858. APP.UI.messageHandler.openReportDialog(null,
  14859. "dialog.joinError", pres);
  14860. } else {
  14861. console.warn('onPresError ', pres);
  14862. APP.UI.messageHandler.openReportDialog(null,
  14863. "dialog.connectError",
  14864. pres);
  14865. }
  14866. } else {
  14867. console.warn('onPresError ', pres);
  14868. APP.UI.messageHandler.openReportDialog(null,
  14869. "dialog.connectError",
  14870. pres);
  14871. }
  14872. return true;
  14873. },
  14874. sendMessage: function (body, nickname) {
  14875. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14876. msg.c('body', body).up();
  14877. if (nickname) {
  14878. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  14879. }
  14880. this.connection.send(msg);
  14881. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  14882. },
  14883. setSubject: function (subject) {
  14884. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14885. msg.c('subject', subject);
  14886. this.connection.send(msg);
  14887. console.log("topic changed to " + subject);
  14888. },
  14889. onMessage: function (msg) {
  14890. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14891. var from = msg.getAttribute('from');
  14892. var nick =
  14893. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14894. .text() ||
  14895. Strophe.getResourceFromJid(from);
  14896. var txt = $(msg).find('>body').text();
  14897. var type = msg.getAttribute("type");
  14898. if (type == "error") {
  14899. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14900. $(msg).find('>text').text(), txt);
  14901. return true;
  14902. }
  14903. var subject = $(msg).find('>subject');
  14904. if (subject.length) {
  14905. var subjectText = subject.text();
  14906. if (subjectText || subjectText == "") {
  14907. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14908. console.log("Subject is changed to " + subjectText);
  14909. }
  14910. }
  14911. // xep-0203 delay
  14912. var stamp = $(msg).find('>delay').attr('stamp');
  14913. if (!stamp) {
  14914. // or xep-0091 delay, UTC timestamp
  14915. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  14916. if (stamp) {
  14917. // the format is CCYYMMDDThh:mm:ss
  14918. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  14919. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  14920. }
  14921. }
  14922. if (txt) {
  14923. console.log('chat', nick, txt);
  14924. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14925. from, nick, txt, this.myroomjid, stamp);
  14926. }
  14927. return true;
  14928. },
  14929. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14930. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14931. var ob = this;
  14932. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14933. function (res) {
  14934. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14935. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14936. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14937. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14938. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14939. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14940. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14941. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14942. ob.connection.sendIQ(formsubmit,
  14943. onSuccess,
  14944. onError);
  14945. } else {
  14946. onNotSupported();
  14947. }
  14948. }, onError);
  14949. },
  14950. kick: function (jid) {
  14951. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14952. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14953. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14954. .c('reason').t('You have been kicked.').up().up().up();
  14955. this.connection.sendIQ(
  14956. kickIQ,
  14957. function (result) {
  14958. console.log('Kick participant with jid: ', jid, result);
  14959. },
  14960. function (error) {
  14961. console.log('Kick participant error: ', error);
  14962. });
  14963. },
  14964. sendPresence: function () {
  14965. if (!this.presMap['to']) {
  14966. // Too early to send presence - not initialized
  14967. return;
  14968. }
  14969. var pres = $pres({to: this.presMap['to'] });
  14970. pres.c('x', {xmlns: this.presMap['xns']});
  14971. if (this.presMap['password']) {
  14972. pres.c('password').t(this.presMap['password']).up();
  14973. }
  14974. pres.up();
  14975. // Send XEP-0115 'c' stanza that contains our capabilities info
  14976. if (this.connection.caps) {
  14977. this.connection.caps.node = config.clientNode;
  14978. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14979. }
  14980. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14981. .t(navigator.userAgent).up();
  14982. if (this.presMap['bridgeIsDown']) {
  14983. pres.c('bridgeIsDown').up();
  14984. }
  14985. if (this.presMap['email']) {
  14986. pres.c('email').t(this.presMap['email']).up();
  14987. }
  14988. if (this.presMap['userId']) {
  14989. pres.c('userId').t(this.presMap['userId']).up();
  14990. }
  14991. if (this.presMap['displayName']) {
  14992. // XEP-0172
  14993. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14994. .t(this.presMap['displayName']).up();
  14995. }
  14996. if(this.presMap["devices"])
  14997. {
  14998. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14999. .c('video').t(this.presMap['devices'].video).up().up();
  15000. }
  15001. if (this.presMap['audions']) {
  15002. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15003. .t(this.presMap['audiomuted']).up();
  15004. }
  15005. if (this.presMap['videons']) {
  15006. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15007. .t(this.presMap['videomuted']).up();
  15008. }
  15009. if (this.presMap['statsns']) {
  15010. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15011. for (var stat in this.presMap["stats"])
  15012. if (this.presMap["stats"][stat] != null)
  15013. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15014. pres.up();
  15015. }
  15016. if (this.presMap['prezins']) {
  15017. pres.c('prezi',
  15018. {xmlns: this.presMap['prezins'],
  15019. 'url': this.presMap['preziurl']})
  15020. .c('current').t(this.presMap['prezicurrent']).up().up();
  15021. }
  15022. if(this.presMap["startMuted"] !== undefined)
  15023. {
  15024. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15025. video: this.presMap["startMuted"].video,
  15026. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15027. delete this.presMap["startMuted"];
  15028. }
  15029. pres.up();
  15030. this.connection.send(pres);
  15031. },
  15032. addDisplayNameToPresence: function (displayName) {
  15033. this.presMap['displayName'] = displayName;
  15034. },
  15035. addDevicesToPresence: function (devices) {
  15036. this.presMap['devices'] = devices;
  15037. },
  15038. addPreziToPresence: function (url, currentSlide) {
  15039. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15040. this.presMap['preziurl'] = url;
  15041. this.presMap['prezicurrent'] = currentSlide;
  15042. },
  15043. removePreziFromPresence: function () {
  15044. delete this.presMap['prezins'];
  15045. delete this.presMap['preziurl'];
  15046. delete this.presMap['prezicurrent'];
  15047. },
  15048. addCurrentSlideToPresence: function (currentSlide) {
  15049. this.presMap['prezicurrent'] = currentSlide;
  15050. },
  15051. getPrezi: function (roomjid) {
  15052. return this.preziMap[roomjid];
  15053. },
  15054. addAudioInfoToPresence: function (isMuted) {
  15055. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15056. this.presMap['audiomuted'] = isMuted.toString();
  15057. },
  15058. addVideoInfoToPresence: function (isMuted) {
  15059. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15060. this.presMap['videomuted'] = isMuted.toString();
  15061. },
  15062. addConnectionInfoToPresence: function (stats) {
  15063. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15064. this.presMap['stats'] = stats;
  15065. },
  15066. findJidFromResource: function (resourceJid) {
  15067. if (resourceJid &&
  15068. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15069. return this.myroomjid;
  15070. }
  15071. var peerJid = null;
  15072. Object.keys(this.members).some(function (jid) {
  15073. peerJid = jid;
  15074. return Strophe.getResourceFromJid(jid) === resourceJid;
  15075. });
  15076. return peerJid;
  15077. },
  15078. addBridgeIsDownToPresence: function () {
  15079. this.presMap['bridgeIsDown'] = true;
  15080. },
  15081. addEmailToPresence: function (email) {
  15082. this.presMap['email'] = email;
  15083. },
  15084. addUserIdToPresence: function (userId) {
  15085. this.presMap['userId'] = userId;
  15086. },
  15087. addStartMutedToPresence: function (audio, video) {
  15088. this.presMap["startMuted"] = {audio: audio, video: video};
  15089. },
  15090. isModerator: function () {
  15091. return this.role === 'moderator';
  15092. },
  15093. getMemberRole: function (peerJid) {
  15094. if (this.members[peerJid]) {
  15095. return this.members[peerJid].role;
  15096. }
  15097. return null;
  15098. },
  15099. onParticipantLeft: function (jid) {
  15100. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15101. this.connection.jingle.terminateByJid(jid);
  15102. if (this.getPrezi(jid)) {
  15103. $(document).trigger('presentationremoved.muc',
  15104. [jid, this.getPrezi(jid)]);
  15105. }
  15106. Moderator.onMucMemberLeft(jid);
  15107. },
  15108. parsePresence: function (from, memeber, pres) {
  15109. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  15110. bridgeIsDown = true;
  15111. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15112. }
  15113. if(memeber.isFocus)
  15114. return;
  15115. var displayName = !config.displayJids
  15116. ? memeber.displayName : Strophe.getResourceFromJid(from);
  15117. if (displayName && displayName.length > 0)
  15118. {
  15119. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15120. }
  15121. var id = $(pres).find('>userID').text();
  15122. var email = $(pres).find('>email');
  15123. if(email.length > 0) {
  15124. id = email.text();
  15125. }
  15126. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15127. }
  15128. });
  15129. };
  15130. },{"../../service/xmpp/XMPPEvents":108,"./JingleSession":53,"./moderator":58}],61:[function(require,module,exports){
  15131. /* jshint -W117 */
  15132. var JingleSession = require("./JingleSession");
  15133. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15134. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15135. module.exports = function(XMPP, eventEmitter)
  15136. {
  15137. function CallIncomingJingle(sid, connection) {
  15138. var sess = connection.jingle.sessions[sid];
  15139. // TODO: do we check activecall == null?
  15140. connection.jingle.activecall = sess;
  15141. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15142. // TODO: check affiliation and/or role
  15143. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15144. sess.usedrip = true; // not-so-naive trickle ice
  15145. sess.sendAnswer();
  15146. sess.accept();
  15147. };
  15148. Strophe.addConnectionPlugin('jingle', {
  15149. connection: null,
  15150. sessions: {},
  15151. jid2session: {},
  15152. ice_config: {iceServers: []},
  15153. pc_constraints: {},
  15154. activecall: null,
  15155. media_constraints: {
  15156. mandatory: {
  15157. 'OfferToReceiveAudio': true,
  15158. 'OfferToReceiveVideo': true
  15159. }
  15160. // MozDontOfferDataChannel: true when this is firefox
  15161. },
  15162. init: function (conn) {
  15163. this.connection = conn;
  15164. if (this.connection.disco) {
  15165. // http://xmpp.org/extensions/xep-0167.html#support
  15166. // http://xmpp.org/extensions/xep-0176.html#support
  15167. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15168. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15169. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15170. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15171. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15172. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15173. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15174. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15175. || RTCBrowserType.isTemasysPluginUsed()) {
  15176. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15177. }
  15178. // this is dealt with by SDP O/A so we don't need to annouce this
  15179. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15180. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15181. if (config.useRtcpMux) {
  15182. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15183. }
  15184. if (config.useBundle) {
  15185. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15186. }
  15187. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15188. }
  15189. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15190. },
  15191. onJingle: function (iq) {
  15192. var sid = $(iq).find('jingle').attr('sid');
  15193. var action = $(iq).find('jingle').attr('action');
  15194. var fromJid = iq.getAttribute('from');
  15195. // send ack first
  15196. var ack = $iq({type: 'result',
  15197. to: fromJid,
  15198. id: iq.getAttribute('id')
  15199. });
  15200. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15201. var sess = this.sessions[sid];
  15202. if ('session-initiate' != action) {
  15203. if (sess === null) {
  15204. ack.type = 'error';
  15205. ack.c('error', {type: 'cancel'})
  15206. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15207. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15208. this.connection.send(ack);
  15209. return true;
  15210. }
  15211. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  15212. // local jid is not checked
  15213. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  15214. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15215. ack.type = 'error';
  15216. ack.c('error', {type: 'cancel'})
  15217. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15218. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15219. this.connection.send(ack);
  15220. return true;
  15221. }
  15222. } else if (sess !== undefined) {
  15223. // existing session with same session id
  15224. // this might be out-of-order if the sess.peerjid is the same as from
  15225. ack.type = 'error';
  15226. ack.c('error', {type: 'cancel'})
  15227. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15228. console.warn('duplicate session id', sid);
  15229. this.connection.send(ack);
  15230. return true;
  15231. }
  15232. // FIXME: check for a defined action
  15233. this.connection.send(ack);
  15234. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15235. switch (action) {
  15236. case 'session-initiate':
  15237. var startMuted = $(iq).find('jingle>startmuted');
  15238. if(startMuted && startMuted.length > 0)
  15239. {
  15240. var audioMuted = startMuted.attr("audio");
  15241. var videoMuted = startMuted.attr("video");
  15242. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  15243. (videoMuted === "true"));
  15244. }
  15245. sess = new JingleSession(
  15246. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15247. this.connection, XMPP, eventEmitter);
  15248. // configure session
  15249. sess.media_constraints = this.media_constraints;
  15250. sess.pc_constraints = this.pc_constraints;
  15251. sess.ice_config = this.ice_config;
  15252. sess.initiate(fromJid, false);
  15253. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15254. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15255. this.sessions[sess.sid] = sess;
  15256. this.jid2session[sess.peerjid] = sess;
  15257. // the callback should either
  15258. // .sendAnswer and .accept
  15259. // or .sendTerminate -- not necessarily synchronus
  15260. CallIncomingJingle(sess.sid, this.connection);
  15261. break;
  15262. case 'session-accept':
  15263. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15264. sess.accept();
  15265. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15266. break;
  15267. case 'session-terminate':
  15268. // If this is not the focus sending the terminate, we have
  15269. // nothing more to do here.
  15270. if (Object.keys(this.sessions).length < 1
  15271. || !(this.sessions[Object.keys(this.sessions)[0]]
  15272. instanceof JingleSession))
  15273. {
  15274. break;
  15275. }
  15276. console.log('terminating...', sess.sid);
  15277. sess.terminate();
  15278. this.terminate(sess.sid);
  15279. if ($(iq).find('>jingle>reason').length) {
  15280. $(document).trigger('callterminated.jingle', [
  15281. sess.sid,
  15282. sess.peerjid,
  15283. $(iq).find('>jingle>reason>:first')[0].tagName,
  15284. $(iq).find('>jingle>reason>text').text()
  15285. ]);
  15286. } else {
  15287. $(document).trigger('callterminated.jingle',
  15288. [sess.sid, sess.peerjid]);
  15289. }
  15290. break;
  15291. case 'transport-info':
  15292. sess.addIceCandidate($(iq).find('>jingle>content'));
  15293. break;
  15294. case 'session-info':
  15295. var affected;
  15296. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15297. $(document).trigger('ringing.jingle', [sess.sid]);
  15298. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15299. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15300. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15301. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15302. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15303. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15304. }
  15305. break;
  15306. case 'addsource': // FIXME: proprietary, un-jingleish
  15307. case 'source-add': // FIXME: proprietary
  15308. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15309. break;
  15310. case 'removesource': // FIXME: proprietary, un-jingleish
  15311. case 'source-remove': // FIXME: proprietary
  15312. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15313. break;
  15314. default:
  15315. console.warn('jingle action not implemented', action);
  15316. break;
  15317. }
  15318. return true;
  15319. },
  15320. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15321. var sess = new JingleSession(myjid || this.connection.jid,
  15322. Math.random().toString(36).substr(2, 12), // random string
  15323. this.connection, XMPP, eventEmitter);
  15324. // configure session
  15325. sess.media_constraints = this.media_constraints;
  15326. sess.pc_constraints = this.pc_constraints;
  15327. sess.ice_config = this.ice_config;
  15328. sess.initiate(peerjid, true);
  15329. this.sessions[sess.sid] = sess;
  15330. this.jid2session[sess.peerjid] = sess;
  15331. sess.sendOffer();
  15332. return sess;
  15333. },
  15334. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15335. if (sid === null || sid === undefined) {
  15336. for (sid in this.sessions) {
  15337. if (this.sessions[sid].state != 'ended') {
  15338. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15339. this.sessions[sid].terminate();
  15340. }
  15341. delete this.jid2session[this.sessions[sid].peerjid];
  15342. delete this.sessions[sid];
  15343. }
  15344. } else if (this.sessions.hasOwnProperty(sid)) {
  15345. if (this.sessions[sid].state != 'ended') {
  15346. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15347. this.sessions[sid].terminate();
  15348. }
  15349. delete this.jid2session[this.sessions[sid].peerjid];
  15350. delete this.sessions[sid];
  15351. }
  15352. },
  15353. // Used to terminate a session when an unavailable presence is received.
  15354. terminateByJid: function (jid) {
  15355. if (this.jid2session.hasOwnProperty(jid)) {
  15356. var sess = this.jid2session[jid];
  15357. if (sess) {
  15358. sess.terminate();
  15359. console.log('peer went away silently', jid);
  15360. delete this.sessions[sess.sid];
  15361. delete this.jid2session[jid];
  15362. $(document).trigger('callterminated.jingle',
  15363. [sess.sid, jid], 'gone');
  15364. }
  15365. }
  15366. },
  15367. terminateRemoteByJid: function (jid, reason) {
  15368. if (this.jid2session.hasOwnProperty(jid)) {
  15369. var sess = this.jid2session[jid];
  15370. if (sess) {
  15371. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15372. sess.terminate();
  15373. console.log('terminate peer with jid', sess.sid, jid);
  15374. delete this.sessions[sess.sid];
  15375. delete this.jid2session[jid];
  15376. $(document).trigger('callterminated.jingle',
  15377. [sess.sid, jid, 'kicked']);
  15378. }
  15379. }
  15380. },
  15381. getStunAndTurnCredentials: function () {
  15382. // get stun and turn configuration from server via xep-0215
  15383. // uses time-limited credentials as described in
  15384. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15385. //
  15386. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15387. // for a prosody module which implements this
  15388. //
  15389. // currently, this doesn't work with updateIce and therefore credentials with a long
  15390. // validity have to be fetched before creating the peerconnection
  15391. // TODO: implement refresh via updateIce as described in
  15392. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15393. var self = this;
  15394. this.connection.sendIQ(
  15395. $iq({type: 'get', to: this.connection.domain})
  15396. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15397. function (res) {
  15398. var iceservers = [];
  15399. $(res).find('>services>service').each(function (idx, el) {
  15400. el = $(el);
  15401. var dict = {};
  15402. var type = el.attr('type');
  15403. switch (type) {
  15404. case 'stun':
  15405. dict.url = 'stun:' + el.attr('host');
  15406. if (el.attr('port')) {
  15407. dict.url += ':' + el.attr('port');
  15408. }
  15409. iceservers.push(dict);
  15410. break;
  15411. case 'turn':
  15412. case 'turns':
  15413. dict.url = type + ':';
  15414. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15415. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15416. dict.url += el.attr('username') + '@';
  15417. } else {
  15418. dict.username = el.attr('username'); // only works in M28
  15419. }
  15420. }
  15421. dict.url += el.attr('host');
  15422. if (el.attr('port') && el.attr('port') != '3478') {
  15423. dict.url += ':' + el.attr('port');
  15424. }
  15425. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15426. dict.url += '?transport=' + el.attr('transport');
  15427. }
  15428. if (el.attr('password')) {
  15429. dict.credential = el.attr('password');
  15430. }
  15431. iceservers.push(dict);
  15432. break;
  15433. }
  15434. });
  15435. self.ice_config.iceServers = iceservers;
  15436. },
  15437. function (err) {
  15438. console.warn('getting turn credentials failed', err);
  15439. console.warn('is mod_turncredentials or similar installed?');
  15440. }
  15441. );
  15442. // implement push?
  15443. },
  15444. /**
  15445. * Populates the log data
  15446. */
  15447. populateData: function () {
  15448. var data = {};
  15449. var self = this;
  15450. Object.keys(this.sessions).forEach(function (sid) {
  15451. var session = self.sessions[sid];
  15452. if (session.peerconnection && session.peerconnection.updateLog) {
  15453. // FIXME: should probably be a .dump call
  15454. data["jingle_" + session.sid] = {
  15455. updateLog: session.peerconnection.updateLog,
  15456. stats: session.peerconnection.stats,
  15457. url: window.location.href
  15458. };
  15459. }
  15460. });
  15461. return data;
  15462. }
  15463. });
  15464. };
  15465. },{"../../service/xmpp/XMPPEvents":108,"../RTC/RTCBrowserType":8,"./JingleSession":53}],62:[function(require,module,exports){
  15466. /* global Strophe */
  15467. module.exports = function () {
  15468. Strophe.addConnectionPlugin('logger', {
  15469. // logs raw stanzas and makes them available for download as JSON
  15470. connection: null,
  15471. log: [],
  15472. init: function (conn) {
  15473. this.connection = conn;
  15474. this.connection.rawInput = this.log_incoming.bind(this);
  15475. this.connection.rawOutput = this.log_outgoing.bind(this);
  15476. },
  15477. log_incoming: function (stanza) {
  15478. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15479. },
  15480. log_outgoing: function (stanza) {
  15481. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15482. }
  15483. });
  15484. };
  15485. },{}],63:[function(require,module,exports){
  15486. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15487. setAudioMuted, Strophe */
  15488. /**
  15489. * Moderate connection plugin.
  15490. */
  15491. module.exports = function (XMPP) {
  15492. Strophe.addConnectionPlugin('moderate', {
  15493. connection: null,
  15494. init: function (conn) {
  15495. this.connection = conn;
  15496. this.connection.addHandler(this.onMute.bind(this),
  15497. 'http://jitsi.org/jitmeet/audio',
  15498. 'iq',
  15499. 'set',
  15500. null,
  15501. null);
  15502. },
  15503. setMute: function (jid, mute) {
  15504. console.info("set mute", mute);
  15505. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15506. .c('mute', {
  15507. xmlns: 'http://jitsi.org/jitmeet/audio',
  15508. jid: jid
  15509. })
  15510. .t(mute.toString())
  15511. .up();
  15512. this.connection.sendIQ(
  15513. iqToFocus,
  15514. function (result) {
  15515. console.log('set mute', result);
  15516. },
  15517. function (error) {
  15518. console.log('set mute error', error);
  15519. });
  15520. },
  15521. onMute: function (iq) {
  15522. var from = iq.getAttribute('from');
  15523. if (from !== this.connection.emuc.focusMucJid) {
  15524. console.warn("Ignored mute from non focus peer");
  15525. return false;
  15526. }
  15527. var mute = $(iq).find('mute');
  15528. if (mute.length) {
  15529. var doMuteAudio = mute.text() === "true";
  15530. APP.UI.setAudioMuted(doMuteAudio);
  15531. XMPP.forceMuted = doMuteAudio;
  15532. }
  15533. return true;
  15534. },
  15535. eject: function (jid) {
  15536. // We're not the focus, so can't terminate
  15537. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15538. this.connection.emuc.kick(jid);
  15539. }
  15540. });
  15541. }
  15542. },{}],64:[function(require,module,exports){
  15543. /* jshint -W117 */
  15544. module.exports = function() {
  15545. Strophe.addConnectionPlugin('rayo',
  15546. {
  15547. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15548. connection: null,
  15549. init: function (conn) {
  15550. this.connection = conn;
  15551. if (this.connection.disco) {
  15552. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15553. }
  15554. this.connection.addHandler(
  15555. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15556. },
  15557. onRayo: function (iq) {
  15558. console.info("Rayo IQ", iq);
  15559. },
  15560. dial: function (to, from, roomName, roomPass) {
  15561. var self = this;
  15562. var req = $iq(
  15563. {
  15564. type: 'set',
  15565. to: this.connection.emuc.focusMucJid
  15566. }
  15567. );
  15568. req.c('dial',
  15569. {
  15570. xmlns: this.RAYO_XMLNS,
  15571. to: to,
  15572. from: from
  15573. });
  15574. req.c('header',
  15575. {
  15576. name: 'JvbRoomName',
  15577. value: roomName
  15578. }).up();
  15579. if (roomPass !== null && roomPass.length) {
  15580. req.c('header',
  15581. {
  15582. name: 'JvbRoomPassword',
  15583. value: roomPass
  15584. }).up();
  15585. }
  15586. this.connection.sendIQ(
  15587. req,
  15588. function (result) {
  15589. console.info('Dial result ', result);
  15590. var resource = $(result).find('ref').attr('uri');
  15591. this.call_resource = resource.substr('xmpp:'.length);
  15592. console.info(
  15593. "Received call resource: " + this.call_resource);
  15594. },
  15595. function (error) {
  15596. console.info('Dial error ', error);
  15597. }
  15598. );
  15599. },
  15600. hang_up: function () {
  15601. if (!this.call_resource) {
  15602. console.warn("No call in progress");
  15603. return;
  15604. }
  15605. var self = this;
  15606. var req = $iq(
  15607. {
  15608. type: 'set',
  15609. to: this.call_resource
  15610. }
  15611. );
  15612. req.c('hangup',
  15613. {
  15614. xmlns: this.RAYO_XMLNS
  15615. });
  15616. this.connection.sendIQ(
  15617. req,
  15618. function (result) {
  15619. console.info('Hangup result ', result);
  15620. self.call_resource = null;
  15621. },
  15622. function (error) {
  15623. console.info('Hangup error ', error);
  15624. self.call_resource = null;
  15625. }
  15626. );
  15627. }
  15628. }
  15629. );
  15630. };
  15631. },{}],65:[function(require,module,exports){
  15632. /**
  15633. * Strophe logger implementation. Logs from level WARN and above.
  15634. */
  15635. module.exports = function () {
  15636. Strophe.log = function (level, msg) {
  15637. switch (level) {
  15638. case Strophe.LogLevel.WARN:
  15639. console.warn("Strophe: " + msg);
  15640. break;
  15641. case Strophe.LogLevel.ERROR:
  15642. case Strophe.LogLevel.FATAL:
  15643. console.error("Strophe: " + msg);
  15644. break;
  15645. }
  15646. };
  15647. Strophe.getStatusString = function (status) {
  15648. switch (status) {
  15649. case Strophe.Status.ERROR:
  15650. return "ERROR";
  15651. case Strophe.Status.CONNECTING:
  15652. return "CONNECTING";
  15653. case Strophe.Status.CONNFAIL:
  15654. return "CONNFAIL";
  15655. case Strophe.Status.AUTHENTICATING:
  15656. return "AUTHENTICATING";
  15657. case Strophe.Status.AUTHFAIL:
  15658. return "AUTHFAIL";
  15659. case Strophe.Status.CONNECTED:
  15660. return "CONNECTED";
  15661. case Strophe.Status.DISCONNECTED:
  15662. return "DISCONNECTED";
  15663. case Strophe.Status.DISCONNECTING:
  15664. return "DISCONNECTING";
  15665. case Strophe.Status.ATTACHED:
  15666. return "ATTACHED";
  15667. default:
  15668. return "unknown";
  15669. }
  15670. };
  15671. };
  15672. },{}],66:[function(require,module,exports){
  15673. /* global $, APP, config, Strophe*/
  15674. var Moderator = require("./moderator");
  15675. var EventEmitter = require("events");
  15676. var Recording = require("./recording");
  15677. var SDP = require("./SDP");
  15678. var Settings = require("../settings/Settings");
  15679. var Pako = require("pako");
  15680. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  15681. var RTCEvents = require("../../service/RTC/RTCEvents");
  15682. var UIEvents = require("../../service/UI/UIEvents");
  15683. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15684. var retry = require('retry');
  15685. var eventEmitter = new EventEmitter();
  15686. var connection = null;
  15687. var authenticatedUser = false;
  15688. function connect(jid, password) {
  15689. var faultTolerantConnect = retry.operation({
  15690. retries: 3
  15691. });
  15692. // fault tolerant connect
  15693. faultTolerantConnect.attempt(function () {
  15694. connection = XMPP.createConnection();
  15695. Moderator.setConnection(connection);
  15696. if (connection.disco) {
  15697. // for chrome, add multistream cap
  15698. }
  15699. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  15700. if (config.useIPv6) {
  15701. // https://code.google.com/p/webrtc/issues/detail?id=2828
  15702. if (!connection.jingle.pc_constraints.optional)
  15703. connection.jingle.pc_constraints.optional = [];
  15704. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  15705. }
  15706. // Include user info in MUC presence
  15707. var settings = Settings.getSettings();
  15708. if (settings.email) {
  15709. connection.emuc.addEmailToPresence(settings.email);
  15710. }
  15711. if (settings.uid) {
  15712. connection.emuc.addUserIdToPresence(settings.uid);
  15713. }
  15714. if (settings.displayName) {
  15715. connection.emuc.addDisplayNameToPresence(settings.displayName);
  15716. }
  15717. // connection.connect() starts the connection process.
  15718. //
  15719. // As the connection process proceeds, the user supplied callback will
  15720. // be triggered multiple times with status updates. The callback should
  15721. // take two arguments - the status code and the error condition.
  15722. //
  15723. // The status code will be one of the values in the Strophe.Status
  15724. // constants. The error condition will be one of the conditions defined
  15725. // in RFC 3920 or the condition ‘strophe-parsererror’.
  15726. //
  15727. // The Parameters wait, hold and route are optional and only relevant
  15728. // for BOSH connections. Please see XEP 124 for a more detailed
  15729. // explanation of the optional parameters.
  15730. //
  15731. // Connection status constants for use by the connection handler
  15732. // callback.
  15733. //
  15734. // Status.ERROR - An error has occurred (websockets specific)
  15735. // Status.CONNECTING - The connection is currently being made
  15736. // Status.CONNFAIL - The connection attempt failed
  15737. // Status.AUTHENTICATING - The connection is authenticating
  15738. // Status.AUTHFAIL - The authentication attempt failed
  15739. // Status.CONNECTED - The connection has succeeded
  15740. // Status.DISCONNECTED - The connection has been terminated
  15741. // Status.DISCONNECTING - The connection is currently being terminated
  15742. // Status.ATTACHED - The connection has been attached
  15743. var anonymousConnectionFailed = false;
  15744. var connectionFailed = false;
  15745. var lastErrorMsg;
  15746. connection.connect(jid, password, function (status, msg) {
  15747. console.log('Strophe status changed to',
  15748. Strophe.getStatusString(status), msg);
  15749. if (status === Strophe.Status.CONNECTED) {
  15750. if (config.useStunTurn) {
  15751. connection.jingle.getStunAndTurnCredentials();
  15752. }
  15753. console.info("My Jabber ID: " + connection.jid);
  15754. if (password)
  15755. authenticatedUser = true;
  15756. maybeDoJoin();
  15757. } else if (status === Strophe.Status.CONNFAIL) {
  15758. if (msg === 'x-strophe-bad-non-anon-jid') {
  15759. anonymousConnectionFailed = true;
  15760. } else {
  15761. connectionFailed = true;
  15762. }
  15763. lastErrorMsg = msg;
  15764. } else if (status === Strophe.Status.DISCONNECTED) {
  15765. if (anonymousConnectionFailed) {
  15766. // prompt user for username and password
  15767. XMPP.promptLogin();
  15768. } else {
  15769. // Strophe already has built-in HTTP/BOSH error handling and
  15770. // request retry logic. Requests are resent automatically
  15771. // until their error count reaches 5. Strophe.js disconnects
  15772. // if the error count is > 5. We are not replicating this
  15773. // here.
  15774. //
  15775. // The "problem" is that failed HTTP/BOSH requests don't
  15776. // trigger a callback with a status update, so when a
  15777. // callback with status Strophe.Status.DISCONNECTED arrives,
  15778. // we can't be sure if it's a graceful disconnect or if it's
  15779. // triggered by some HTTP/BOSH error.
  15780. //
  15781. // But that's a minor issue in Jitsi Meet as we never
  15782. // disconnect anyway, not even when the user closes the
  15783. // browser window (which is kind of wrong, but the point is
  15784. // that we should never ever get disconnected).
  15785. //
  15786. // On the other hand, failed connections due to XMPP layer
  15787. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  15788. //
  15789. // Here we implement retry logic for failed connections due
  15790. // to XMPP layer errors and we display an error to the user
  15791. // if we get disconnected from the XMPP server permanently.
  15792. // If the connection failed, retry.
  15793. if (connectionFailed
  15794. && faultTolerantConnect.retry("connection-failed")) {
  15795. return;
  15796. }
  15797. // If we failed to connect to the XMPP server, fire an event
  15798. // to let all the interested module now about it.
  15799. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  15800. msg ? msg : lastErrorMsg);
  15801. }
  15802. } else if (status === Strophe.Status.AUTHFAIL) {
  15803. // wrong password or username, prompt user
  15804. XMPP.promptLogin();
  15805. }
  15806. });
  15807. });
  15808. }
  15809. function maybeDoJoin() {
  15810. if (connection && connection.connected &&
  15811. Strophe.getResourceFromJid(connection.jid)
  15812. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15813. // .connected is true while connecting?
  15814. doJoin();
  15815. }
  15816. }
  15817. function doJoin() {
  15818. var roomName = APP.UI.generateRoomName();
  15819. Moderator.allocateConferenceFocus(
  15820. roomName, APP.UI.checkForNicknameAndJoin);
  15821. }
  15822. function initStrophePlugins()
  15823. {
  15824. require("./strophe.emuc")(XMPP, eventEmitter);
  15825. require("./strophe.jingle")(XMPP, eventEmitter);
  15826. require("./strophe.moderate")(XMPP);
  15827. require("./strophe.util")();
  15828. require("./strophe.rayo")();
  15829. require("./strophe.logger")();
  15830. }
  15831. function registerListeners() {
  15832. APP.RTC.addStreamListener(maybeDoJoin,
  15833. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  15834. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  15835. XMPP.addToPresence("devices", devices);
  15836. })
  15837. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  15838. XMPP.addToPresence("displayName", nickname);
  15839. });
  15840. }
  15841. var unload = (function () {
  15842. var unloaded = false;
  15843. return function () {
  15844. if (unloaded) { return; }
  15845. unloaded = true;
  15846. if (connection && connection.connected) {
  15847. // ensure signout
  15848. $.ajax({
  15849. type: 'POST',
  15850. url: config.bosh,
  15851. async: false,
  15852. cache: false,
  15853. contentType: 'application/xml',
  15854. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  15855. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  15856. (connection.sid || connection._proto.sid) +
  15857. "' type='terminate'>" +
  15858. "<presence xmlns='jabber:client' type='unavailable'/>" +
  15859. "</body>",
  15860. success: function (data) {
  15861. console.log('signed out');
  15862. console.log(data);
  15863. },
  15864. error: function (XMLHttpRequest, textStatus, errorThrown) {
  15865. console.log('signout error',
  15866. textStatus + ' (' + errorThrown + ')');
  15867. }
  15868. });
  15869. }
  15870. XMPP.disposeConference(true);
  15871. };
  15872. })();
  15873. function setupEvents() {
  15874. // In recent versions of FF the 'beforeunload' event is not fired when the
  15875. // window or the tab is closed. It is only fired when we leave the page
  15876. // (change URL). If this participant doesn't unload properly, then it
  15877. // becomes a ghost for the rest of the participants that stay in the
  15878. // conference. Thankfully handling the 'unload' event in addition to the
  15879. // 'beforeunload' event seems to garante the execution of the 'unload'
  15880. // method at least once.
  15881. //
  15882. // The 'unload' method can safely be run multiple times, it will actually do
  15883. // something only the first time that it's run, so we're don't have to worry
  15884. // about browsers that fire both events.
  15885. $(window).bind('beforeunload', unload);
  15886. $(window).bind('unload', unload);
  15887. }
  15888. var XMPP = {
  15889. getConnection: function(){ return connection; },
  15890. sessionTerminated: false,
  15891. /**
  15892. * XMPP connection status
  15893. */
  15894. Status: Strophe.Status,
  15895. /**
  15896. * Remembers if we were muted by the focus.
  15897. * @type {boolean}
  15898. */
  15899. forceMuted: false,
  15900. start: function () {
  15901. setupEvents();
  15902. initStrophePlugins();
  15903. registerListeners();
  15904. Moderator.init(this, eventEmitter);
  15905. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  15906. // Force authenticated domain if room is appended with '?login=true'
  15907. if (config.hosts.anonymousdomain &&
  15908. window.location.search.indexOf("login=true") !== -1) {
  15909. configDomain = config.hosts.domain;
  15910. }
  15911. var jid = configDomain || window.location.hostname;
  15912. connect(jid, null);
  15913. },
  15914. createConnection: function () {
  15915. var bosh = config.bosh || '/http-bind';
  15916. return new Strophe.Connection(bosh);
  15917. },
  15918. getStatusString: function (status) {
  15919. return Strophe.getStatusString(status);
  15920. },
  15921. promptLogin: function () {
  15922. // FIXME: re-use LoginDialog which supports retries
  15923. APP.UI.showLoginPopup(connect);
  15924. },
  15925. joinRoom: function(roomName, useNicks, nick)
  15926. {
  15927. var roomjid;
  15928. roomjid = roomName;
  15929. if (useNicks) {
  15930. if (nick) {
  15931. roomjid += '/' + nick;
  15932. } else {
  15933. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  15934. }
  15935. } else {
  15936. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  15937. if(!authenticatedUser)
  15938. tmpJid = tmpJid.substr(0, 8);
  15939. roomjid += '/' + tmpJid;
  15940. }
  15941. connection.emuc.doJoin(roomjid);
  15942. },
  15943. myJid: function () {
  15944. if(!connection)
  15945. return null;
  15946. return connection.emuc.myroomjid;
  15947. },
  15948. myResource: function () {
  15949. if(!connection || ! connection.emuc.myroomjid)
  15950. return null;
  15951. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  15952. },
  15953. disposeConference: function (onUnload) {
  15954. var handler = connection.jingle.activecall;
  15955. if (handler && handler.peerconnection) {
  15956. // FIXME: probably removing streams is not required and close() should
  15957. // be enough
  15958. if (APP.RTC.localAudio) {
  15959. handler.peerconnection.removeStream(
  15960. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15961. }
  15962. if (APP.RTC.localVideo) {
  15963. handler.peerconnection.removeStream(
  15964. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15965. }
  15966. handler.peerconnection.close();
  15967. }
  15968. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  15969. connection.jingle.activecall = null;
  15970. if(!onUnload)
  15971. {
  15972. this.sessionTerminated = true;
  15973. connection.emuc.doLeave();
  15974. }
  15975. },
  15976. addListener: function(type, listener)
  15977. {
  15978. eventEmitter.on(type, listener);
  15979. },
  15980. removeListener: function (type, listener) {
  15981. eventEmitter.removeListener(type, listener);
  15982. },
  15983. allocateConferenceFocus: function(roomName, callback) {
  15984. Moderator.allocateConferenceFocus(roomName, callback);
  15985. },
  15986. getLoginUrl: function (roomName, callback) {
  15987. Moderator.getLoginUrl(roomName, callback);
  15988. },
  15989. getPopupLoginUrl: function (roomName, callback) {
  15990. Moderator.getPopupLoginUrl(roomName, callback);
  15991. },
  15992. isModerator: function () {
  15993. return Moderator.isModerator();
  15994. },
  15995. isSipGatewayEnabled: function () {
  15996. return Moderator.isSipGatewayEnabled();
  15997. },
  15998. isExternalAuthEnabled: function () {
  15999. return Moderator.isExternalAuthEnabled();
  16000. },
  16001. isConferenceInProgress: function () {
  16002. return connection && connection.jingle.activecall &&
  16003. connection.jingle.activecall.peerconnection;
  16004. },
  16005. switchStreams: function (stream, oldStream, callback, isAudio) {
  16006. if (this.isConferenceInProgress()) {
  16007. // FIXME: will block switchInProgress on true value in case of exception
  16008. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16009. } else {
  16010. // We are done immediately
  16011. console.warn("No conference handler or conference not started yet");
  16012. callback();
  16013. }
  16014. },
  16015. sendVideoInfoPresence: function (mute) {
  16016. if(!connection)
  16017. return;
  16018. connection.emuc.addVideoInfoToPresence(mute);
  16019. connection.emuc.sendPresence();
  16020. },
  16021. setVideoMute: function (mute, callback, options) {
  16022. if(!connection)
  16023. return;
  16024. var self = this;
  16025. var localCallback = function (mute) {
  16026. self.sendVideoInfoPresence(mute);
  16027. return callback(mute);
  16028. };
  16029. if(connection.jingle.activecall)
  16030. {
  16031. connection.jingle.activecall.setVideoMute(
  16032. mute, localCallback, options);
  16033. }
  16034. else {
  16035. localCallback(mute);
  16036. }
  16037. },
  16038. setAudioMute: function (mute, callback) {
  16039. if (!(connection && APP.RTC.localAudio)) {
  16040. return false;
  16041. }
  16042. if (this.forceMuted && !mute) {
  16043. console.info("Asking focus for unmute");
  16044. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16045. // FIXME: wait for result before resetting muted status
  16046. this.forceMuted = false;
  16047. }
  16048. if (mute == APP.RTC.localAudio.isMuted()) {
  16049. // Nothing to do
  16050. return true;
  16051. }
  16052. // It is not clear what is the right way to handle multiple tracks.
  16053. // So at least make sure that they are all muted or all unmuted and
  16054. // that we send presence just once.
  16055. APP.RTC.localAudio.setMute(!mute);
  16056. // isMuted is the opposite of audioEnabled
  16057. this.sendAudioInfoPresence(mute, callback);
  16058. return true;
  16059. },
  16060. sendAudioInfoPresence: function(mute, callback)
  16061. {
  16062. if(connection) {
  16063. connection.emuc.addAudioInfoToPresence(mute);
  16064. connection.emuc.sendPresence();
  16065. }
  16066. callback();
  16067. return true;
  16068. },
  16069. // Really mute video, i.e. dont even send black frames
  16070. muteVideo: function (pc, unmute) {
  16071. // FIXME: this probably needs another of those lovely state safeguards...
  16072. // which checks for iceconn == connected and sigstate == stable
  16073. pc.setRemoteDescription(pc.remoteDescription,
  16074. function () {
  16075. pc.createAnswer(
  16076. function (answer) {
  16077. var sdp = new SDP(answer.sdp);
  16078. if (sdp.media.length > 1) {
  16079. if (unmute)
  16080. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  16081. else
  16082. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  16083. sdp.raw = sdp.session + sdp.media.join('');
  16084. answer.sdp = sdp.raw;
  16085. }
  16086. pc.setLocalDescription(answer,
  16087. function () {
  16088. console.log('mute SLD ok');
  16089. },
  16090. function (error) {
  16091. console.log('mute SLD error');
  16092. APP.UI.messageHandler.showError("dialog.error",
  16093. "dialog.SLDFailure");
  16094. }
  16095. );
  16096. },
  16097. function (error) {
  16098. console.log(error);
  16099. APP.UI.messageHandler.showError();
  16100. }
  16101. );
  16102. },
  16103. function (error) {
  16104. console.log('muteVideo SRD error');
  16105. APP.UI.messageHandler.showError("dialog.error",
  16106. "dialog.SRDFailure");
  16107. }
  16108. );
  16109. },
  16110. toggleRecording: function (tokenEmptyCallback,
  16111. startingCallback, startedCallback) {
  16112. Recording.toggleRecording(tokenEmptyCallback,
  16113. startingCallback, startedCallback, connection);
  16114. },
  16115. addToPresence: function (name, value, dontSend) {
  16116. switch (name)
  16117. {
  16118. case "displayName":
  16119. connection.emuc.addDisplayNameToPresence(value);
  16120. break;
  16121. case "prezi":
  16122. connection.emuc.addPreziToPresence(value, 0);
  16123. break;
  16124. case "preziSlide":
  16125. connection.emuc.addCurrentSlideToPresence(value);
  16126. break;
  16127. case "connectionQuality":
  16128. connection.emuc.addConnectionInfoToPresence(value);
  16129. break;
  16130. case "email":
  16131. connection.emuc.addEmailToPresence(value);
  16132. break;
  16133. case "devices":
  16134. connection.emuc.addDevicesToPresence(value);
  16135. break;
  16136. case "startMuted":
  16137. if(!Moderator.isModerator())
  16138. return;
  16139. connection.emuc.addStartMutedToPresence(value[0],
  16140. value[1]);
  16141. break;
  16142. default :
  16143. console.log("Unknown tag for presence: " + name);
  16144. return;
  16145. }
  16146. if (!dontSend)
  16147. connection.emuc.sendPresence();
  16148. },
  16149. /**
  16150. * Sends 'data' as a log message to the focus. Returns true iff a message
  16151. * was sent.
  16152. * @param data
  16153. * @returns {boolean} true iff a message was sent.
  16154. */
  16155. sendLogs: function (data) {
  16156. if(!connection.emuc.focusMucJid)
  16157. return false;
  16158. var deflate = true;
  16159. var content = JSON.stringify(data);
  16160. if (deflate) {
  16161. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16162. }
  16163. content = Base64.encode(content);
  16164. // XEP-0337-ish
  16165. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16166. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16167. id: 'PeerConnectionStats'});
  16168. message.c('message').t(content).up();
  16169. if (deflate) {
  16170. message.c('tag', {name: "deflated", value: "true"}).up();
  16171. }
  16172. message.up();
  16173. connection.send(message);
  16174. return true;
  16175. },
  16176. populateData: function () {
  16177. var data = {};
  16178. if (connection.jingle) {
  16179. data = connection.jingle.populateData();
  16180. }
  16181. return data;
  16182. },
  16183. getLogger: function () {
  16184. if(connection.logger)
  16185. return connection.logger.log;
  16186. return null;
  16187. },
  16188. getPrezi: function () {
  16189. return connection.emuc.getPrezi(this.myJid());
  16190. },
  16191. removePreziFromPresence: function () {
  16192. connection.emuc.removePreziFromPresence();
  16193. connection.emuc.sendPresence();
  16194. },
  16195. sendChatMessage: function (message, nickname) {
  16196. connection.emuc.sendMessage(message, nickname);
  16197. },
  16198. setSubject: function (topic) {
  16199. connection.emuc.setSubject(topic);
  16200. },
  16201. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16202. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16203. },
  16204. dial: function (to, from, roomName,roomPass) {
  16205. connection.rayo.dial(to, from, roomName,roomPass);
  16206. },
  16207. setMute: function (jid, mute) {
  16208. connection.moderate.setMute(jid, mute);
  16209. },
  16210. eject: function (jid) {
  16211. connection.moderate.eject(jid);
  16212. },
  16213. logout: function (callback) {
  16214. Moderator.logout(callback);
  16215. },
  16216. findJidFromResource: function (resource) {
  16217. return connection.emuc.findJidFromResource(resource);
  16218. },
  16219. getMembers: function () {
  16220. return connection.emuc.members;
  16221. },
  16222. getJidFromSSRC: function (ssrc) {
  16223. if (!this.isConferenceInProgress())
  16224. return null;
  16225. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16226. },
  16227. getMUCJoined: function () {
  16228. return connection.emuc.joined;
  16229. },
  16230. getSessions: function () {
  16231. return connection.jingle.sessions;
  16232. },
  16233. removeStream: function (stream) {
  16234. if (!this.isConferenceInProgress())
  16235. return;
  16236. connection.jingle.activecall.peerconnection.removeStream(stream);
  16237. }
  16238. };
  16239. module.exports = XMPP;
  16240. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes":101,"../../service/UI/UIEvents":102,"../../service/xmpp/XMPPEvents":108,"../settings/Settings":47,"./SDP":54,"./moderator":58,"./recording":59,"./strophe.emuc":60,"./strophe.jingle":61,"./strophe.logger":62,"./strophe.moderate":63,"./strophe.rayo":64,"./strophe.util":65,"events":109,"pako":69,"retry":85}],67:[function(require,module,exports){
  16241. (function (process){
  16242. /*!
  16243. * async
  16244. * https://github.com/caolan/async
  16245. *
  16246. * Copyright 2010-2014 Caolan McMahon
  16247. * Released under the MIT license
  16248. */
  16249. /*jshint onevar: false, indent:4 */
  16250. /*global setImmediate: false, setTimeout: false, console: false */
  16251. (function () {
  16252. var async = {};
  16253. // global on the server, window in the browser
  16254. var root, previous_async;
  16255. root = this;
  16256. if (root != null) {
  16257. previous_async = root.async;
  16258. }
  16259. async.noConflict = function () {
  16260. root.async = previous_async;
  16261. return async;
  16262. };
  16263. function only_once(fn) {
  16264. var called = false;
  16265. return function() {
  16266. if (called) throw new Error("Callback was already called.");
  16267. called = true;
  16268. fn.apply(root, arguments);
  16269. }
  16270. }
  16271. //// cross-browser compatiblity functions ////
  16272. var _toString = Object.prototype.toString;
  16273. var _isArray = Array.isArray || function (obj) {
  16274. return _toString.call(obj) === '[object Array]';
  16275. };
  16276. var _each = function (arr, iterator) {
  16277. if (arr.forEach) {
  16278. return arr.forEach(iterator);
  16279. }
  16280. for (var i = 0; i < arr.length; i += 1) {
  16281. iterator(arr[i], i, arr);
  16282. }
  16283. };
  16284. var _map = function (arr, iterator) {
  16285. if (arr.map) {
  16286. return arr.map(iterator);
  16287. }
  16288. var results = [];
  16289. _each(arr, function (x, i, a) {
  16290. results.push(iterator(x, i, a));
  16291. });
  16292. return results;
  16293. };
  16294. var _reduce = function (arr, iterator, memo) {
  16295. if (arr.reduce) {
  16296. return arr.reduce(iterator, memo);
  16297. }
  16298. _each(arr, function (x, i, a) {
  16299. memo = iterator(memo, x, i, a);
  16300. });
  16301. return memo;
  16302. };
  16303. var _keys = function (obj) {
  16304. if (Object.keys) {
  16305. return Object.keys(obj);
  16306. }
  16307. var keys = [];
  16308. for (var k in obj) {
  16309. if (obj.hasOwnProperty(k)) {
  16310. keys.push(k);
  16311. }
  16312. }
  16313. return keys;
  16314. };
  16315. //// exported async module functions ////
  16316. //// nextTick implementation with browser-compatible fallback ////
  16317. if (typeof process === 'undefined' || !(process.nextTick)) {
  16318. if (typeof setImmediate === 'function') {
  16319. async.nextTick = function (fn) {
  16320. // not a direct alias for IE10 compatibility
  16321. setImmediate(fn);
  16322. };
  16323. async.setImmediate = async.nextTick;
  16324. }
  16325. else {
  16326. async.nextTick = function (fn) {
  16327. setTimeout(fn, 0);
  16328. };
  16329. async.setImmediate = async.nextTick;
  16330. }
  16331. }
  16332. else {
  16333. async.nextTick = process.nextTick;
  16334. if (typeof setImmediate !== 'undefined') {
  16335. async.setImmediate = function (fn) {
  16336. // not a direct alias for IE10 compatibility
  16337. setImmediate(fn);
  16338. };
  16339. }
  16340. else {
  16341. async.setImmediate = async.nextTick;
  16342. }
  16343. }
  16344. async.each = function (arr, iterator, callback) {
  16345. callback = callback || function () {};
  16346. if (!arr.length) {
  16347. return callback();
  16348. }
  16349. var completed = 0;
  16350. _each(arr, function (x) {
  16351. iterator(x, only_once(done) );
  16352. });
  16353. function done(err) {
  16354. if (err) {
  16355. callback(err);
  16356. callback = function () {};
  16357. }
  16358. else {
  16359. completed += 1;
  16360. if (completed >= arr.length) {
  16361. callback();
  16362. }
  16363. }
  16364. }
  16365. };
  16366. async.forEach = async.each;
  16367. async.eachSeries = function (arr, iterator, callback) {
  16368. callback = callback || function () {};
  16369. if (!arr.length) {
  16370. return callback();
  16371. }
  16372. var completed = 0;
  16373. var iterate = function () {
  16374. iterator(arr[completed], function (err) {
  16375. if (err) {
  16376. callback(err);
  16377. callback = function () {};
  16378. }
  16379. else {
  16380. completed += 1;
  16381. if (completed >= arr.length) {
  16382. callback();
  16383. }
  16384. else {
  16385. iterate();
  16386. }
  16387. }
  16388. });
  16389. };
  16390. iterate();
  16391. };
  16392. async.forEachSeries = async.eachSeries;
  16393. async.eachLimit = function (arr, limit, iterator, callback) {
  16394. var fn = _eachLimit(limit);
  16395. fn.apply(null, [arr, iterator, callback]);
  16396. };
  16397. async.forEachLimit = async.eachLimit;
  16398. var _eachLimit = function (limit) {
  16399. return function (arr, iterator, callback) {
  16400. callback = callback || function () {};
  16401. if (!arr.length || limit <= 0) {
  16402. return callback();
  16403. }
  16404. var completed = 0;
  16405. var started = 0;
  16406. var running = 0;
  16407. (function replenish () {
  16408. if (completed >= arr.length) {
  16409. return callback();
  16410. }
  16411. while (running < limit && started < arr.length) {
  16412. started += 1;
  16413. running += 1;
  16414. iterator(arr[started - 1], function (err) {
  16415. if (err) {
  16416. callback(err);
  16417. callback = function () {};
  16418. }
  16419. else {
  16420. completed += 1;
  16421. running -= 1;
  16422. if (completed >= arr.length) {
  16423. callback();
  16424. }
  16425. else {
  16426. replenish();
  16427. }
  16428. }
  16429. });
  16430. }
  16431. })();
  16432. };
  16433. };
  16434. var doParallel = function (fn) {
  16435. return function () {
  16436. var args = Array.prototype.slice.call(arguments);
  16437. return fn.apply(null, [async.each].concat(args));
  16438. };
  16439. };
  16440. var doParallelLimit = function(limit, fn) {
  16441. return function () {
  16442. var args = Array.prototype.slice.call(arguments);
  16443. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16444. };
  16445. };
  16446. var doSeries = function (fn) {
  16447. return function () {
  16448. var args = Array.prototype.slice.call(arguments);
  16449. return fn.apply(null, [async.eachSeries].concat(args));
  16450. };
  16451. };
  16452. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16453. arr = _map(arr, function (x, i) {
  16454. return {index: i, value: x};
  16455. });
  16456. if (!callback) {
  16457. eachfn(arr, function (x, callback) {
  16458. iterator(x.value, function (err) {
  16459. callback(err);
  16460. });
  16461. });
  16462. } else {
  16463. var results = [];
  16464. eachfn(arr, function (x, callback) {
  16465. iterator(x.value, function (err, v) {
  16466. results[x.index] = v;
  16467. callback(err);
  16468. });
  16469. }, function (err) {
  16470. callback(err, results);
  16471. });
  16472. }
  16473. };
  16474. async.map = doParallel(_asyncMap);
  16475. async.mapSeries = doSeries(_asyncMap);
  16476. async.mapLimit = function (arr, limit, iterator, callback) {
  16477. return _mapLimit(limit)(arr, iterator, callback);
  16478. };
  16479. var _mapLimit = function(limit) {
  16480. return doParallelLimit(limit, _asyncMap);
  16481. };
  16482. // reduce only has a series version, as doing reduce in parallel won't
  16483. // work in many situations.
  16484. async.reduce = function (arr, memo, iterator, callback) {
  16485. async.eachSeries(arr, function (x, callback) {
  16486. iterator(memo, x, function (err, v) {
  16487. memo = v;
  16488. callback(err);
  16489. });
  16490. }, function (err) {
  16491. callback(err, memo);
  16492. });
  16493. };
  16494. // inject alias
  16495. async.inject = async.reduce;
  16496. // foldl alias
  16497. async.foldl = async.reduce;
  16498. async.reduceRight = function (arr, memo, iterator, callback) {
  16499. var reversed = _map(arr, function (x) {
  16500. return x;
  16501. }).reverse();
  16502. async.reduce(reversed, memo, iterator, callback);
  16503. };
  16504. // foldr alias
  16505. async.foldr = async.reduceRight;
  16506. var _filter = function (eachfn, arr, iterator, callback) {
  16507. var results = [];
  16508. arr = _map(arr, function (x, i) {
  16509. return {index: i, value: x};
  16510. });
  16511. eachfn(arr, function (x, callback) {
  16512. iterator(x.value, function (v) {
  16513. if (v) {
  16514. results.push(x);
  16515. }
  16516. callback();
  16517. });
  16518. }, function (err) {
  16519. callback(_map(results.sort(function (a, b) {
  16520. return a.index - b.index;
  16521. }), function (x) {
  16522. return x.value;
  16523. }));
  16524. });
  16525. };
  16526. async.filter = doParallel(_filter);
  16527. async.filterSeries = doSeries(_filter);
  16528. // select alias
  16529. async.select = async.filter;
  16530. async.selectSeries = async.filterSeries;
  16531. var _reject = function (eachfn, arr, iterator, callback) {
  16532. var results = [];
  16533. arr = _map(arr, function (x, i) {
  16534. return {index: i, value: x};
  16535. });
  16536. eachfn(arr, function (x, callback) {
  16537. iterator(x.value, function (v) {
  16538. if (!v) {
  16539. results.push(x);
  16540. }
  16541. callback();
  16542. });
  16543. }, function (err) {
  16544. callback(_map(results.sort(function (a, b) {
  16545. return a.index - b.index;
  16546. }), function (x) {
  16547. return x.value;
  16548. }));
  16549. });
  16550. };
  16551. async.reject = doParallel(_reject);
  16552. async.rejectSeries = doSeries(_reject);
  16553. var _detect = function (eachfn, arr, iterator, main_callback) {
  16554. eachfn(arr, function (x, callback) {
  16555. iterator(x, function (result) {
  16556. if (result) {
  16557. main_callback(x);
  16558. main_callback = function () {};
  16559. }
  16560. else {
  16561. callback();
  16562. }
  16563. });
  16564. }, function (err) {
  16565. main_callback();
  16566. });
  16567. };
  16568. async.detect = doParallel(_detect);
  16569. async.detectSeries = doSeries(_detect);
  16570. async.some = function (arr, iterator, main_callback) {
  16571. async.each(arr, function (x, callback) {
  16572. iterator(x, function (v) {
  16573. if (v) {
  16574. main_callback(true);
  16575. main_callback = function () {};
  16576. }
  16577. callback();
  16578. });
  16579. }, function (err) {
  16580. main_callback(false);
  16581. });
  16582. };
  16583. // any alias
  16584. async.any = async.some;
  16585. async.every = function (arr, iterator, main_callback) {
  16586. async.each(arr, function (x, callback) {
  16587. iterator(x, function (v) {
  16588. if (!v) {
  16589. main_callback(false);
  16590. main_callback = function () {};
  16591. }
  16592. callback();
  16593. });
  16594. }, function (err) {
  16595. main_callback(true);
  16596. });
  16597. };
  16598. // all alias
  16599. async.all = async.every;
  16600. async.sortBy = function (arr, iterator, callback) {
  16601. async.map(arr, function (x, callback) {
  16602. iterator(x, function (err, criteria) {
  16603. if (err) {
  16604. callback(err);
  16605. }
  16606. else {
  16607. callback(null, {value: x, criteria: criteria});
  16608. }
  16609. });
  16610. }, function (err, results) {
  16611. if (err) {
  16612. return callback(err);
  16613. }
  16614. else {
  16615. var fn = function (left, right) {
  16616. var a = left.criteria, b = right.criteria;
  16617. return a < b ? -1 : a > b ? 1 : 0;
  16618. };
  16619. callback(null, _map(results.sort(fn), function (x) {
  16620. return x.value;
  16621. }));
  16622. }
  16623. });
  16624. };
  16625. async.auto = function (tasks, callback) {
  16626. callback = callback || function () {};
  16627. var keys = _keys(tasks);
  16628. var remainingTasks = keys.length
  16629. if (!remainingTasks) {
  16630. return callback();
  16631. }
  16632. var results = {};
  16633. var listeners = [];
  16634. var addListener = function (fn) {
  16635. listeners.unshift(fn);
  16636. };
  16637. var removeListener = function (fn) {
  16638. for (var i = 0; i < listeners.length; i += 1) {
  16639. if (listeners[i] === fn) {
  16640. listeners.splice(i, 1);
  16641. return;
  16642. }
  16643. }
  16644. };
  16645. var taskComplete = function () {
  16646. remainingTasks--
  16647. _each(listeners.slice(0), function (fn) {
  16648. fn();
  16649. });
  16650. };
  16651. addListener(function () {
  16652. if (!remainingTasks) {
  16653. var theCallback = callback;
  16654. // prevent final callback from calling itself if it errors
  16655. callback = function () {};
  16656. theCallback(null, results);
  16657. }
  16658. });
  16659. _each(keys, function (k) {
  16660. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  16661. var taskCallback = function (err) {
  16662. var args = Array.prototype.slice.call(arguments, 1);
  16663. if (args.length <= 1) {
  16664. args = args[0];
  16665. }
  16666. if (err) {
  16667. var safeResults = {};
  16668. _each(_keys(results), function(rkey) {
  16669. safeResults[rkey] = results[rkey];
  16670. });
  16671. safeResults[k] = args;
  16672. callback(err, safeResults);
  16673. // stop subsequent errors hitting callback multiple times
  16674. callback = function () {};
  16675. }
  16676. else {
  16677. results[k] = args;
  16678. async.setImmediate(taskComplete);
  16679. }
  16680. };
  16681. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  16682. var ready = function () {
  16683. return _reduce(requires, function (a, x) {
  16684. return (a && results.hasOwnProperty(x));
  16685. }, true) && !results.hasOwnProperty(k);
  16686. };
  16687. if (ready()) {
  16688. task[task.length - 1](taskCallback, results);
  16689. }
  16690. else {
  16691. var listener = function () {
  16692. if (ready()) {
  16693. removeListener(listener);
  16694. task[task.length - 1](taskCallback, results);
  16695. }
  16696. };
  16697. addListener(listener);
  16698. }
  16699. });
  16700. };
  16701. async.retry = function(times, task, callback) {
  16702. var DEFAULT_TIMES = 5;
  16703. var attempts = [];
  16704. // Use defaults if times not passed
  16705. if (typeof times === 'function') {
  16706. callback = task;
  16707. task = times;
  16708. times = DEFAULT_TIMES;
  16709. }
  16710. // Make sure times is a number
  16711. times = parseInt(times, 10) || DEFAULT_TIMES;
  16712. var wrappedTask = function(wrappedCallback, wrappedResults) {
  16713. var retryAttempt = function(task, finalAttempt) {
  16714. return function(seriesCallback) {
  16715. task(function(err, result){
  16716. seriesCallback(!err || finalAttempt, {err: err, result: result});
  16717. }, wrappedResults);
  16718. };
  16719. };
  16720. while (times) {
  16721. attempts.push(retryAttempt(task, !(times-=1)));
  16722. }
  16723. async.series(attempts, function(done, data){
  16724. data = data[data.length - 1];
  16725. (wrappedCallback || callback)(data.err, data.result);
  16726. });
  16727. }
  16728. // If a callback is passed, run this as a controll flow
  16729. return callback ? wrappedTask() : wrappedTask
  16730. };
  16731. async.waterfall = function (tasks, callback) {
  16732. callback = callback || function () {};
  16733. if (!_isArray(tasks)) {
  16734. var err = new Error('First argument to waterfall must be an array of functions');
  16735. return callback(err);
  16736. }
  16737. if (!tasks.length) {
  16738. return callback();
  16739. }
  16740. var wrapIterator = function (iterator) {
  16741. return function (err) {
  16742. if (err) {
  16743. callback.apply(null, arguments);
  16744. callback = function () {};
  16745. }
  16746. else {
  16747. var args = Array.prototype.slice.call(arguments, 1);
  16748. var next = iterator.next();
  16749. if (next) {
  16750. args.push(wrapIterator(next));
  16751. }
  16752. else {
  16753. args.push(callback);
  16754. }
  16755. async.setImmediate(function () {
  16756. iterator.apply(null, args);
  16757. });
  16758. }
  16759. };
  16760. };
  16761. wrapIterator(async.iterator(tasks))();
  16762. };
  16763. var _parallel = function(eachfn, tasks, callback) {
  16764. callback = callback || function () {};
  16765. if (_isArray(tasks)) {
  16766. eachfn.map(tasks, function (fn, callback) {
  16767. if (fn) {
  16768. fn(function (err) {
  16769. var args = Array.prototype.slice.call(arguments, 1);
  16770. if (args.length <= 1) {
  16771. args = args[0];
  16772. }
  16773. callback.call(null, err, args);
  16774. });
  16775. }
  16776. }, callback);
  16777. }
  16778. else {
  16779. var results = {};
  16780. eachfn.each(_keys(tasks), function (k, callback) {
  16781. tasks[k](function (err) {
  16782. var args = Array.prototype.slice.call(arguments, 1);
  16783. if (args.length <= 1) {
  16784. args = args[0];
  16785. }
  16786. results[k] = args;
  16787. callback(err);
  16788. });
  16789. }, function (err) {
  16790. callback(err, results);
  16791. });
  16792. }
  16793. };
  16794. async.parallel = function (tasks, callback) {
  16795. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16796. };
  16797. async.parallelLimit = function(tasks, limit, callback) {
  16798. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16799. };
  16800. async.series = function (tasks, callback) {
  16801. callback = callback || function () {};
  16802. if (_isArray(tasks)) {
  16803. async.mapSeries(tasks, function (fn, callback) {
  16804. if (fn) {
  16805. fn(function (err) {
  16806. var args = Array.prototype.slice.call(arguments, 1);
  16807. if (args.length <= 1) {
  16808. args = args[0];
  16809. }
  16810. callback.call(null, err, args);
  16811. });
  16812. }
  16813. }, callback);
  16814. }
  16815. else {
  16816. var results = {};
  16817. async.eachSeries(_keys(tasks), function (k, callback) {
  16818. tasks[k](function (err) {
  16819. var args = Array.prototype.slice.call(arguments, 1);
  16820. if (args.length <= 1) {
  16821. args = args[0];
  16822. }
  16823. results[k] = args;
  16824. callback(err);
  16825. });
  16826. }, function (err) {
  16827. callback(err, results);
  16828. });
  16829. }
  16830. };
  16831. async.iterator = function (tasks) {
  16832. var makeCallback = function (index) {
  16833. var fn = function () {
  16834. if (tasks.length) {
  16835. tasks[index].apply(null, arguments);
  16836. }
  16837. return fn.next();
  16838. };
  16839. fn.next = function () {
  16840. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  16841. };
  16842. return fn;
  16843. };
  16844. return makeCallback(0);
  16845. };
  16846. async.apply = function (fn) {
  16847. var args = Array.prototype.slice.call(arguments, 1);
  16848. return function () {
  16849. return fn.apply(
  16850. null, args.concat(Array.prototype.slice.call(arguments))
  16851. );
  16852. };
  16853. };
  16854. var _concat = function (eachfn, arr, fn, callback) {
  16855. var r = [];
  16856. eachfn(arr, function (x, cb) {
  16857. fn(x, function (err, y) {
  16858. r = r.concat(y || []);
  16859. cb(err);
  16860. });
  16861. }, function (err) {
  16862. callback(err, r);
  16863. });
  16864. };
  16865. async.concat = doParallel(_concat);
  16866. async.concatSeries = doSeries(_concat);
  16867. async.whilst = function (test, iterator, callback) {
  16868. if (test()) {
  16869. iterator(function (err) {
  16870. if (err) {
  16871. return callback(err);
  16872. }
  16873. async.whilst(test, iterator, callback);
  16874. });
  16875. }
  16876. else {
  16877. callback();
  16878. }
  16879. };
  16880. async.doWhilst = function (iterator, test, callback) {
  16881. iterator(function (err) {
  16882. if (err) {
  16883. return callback(err);
  16884. }
  16885. var args = Array.prototype.slice.call(arguments, 1);
  16886. if (test.apply(null, args)) {
  16887. async.doWhilst(iterator, test, callback);
  16888. }
  16889. else {
  16890. callback();
  16891. }
  16892. });
  16893. };
  16894. async.until = function (test, iterator, callback) {
  16895. if (!test()) {
  16896. iterator(function (err) {
  16897. if (err) {
  16898. return callback(err);
  16899. }
  16900. async.until(test, iterator, callback);
  16901. });
  16902. }
  16903. else {
  16904. callback();
  16905. }
  16906. };
  16907. async.doUntil = function (iterator, test, callback) {
  16908. iterator(function (err) {
  16909. if (err) {
  16910. return callback(err);
  16911. }
  16912. var args = Array.prototype.slice.call(arguments, 1);
  16913. if (!test.apply(null, args)) {
  16914. async.doUntil(iterator, test, callback);
  16915. }
  16916. else {
  16917. callback();
  16918. }
  16919. });
  16920. };
  16921. async.queue = function (worker, concurrency) {
  16922. if (concurrency === undefined) {
  16923. concurrency = 1;
  16924. }
  16925. function _insert(q, data, pos, callback) {
  16926. if (!q.started){
  16927. q.started = true;
  16928. }
  16929. if (!_isArray(data)) {
  16930. data = [data];
  16931. }
  16932. if(data.length == 0) {
  16933. // call drain immediately if there are no tasks
  16934. return async.setImmediate(function() {
  16935. if (q.drain) {
  16936. q.drain();
  16937. }
  16938. });
  16939. }
  16940. _each(data, function(task) {
  16941. var item = {
  16942. data: task,
  16943. callback: typeof callback === 'function' ? callback : null
  16944. };
  16945. if (pos) {
  16946. q.tasks.unshift(item);
  16947. } else {
  16948. q.tasks.push(item);
  16949. }
  16950. if (q.saturated && q.tasks.length === q.concurrency) {
  16951. q.saturated();
  16952. }
  16953. async.setImmediate(q.process);
  16954. });
  16955. }
  16956. var workers = 0;
  16957. var q = {
  16958. tasks: [],
  16959. concurrency: concurrency,
  16960. saturated: null,
  16961. empty: null,
  16962. drain: null,
  16963. started: false,
  16964. paused: false,
  16965. push: function (data, callback) {
  16966. _insert(q, data, false, callback);
  16967. },
  16968. kill: function () {
  16969. q.drain = null;
  16970. q.tasks = [];
  16971. },
  16972. unshift: function (data, callback) {
  16973. _insert(q, data, true, callback);
  16974. },
  16975. process: function () {
  16976. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  16977. var task = q.tasks.shift();
  16978. if (q.empty && q.tasks.length === 0) {
  16979. q.empty();
  16980. }
  16981. workers += 1;
  16982. var next = function () {
  16983. workers -= 1;
  16984. if (task.callback) {
  16985. task.callback.apply(task, arguments);
  16986. }
  16987. if (q.drain && q.tasks.length + workers === 0) {
  16988. q.drain();
  16989. }
  16990. q.process();
  16991. };
  16992. var cb = only_once(next);
  16993. worker(task.data, cb);
  16994. }
  16995. },
  16996. length: function () {
  16997. return q.tasks.length;
  16998. },
  16999. running: function () {
  17000. return workers;
  17001. },
  17002. idle: function() {
  17003. return q.tasks.length + workers === 0;
  17004. },
  17005. pause: function () {
  17006. if (q.paused === true) { return; }
  17007. q.paused = true;
  17008. q.process();
  17009. },
  17010. resume: function () {
  17011. if (q.paused === false) { return; }
  17012. q.paused = false;
  17013. q.process();
  17014. }
  17015. };
  17016. return q;
  17017. };
  17018. async.priorityQueue = function (worker, concurrency) {
  17019. function _compareTasks(a, b){
  17020. return a.priority - b.priority;
  17021. };
  17022. function _binarySearch(sequence, item, compare) {
  17023. var beg = -1,
  17024. end = sequence.length - 1;
  17025. while (beg < end) {
  17026. var mid = beg + ((end - beg + 1) >>> 1);
  17027. if (compare(item, sequence[mid]) >= 0) {
  17028. beg = mid;
  17029. } else {
  17030. end = mid - 1;
  17031. }
  17032. }
  17033. return beg;
  17034. }
  17035. function _insert(q, data, priority, callback) {
  17036. if (!q.started){
  17037. q.started = true;
  17038. }
  17039. if (!_isArray(data)) {
  17040. data = [data];
  17041. }
  17042. if(data.length == 0) {
  17043. // call drain immediately if there are no tasks
  17044. return async.setImmediate(function() {
  17045. if (q.drain) {
  17046. q.drain();
  17047. }
  17048. });
  17049. }
  17050. _each(data, function(task) {
  17051. var item = {
  17052. data: task,
  17053. priority: priority,
  17054. callback: typeof callback === 'function' ? callback : null
  17055. };
  17056. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17057. if (q.saturated && q.tasks.length === q.concurrency) {
  17058. q.saturated();
  17059. }
  17060. async.setImmediate(q.process);
  17061. });
  17062. }
  17063. // Start with a normal queue
  17064. var q = async.queue(worker, concurrency);
  17065. // Override push to accept second parameter representing priority
  17066. q.push = function (data, priority, callback) {
  17067. _insert(q, data, priority, callback);
  17068. };
  17069. // Remove unshift function
  17070. delete q.unshift;
  17071. return q;
  17072. };
  17073. async.cargo = function (worker, payload) {
  17074. var working = false,
  17075. tasks = [];
  17076. var cargo = {
  17077. tasks: tasks,
  17078. payload: payload,
  17079. saturated: null,
  17080. empty: null,
  17081. drain: null,
  17082. drained: true,
  17083. push: function (data, callback) {
  17084. if (!_isArray(data)) {
  17085. data = [data];
  17086. }
  17087. _each(data, function(task) {
  17088. tasks.push({
  17089. data: task,
  17090. callback: typeof callback === 'function' ? callback : null
  17091. });
  17092. cargo.drained = false;
  17093. if (cargo.saturated && tasks.length === payload) {
  17094. cargo.saturated();
  17095. }
  17096. });
  17097. async.setImmediate(cargo.process);
  17098. },
  17099. process: function process() {
  17100. if (working) return;
  17101. if (tasks.length === 0) {
  17102. if(cargo.drain && !cargo.drained) cargo.drain();
  17103. cargo.drained = true;
  17104. return;
  17105. }
  17106. var ts = typeof payload === 'number'
  17107. ? tasks.splice(0, payload)
  17108. : tasks.splice(0, tasks.length);
  17109. var ds = _map(ts, function (task) {
  17110. return task.data;
  17111. });
  17112. if(cargo.empty) cargo.empty();
  17113. working = true;
  17114. worker(ds, function () {
  17115. working = false;
  17116. var args = arguments;
  17117. _each(ts, function (data) {
  17118. if (data.callback) {
  17119. data.callback.apply(null, args);
  17120. }
  17121. });
  17122. process();
  17123. });
  17124. },
  17125. length: function () {
  17126. return tasks.length;
  17127. },
  17128. running: function () {
  17129. return working;
  17130. }
  17131. };
  17132. return cargo;
  17133. };
  17134. var _console_fn = function (name) {
  17135. return function (fn) {
  17136. var args = Array.prototype.slice.call(arguments, 1);
  17137. fn.apply(null, args.concat([function (err) {
  17138. var args = Array.prototype.slice.call(arguments, 1);
  17139. if (typeof console !== 'undefined') {
  17140. if (err) {
  17141. if (console.error) {
  17142. console.error(err);
  17143. }
  17144. }
  17145. else if (console[name]) {
  17146. _each(args, function (x) {
  17147. console[name](x);
  17148. });
  17149. }
  17150. }
  17151. }]));
  17152. };
  17153. };
  17154. async.log = _console_fn('log');
  17155. async.dir = _console_fn('dir');
  17156. /*async.info = _console_fn('info');
  17157. async.warn = _console_fn('warn');
  17158. async.error = _console_fn('error');*/
  17159. async.memoize = function (fn, hasher) {
  17160. var memo = {};
  17161. var queues = {};
  17162. hasher = hasher || function (x) {
  17163. return x;
  17164. };
  17165. var memoized = function () {
  17166. var args = Array.prototype.slice.call(arguments);
  17167. var callback = args.pop();
  17168. var key = hasher.apply(null, args);
  17169. if (key in memo) {
  17170. async.nextTick(function () {
  17171. callback.apply(null, memo[key]);
  17172. });
  17173. }
  17174. else if (key in queues) {
  17175. queues[key].push(callback);
  17176. }
  17177. else {
  17178. queues[key] = [callback];
  17179. fn.apply(null, args.concat([function () {
  17180. memo[key] = arguments;
  17181. var q = queues[key];
  17182. delete queues[key];
  17183. for (var i = 0, l = q.length; i < l; i++) {
  17184. q[i].apply(null, arguments);
  17185. }
  17186. }]));
  17187. }
  17188. };
  17189. memoized.memo = memo;
  17190. memoized.unmemoized = fn;
  17191. return memoized;
  17192. };
  17193. async.unmemoize = function (fn) {
  17194. return function () {
  17195. return (fn.unmemoized || fn).apply(null, arguments);
  17196. };
  17197. };
  17198. async.times = function (count, iterator, callback) {
  17199. var counter = [];
  17200. for (var i = 0; i < count; i++) {
  17201. counter.push(i);
  17202. }
  17203. return async.map(counter, iterator, callback);
  17204. };
  17205. async.timesSeries = function (count, iterator, callback) {
  17206. var counter = [];
  17207. for (var i = 0; i < count; i++) {
  17208. counter.push(i);
  17209. }
  17210. return async.mapSeries(counter, iterator, callback);
  17211. };
  17212. async.seq = function (/* functions... */) {
  17213. var fns = arguments;
  17214. return function () {
  17215. var that = this;
  17216. var args = Array.prototype.slice.call(arguments);
  17217. var callback = args.pop();
  17218. async.reduce(fns, args, function (newargs, fn, cb) {
  17219. fn.apply(that, newargs.concat([function () {
  17220. var err = arguments[0];
  17221. var nextargs = Array.prototype.slice.call(arguments, 1);
  17222. cb(err, nextargs);
  17223. }]))
  17224. },
  17225. function (err, results) {
  17226. callback.apply(that, [err].concat(results));
  17227. });
  17228. };
  17229. };
  17230. async.compose = function (/* functions... */) {
  17231. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17232. };
  17233. var _applyEach = function (eachfn, fns /*args...*/) {
  17234. var go = function () {
  17235. var that = this;
  17236. var args = Array.prototype.slice.call(arguments);
  17237. var callback = args.pop();
  17238. return eachfn(fns, function (fn, cb) {
  17239. fn.apply(that, args.concat([cb]));
  17240. },
  17241. callback);
  17242. };
  17243. if (arguments.length > 2) {
  17244. var args = Array.prototype.slice.call(arguments, 2);
  17245. return go.apply(this, args);
  17246. }
  17247. else {
  17248. return go;
  17249. }
  17250. };
  17251. async.applyEach = doParallel(_applyEach);
  17252. async.applyEachSeries = doSeries(_applyEach);
  17253. async.forever = function (fn, callback) {
  17254. function next(err) {
  17255. if (err) {
  17256. if (callback) {
  17257. return callback(err);
  17258. }
  17259. throw err;
  17260. }
  17261. fn(next);
  17262. }
  17263. next();
  17264. };
  17265. // Node.js
  17266. if (typeof module !== 'undefined' && module.exports) {
  17267. module.exports = async;
  17268. }
  17269. // AMD / RequireJS
  17270. else if (typeof define !== 'undefined' && define.amd) {
  17271. define([], function () {
  17272. return async;
  17273. });
  17274. }
  17275. // included directly via <script> tag
  17276. else {
  17277. root.async = async;
  17278. }
  17279. }());
  17280. }).call(this,require('_process'))
  17281. },{"_process":110}],68:[function(require,module,exports){
  17282. // i18next, v1.7.7
  17283. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17284. // Distributed under MIT license
  17285. // http://i18next.com
  17286. (function() {
  17287. // add indexOf to non ECMA-262 standard compliant browsers
  17288. if (!Array.prototype.indexOf) {
  17289. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17290. "use strict";
  17291. if (this == null) {
  17292. throw new TypeError();
  17293. }
  17294. var t = Object(this);
  17295. var len = t.length >>> 0;
  17296. if (len === 0) {
  17297. return -1;
  17298. }
  17299. var n = 0;
  17300. if (arguments.length > 0) {
  17301. n = Number(arguments[1]);
  17302. if (n != n) { // shortcut for verifying if it's NaN
  17303. n = 0;
  17304. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17305. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17306. }
  17307. }
  17308. if (n >= len) {
  17309. return -1;
  17310. }
  17311. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17312. for (; k < len; k++) {
  17313. if (k in t && t[k] === searchElement) {
  17314. return k;
  17315. }
  17316. }
  17317. return -1;
  17318. }
  17319. }
  17320. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17321. if (!Array.prototype.lastIndexOf) {
  17322. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17323. "use strict";
  17324. if (this == null) {
  17325. throw new TypeError();
  17326. }
  17327. var t = Object(this);
  17328. var len = t.length >>> 0;
  17329. if (len === 0) {
  17330. return -1;
  17331. }
  17332. var n = len;
  17333. if (arguments.length > 1) {
  17334. n = Number(arguments[1]);
  17335. if (n != n) {
  17336. n = 0;
  17337. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17338. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17339. }
  17340. }
  17341. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17342. for (; k >= 0; k--) {
  17343. if (k in t && t[k] === searchElement) {
  17344. return k;
  17345. }
  17346. }
  17347. return -1;
  17348. };
  17349. }
  17350. // Add string trim for IE8.
  17351. if (typeof String.prototype.trim !== 'function') {
  17352. String.prototype.trim = function() {
  17353. return this.replace(/^\s+|\s+$/g, '');
  17354. }
  17355. }
  17356. var root = this
  17357. , $ = root.jQuery || root.Zepto
  17358. , i18n = {}
  17359. , resStore = {}
  17360. , currentLng
  17361. , replacementCounter = 0
  17362. , languages = []
  17363. , initialized = false
  17364. , sync = {};
  17365. // Export the i18next object for **CommonJS**.
  17366. // If we're not in CommonJS, add `i18n` to the
  17367. // global object or to jquery.
  17368. if (typeof module !== 'undefined' && module.exports) {
  17369. if (!$) {
  17370. try {
  17371. $ = require('jquery');
  17372. } catch(e) {
  17373. // just ignore
  17374. }
  17375. }
  17376. if ($) {
  17377. $.i18n = $.i18n || i18n;
  17378. }
  17379. module.exports = i18n;
  17380. } else {
  17381. if ($) {
  17382. $.i18n = $.i18n || i18n;
  17383. }
  17384. root.i18n = root.i18n || i18n;
  17385. }
  17386. sync = {
  17387. load: function(lngs, options, cb) {
  17388. if (options.useLocalStorage) {
  17389. sync._loadLocal(lngs, options, function(err, store) {
  17390. var missingLngs = [];
  17391. for (var i = 0, len = lngs.length; i < len; i++) {
  17392. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17393. }
  17394. if (missingLngs.length > 0) {
  17395. sync._fetch(missingLngs, options, function(err, fetched) {
  17396. f.extend(store, fetched);
  17397. sync._storeLocal(fetched);
  17398. cb(null, store);
  17399. });
  17400. } else {
  17401. cb(null, store);
  17402. }
  17403. });
  17404. } else {
  17405. sync._fetch(lngs, options, function(err, store){
  17406. cb(null, store);
  17407. });
  17408. }
  17409. },
  17410. _loadLocal: function(lngs, options, cb) {
  17411. var store = {}
  17412. , nowMS = new Date().getTime();
  17413. if(window.localStorage) {
  17414. var todo = lngs.length;
  17415. f.each(lngs, function(key, lng) {
  17416. var local = window.localStorage.getItem('res_' + lng);
  17417. if (local) {
  17418. local = JSON.parse(local);
  17419. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17420. store[lng] = local;
  17421. }
  17422. }
  17423. todo--; // wait for all done befor callback
  17424. if (todo === 0) cb(null, store);
  17425. });
  17426. }
  17427. },
  17428. _storeLocal: function(store) {
  17429. if(window.localStorage) {
  17430. for (var m in store) {
  17431. store[m].i18nStamp = new Date().getTime();
  17432. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17433. }
  17434. }
  17435. return;
  17436. },
  17437. _fetch: function(lngs, options, cb) {
  17438. var ns = options.ns
  17439. , store = {};
  17440. if (!options.dynamicLoad) {
  17441. var todo = ns.namespaces.length * lngs.length
  17442. , errors;
  17443. // load each file individual
  17444. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17445. f.each(lngs, function(lngIndex, lngValue) {
  17446. // Call this once our translation has returned.
  17447. var loadComplete = function(err, data) {
  17448. if (err) {
  17449. errors = errors || [];
  17450. errors.push(err);
  17451. }
  17452. store[lngValue] = store[lngValue] || {};
  17453. store[lngValue][nsValue] = data;
  17454. todo--; // wait for all done befor callback
  17455. if (todo === 0) cb(errors, store);
  17456. };
  17457. if(typeof options.customLoad == 'function'){
  17458. // Use the specified custom callback.
  17459. options.customLoad(lngValue, nsValue, options, loadComplete);
  17460. } else {
  17461. //~ // Use our inbuilt sync.
  17462. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17463. }
  17464. });
  17465. });
  17466. } else {
  17467. // Call this once our translation has returned.
  17468. var loadComplete = function(err, data) {
  17469. cb(null, data);
  17470. };
  17471. if(typeof options.customLoad == 'function'){
  17472. // Use the specified custom callback.
  17473. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17474. } else {
  17475. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17476. // load all needed stuff once
  17477. f.ajax({
  17478. url: url,
  17479. success: function(data, status, xhr) {
  17480. f.log('loaded: ' + url);
  17481. loadComplete(null, data);
  17482. },
  17483. error : function(xhr, status, error) {
  17484. f.log('failed loading: ' + url);
  17485. loadComplete('failed loading resource.json error: ' + error);
  17486. },
  17487. dataType: "json",
  17488. async : options.getAsync
  17489. });
  17490. }
  17491. }
  17492. },
  17493. _fetchOne: function(lng, ns, options, done) {
  17494. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17495. f.ajax({
  17496. url: url,
  17497. success: function(data, status, xhr) {
  17498. f.log('loaded: ' + url);
  17499. done(null, data);
  17500. },
  17501. error : function(xhr, status, error) {
  17502. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17503. // file loaded but invalid json, stop waste time !
  17504. f.error('There is a typo in: ' + url);
  17505. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17506. f.log('Does not exist: ' + url);
  17507. } else {
  17508. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17509. f.log(theStatus + ' when loading ' + url);
  17510. }
  17511. done(error, {});
  17512. },
  17513. dataType: "json",
  17514. async : options.getAsync
  17515. });
  17516. },
  17517. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17518. var payload = {};
  17519. payload[key] = defaultValue;
  17520. var urls = [];
  17521. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17522. for (var i = 0; i < o.fallbackLng.length; i++) {
  17523. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17524. }
  17525. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17526. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17527. } else if (o.sendMissingTo === 'all') {
  17528. for (var i = 0, l = lngs.length; i < l; i++) {
  17529. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17530. }
  17531. }
  17532. for (var y = 0, len = urls.length; y < len; y++) {
  17533. var item = urls[y];
  17534. f.ajax({
  17535. url: item.url,
  17536. type: o.sendType,
  17537. data: payload,
  17538. success: function(data, status, xhr) {
  17539. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17540. // add key to resStore
  17541. var keys = key.split('.');
  17542. var x = 0;
  17543. var value = resStore[item.lng][ns];
  17544. while (keys[x]) {
  17545. if (x === keys.length - 1) {
  17546. value = value[keys[x]] = defaultValue;
  17547. } else {
  17548. value = value[keys[x]] = value[keys[x]] || {};
  17549. }
  17550. x++;
  17551. }
  17552. },
  17553. error : function(xhr, status, error) {
  17554. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17555. },
  17556. dataType: "json",
  17557. async : o.postAsync
  17558. });
  17559. }
  17560. },
  17561. reload: reload
  17562. };
  17563. // defaults
  17564. var o = {
  17565. lng: undefined,
  17566. load: 'all',
  17567. preload: [],
  17568. lowerCaseLng: false,
  17569. returnObjectTrees: false,
  17570. fallbackLng: ['dev'],
  17571. fallbackNS: [],
  17572. detectLngQS: 'setLng',
  17573. detectLngFromLocalStorage: false,
  17574. ns: 'translation',
  17575. fallbackOnNull: true,
  17576. fallbackOnEmpty: false,
  17577. fallbackToDefaultNS: false,
  17578. nsseparator: ':',
  17579. keyseparator: '.',
  17580. selectorAttr: 'data-i18n',
  17581. debug: false,
  17582. resGetPath: 'locales/__lng__/__ns__.json',
  17583. resPostPath: 'locales/add/__lng__/__ns__',
  17584. getAsync: true,
  17585. postAsync: true,
  17586. resStore: undefined,
  17587. useLocalStorage: false,
  17588. localStorageExpirationTime: 7*24*60*60*1000,
  17589. dynamicLoad: false,
  17590. sendMissing: false,
  17591. sendMissingTo: 'fallback', // current | all
  17592. sendType: 'POST',
  17593. interpolationPrefix: '__',
  17594. interpolationSuffix: '__',
  17595. defaultVariables: false,
  17596. reusePrefix: '$t(',
  17597. reuseSuffix: ')',
  17598. pluralSuffix: '_plural',
  17599. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17600. contextNotFound: ['context_not_found', Math.random()].join(''),
  17601. escapeInterpolation: false,
  17602. indefiniteSuffix: '_indefinite',
  17603. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17604. setJqueryExt: true,
  17605. defaultValueFromContent: true,
  17606. useDataAttrOptions: false,
  17607. cookieExpirationTime: undefined,
  17608. useCookie: true,
  17609. cookieName: 'i18next',
  17610. cookieDomain: undefined,
  17611. objectTreeKeyHandler: undefined,
  17612. postProcess: undefined,
  17613. parseMissingKey: undefined,
  17614. missingKeyHandler: sync.postMissing,
  17615. shortcutFunction: 'sprintf' // or: defaultValue
  17616. };
  17617. function _extend(target, source) {
  17618. if (!source || typeof source === 'function') {
  17619. return target;
  17620. }
  17621. for (var attr in source) { target[attr] = source[attr]; }
  17622. return target;
  17623. }
  17624. function _deepExtend(target, source) {
  17625. for (var prop in source)
  17626. if (prop in target)
  17627. _deepExtend(target[prop], source[prop]);
  17628. else
  17629. target[prop] = source[prop];
  17630. return target;
  17631. }
  17632. function _each(object, callback, args) {
  17633. var name, i = 0,
  17634. length = object.length,
  17635. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17636. if (args) {
  17637. if (isObj) {
  17638. for (name in object) {
  17639. if (callback.apply(object[name], args) === false) {
  17640. break;
  17641. }
  17642. }
  17643. } else {
  17644. for ( ; i < length; ) {
  17645. if (callback.apply(object[i++], args) === false) {
  17646. break;
  17647. }
  17648. }
  17649. }
  17650. // A special, fast, case for the most common use of each
  17651. } else {
  17652. if (isObj) {
  17653. for (name in object) {
  17654. if (callback.call(object[name], name, object[name]) === false) {
  17655. break;
  17656. }
  17657. }
  17658. } else {
  17659. for ( ; i < length; ) {
  17660. if (callback.call(object[i], i, object[i++]) === false) {
  17661. break;
  17662. }
  17663. }
  17664. }
  17665. }
  17666. return object;
  17667. }
  17668. var _entityMap = {
  17669. "&": "&amp;",
  17670. "<": "&lt;",
  17671. ">": "&gt;",
  17672. '"': '&quot;',
  17673. "'": '&#39;',
  17674. "/": '&#x2F;'
  17675. };
  17676. function _escape(data) {
  17677. if (typeof data === 'string') {
  17678. return data.replace(/[&<>"'\/]/g, function (s) {
  17679. return _entityMap[s];
  17680. });
  17681. }else{
  17682. return data;
  17683. }
  17684. }
  17685. function _ajax(options) {
  17686. // v0.5.0 of https://github.com/goloroden/http.js
  17687. var getXhr = function (callback) {
  17688. // Use the native XHR object if the browser supports it.
  17689. if (window.XMLHttpRequest) {
  17690. return callback(null, new XMLHttpRequest());
  17691. } else if (window.ActiveXObject) {
  17692. // In Internet Explorer check for ActiveX versions of the XHR object.
  17693. try {
  17694. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  17695. } catch (e) {
  17696. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  17697. }
  17698. }
  17699. // If no XHR support was found, throw an error.
  17700. return callback(new Error());
  17701. };
  17702. var encodeUsingUrlEncoding = function (data) {
  17703. if(typeof data === 'string') {
  17704. return data;
  17705. }
  17706. var result = [];
  17707. for(var dataItem in data) {
  17708. if(data.hasOwnProperty(dataItem)) {
  17709. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  17710. }
  17711. }
  17712. return result.join('&');
  17713. };
  17714. var utf8 = function (text) {
  17715. text = text.replace(/\r\n/g, '\n');
  17716. var result = '';
  17717. for(var i = 0; i < text.length; i++) {
  17718. var c = text.charCodeAt(i);
  17719. if(c < 128) {
  17720. result += String.fromCharCode(c);
  17721. } else if((c > 127) && (c < 2048)) {
  17722. result += String.fromCharCode((c >> 6) | 192);
  17723. result += String.fromCharCode((c & 63) | 128);
  17724. } else {
  17725. result += String.fromCharCode((c >> 12) | 224);
  17726. result += String.fromCharCode(((c >> 6) & 63) | 128);
  17727. result += String.fromCharCode((c & 63) | 128);
  17728. }
  17729. }
  17730. return result;
  17731. };
  17732. var base64 = function (text) {
  17733. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17734. text = utf8(text);
  17735. var result = '',
  17736. chr1, chr2, chr3,
  17737. enc1, enc2, enc3, enc4,
  17738. i = 0;
  17739. do {
  17740. chr1 = text.charCodeAt(i++);
  17741. chr2 = text.charCodeAt(i++);
  17742. chr3 = text.charCodeAt(i++);
  17743. enc1 = chr1 >> 2;
  17744. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  17745. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  17746. enc4 = chr3 & 63;
  17747. if(isNaN(chr2)) {
  17748. enc3 = enc4 = 64;
  17749. } else if(isNaN(chr3)) {
  17750. enc4 = 64;
  17751. }
  17752. result +=
  17753. keyStr.charAt(enc1) +
  17754. keyStr.charAt(enc2) +
  17755. keyStr.charAt(enc3) +
  17756. keyStr.charAt(enc4);
  17757. chr1 = chr2 = chr3 = '';
  17758. enc1 = enc2 = enc3 = enc4 = '';
  17759. } while(i < text.length);
  17760. return result;
  17761. };
  17762. var mergeHeaders = function () {
  17763. // Use the first header object as base.
  17764. var result = arguments[0];
  17765. // Iterate through the remaining header objects and add them.
  17766. for(var i = 1; i < arguments.length; i++) {
  17767. var currentHeaders = arguments[i];
  17768. for(var header in currentHeaders) {
  17769. if(currentHeaders.hasOwnProperty(header)) {
  17770. result[header] = currentHeaders[header];
  17771. }
  17772. }
  17773. }
  17774. // Return the merged headers.
  17775. return result;
  17776. };
  17777. var ajax = function (method, url, options, callback) {
  17778. // Adjust parameters.
  17779. if(typeof options === 'function') {
  17780. callback = options;
  17781. options = {};
  17782. }
  17783. // Set default parameter values.
  17784. options.cache = options.cache || false;
  17785. options.data = options.data || {};
  17786. options.headers = options.headers || {};
  17787. options.jsonp = options.jsonp || false;
  17788. options.async = options.async === undefined ? true : options.async;
  17789. // Merge the various header objects.
  17790. var headers = mergeHeaders({
  17791. 'accept': '*/*',
  17792. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  17793. }, ajax.headers, options.headers);
  17794. // Encode the data according to the content-type.
  17795. var payload;
  17796. if (headers['content-type'] === 'application/json') {
  17797. payload = JSON.stringify(options.data);
  17798. } else {
  17799. payload = encodeUsingUrlEncoding(options.data);
  17800. }
  17801. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17802. // if neccessary.
  17803. if(method === 'GET') {
  17804. // Setup the query string.
  17805. var queryString = [];
  17806. if(payload) {
  17807. queryString.push(payload);
  17808. payload = null;
  17809. }
  17810. // Handle caching.
  17811. if(!options.cache) {
  17812. queryString.push('_=' + (new Date()).getTime());
  17813. }
  17814. // If neccessary prepare the query string for a JSONP call.
  17815. if(options.jsonp) {
  17816. queryString.push('callback=' + options.jsonp);
  17817. queryString.push('jsonp=' + options.jsonp);
  17818. }
  17819. // Merge the query string and attach it to the url.
  17820. queryString = queryString.join('&');
  17821. if (queryString.length > 1) {
  17822. if (url.indexOf('?') > -1) {
  17823. url += '&' + queryString;
  17824. } else {
  17825. url += '?' + queryString;
  17826. }
  17827. }
  17828. // Make a JSONP call if neccessary.
  17829. if(options.jsonp) {
  17830. var head = document.getElementsByTagName('head')[0];
  17831. var script = document.createElement('script');
  17832. script.type = 'text/javascript';
  17833. script.src = url;
  17834. head.appendChild(script);
  17835. return;
  17836. }
  17837. }
  17838. // Since we got here, it is no JSONP request, so make a normal XHR request.
  17839. getXhr(function (err, xhr) {
  17840. if(err) return callback(err);
  17841. // Open the request.
  17842. xhr.open(method, url, options.async);
  17843. // Set the request headers.
  17844. for(var header in headers) {
  17845. if(headers.hasOwnProperty(header)) {
  17846. xhr.setRequestHeader(header, headers[header]);
  17847. }
  17848. }
  17849. // Handle the request events.
  17850. xhr.onreadystatechange = function () {
  17851. if(xhr.readyState === 4) {
  17852. var data = xhr.responseText || '';
  17853. // If no callback is given, return.
  17854. if(!callback) {
  17855. return;
  17856. }
  17857. // Return an object that provides access to the data as text and JSON.
  17858. callback(xhr.status, {
  17859. text: function () {
  17860. return data;
  17861. },
  17862. json: function () {
  17863. try {
  17864. return JSON.parse(data)
  17865. } catch (e) {
  17866. f.error('Can not parse JSON. URL: ' + url);
  17867. return {};
  17868. }
  17869. }
  17870. });
  17871. }
  17872. };
  17873. // Actually send the XHR request.
  17874. xhr.send(payload);
  17875. });
  17876. };
  17877. // Define the external interface.
  17878. var http = {
  17879. authBasic: function (username, password) {
  17880. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  17881. },
  17882. connect: function (url, options, callback) {
  17883. return ajax('CONNECT', url, options, callback);
  17884. },
  17885. del: function (url, options, callback) {
  17886. return ajax('DELETE', url, options, callback);
  17887. },
  17888. get: function (url, options, callback) {
  17889. return ajax('GET', url, options, callback);
  17890. },
  17891. head: function (url, options, callback) {
  17892. return ajax('HEAD', url, options, callback);
  17893. },
  17894. headers: function (headers) {
  17895. ajax.headers = headers || {};
  17896. },
  17897. isAllowed: function (url, verb, callback) {
  17898. this.options(url, function (status, data) {
  17899. callback(data.text().indexOf(verb) !== -1);
  17900. });
  17901. },
  17902. options: function (url, options, callback) {
  17903. return ajax('OPTIONS', url, options, callback);
  17904. },
  17905. patch: function (url, options, callback) {
  17906. return ajax('PATCH', url, options, callback);
  17907. },
  17908. post: function (url, options, callback) {
  17909. return ajax('POST', url, options, callback);
  17910. },
  17911. put: function (url, options, callback) {
  17912. return ajax('PUT', url, options, callback);
  17913. },
  17914. trace: function (url, options, callback) {
  17915. return ajax('TRACE', url, options, callback);
  17916. }
  17917. };
  17918. var methode = options.type ? options.type.toLowerCase() : 'get';
  17919. http[methode](options.url, options, function (status, data) {
  17920. // file: protocol always gives status code 0, so check for data
  17921. if (status === 200 || (status === 0 && data.text())) {
  17922. options.success(data.json(), status, null);
  17923. } else {
  17924. options.error(data.text(), status, null);
  17925. }
  17926. });
  17927. }
  17928. var _cookie = {
  17929. create: function(name,value,minutes,domain) {
  17930. var expires;
  17931. if (minutes) {
  17932. var date = new Date();
  17933. date.setTime(date.getTime()+(minutes*60*1000));
  17934. expires = "; expires="+date.toGMTString();
  17935. }
  17936. else expires = "";
  17937. domain = (domain)? "domain="+domain+";" : "";
  17938. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  17939. },
  17940. read: function(name) {
  17941. var nameEQ = name + "=";
  17942. var ca = document.cookie.split(';');
  17943. for(var i=0;i < ca.length;i++) {
  17944. var c = ca[i];
  17945. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  17946. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  17947. }
  17948. return null;
  17949. },
  17950. remove: function(name) {
  17951. this.create(name,"",-1);
  17952. }
  17953. };
  17954. var cookie_noop = {
  17955. create: function(name,value,minutes,domain) {},
  17956. read: function(name) { return null; },
  17957. remove: function(name) {}
  17958. };
  17959. // move dependent functions to a container so that
  17960. // they can be overriden easier in no jquery environment (node.js)
  17961. var f = {
  17962. extend: $ ? $.extend : _extend,
  17963. deepExtend: _deepExtend,
  17964. each: $ ? $.each : _each,
  17965. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  17966. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  17967. detectLanguage: detectLanguage,
  17968. escape: _escape,
  17969. log: function(str) {
  17970. if (o.debug && typeof console !== "undefined") console.log(str);
  17971. },
  17972. error: function(str) {
  17973. if (typeof console !== "undefined") console.error(str);
  17974. },
  17975. getCountyIndexOfLng: function(lng) {
  17976. var lng_index = 0;
  17977. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  17978. return lng_index;
  17979. },
  17980. toLanguages: function(lng) {
  17981. var log = this.log;
  17982. function applyCase(l) {
  17983. var ret = l;
  17984. if (typeof l === 'string' && l.indexOf('-') > -1) {
  17985. var parts = l.split('-');
  17986. ret = o.lowerCaseLng ?
  17987. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17988. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17989. } else {
  17990. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  17991. }
  17992. return ret;
  17993. }
  17994. var languages = [];
  17995. var whitelist = o.lngWhitelist || false;
  17996. var addLanguage = function(language){
  17997. //reject langs not whitelisted
  17998. if(!whitelist || whitelist.indexOf(language) > -1){
  17999. languages.push(language);
  18000. }else{
  18001. log('rejecting non-whitelisted language: ' + language);
  18002. }
  18003. };
  18004. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18005. var parts = lng.split('-');
  18006. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18007. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18008. } else {
  18009. addLanguage(applyCase(lng));
  18010. }
  18011. for (var i = 0; i < o.fallbackLng.length; i++) {
  18012. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18013. }
  18014. return languages;
  18015. },
  18016. regexEscape: function(str) {
  18017. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18018. },
  18019. regexReplacementEscape: function(strOrFn) {
  18020. if (typeof strOrFn === 'string') {
  18021. return strOrFn.replace(/\$/g, "$$$$");
  18022. } else {
  18023. return strOrFn;
  18024. }
  18025. },
  18026. localStorage: {
  18027. setItem: function(key, value) {
  18028. if (window.localStorage) {
  18029. try {
  18030. window.localStorage.setItem(key, value);
  18031. } catch (e) {
  18032. f.log('failed to set value for key "' + key + '" to localStorage.');
  18033. }
  18034. }
  18035. }
  18036. }
  18037. };
  18038. function init(options, cb) {
  18039. if (typeof options === 'function') {
  18040. cb = options;
  18041. options = {};
  18042. }
  18043. options = options || {};
  18044. // override defaults with passed in options
  18045. f.extend(o, options);
  18046. delete o.fixLng; /* passed in each time */
  18047. // override functions: .log(), .detectLanguage(), etc
  18048. if (o.functions) {
  18049. delete o.functions;
  18050. f.extend(f, options.functions);
  18051. }
  18052. // create namespace object if namespace is passed in as string
  18053. if (typeof o.ns == 'string') {
  18054. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18055. }
  18056. // fallback namespaces
  18057. if (typeof o.fallbackNS == 'string') {
  18058. o.fallbackNS = [o.fallbackNS];
  18059. }
  18060. // fallback languages
  18061. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18062. o.fallbackLng = [o.fallbackLng];
  18063. }
  18064. // escape prefix/suffix
  18065. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18066. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18067. if (!o.lng) o.lng = f.detectLanguage();
  18068. languages = f.toLanguages(o.lng);
  18069. currentLng = languages[0];
  18070. f.log('currentLng set to: ' + currentLng);
  18071. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18072. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18073. }
  18074. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18075. f.localStorage.setItem('i18next_lng', currentLng);
  18076. }
  18077. var lngTranslate = translate;
  18078. if (options.fixLng) {
  18079. lngTranslate = function(key, options) {
  18080. options = options || {};
  18081. options.lng = options.lng || lngTranslate.lng;
  18082. return translate(key, options);
  18083. };
  18084. lngTranslate.lng = currentLng;
  18085. }
  18086. pluralExtensions.setCurrentLng(currentLng);
  18087. // add JQuery extensions
  18088. if ($ && o.setJqueryExt) addJqueryFunct();
  18089. // jQuery deferred
  18090. var deferred;
  18091. if ($ && $.Deferred) {
  18092. deferred = $.Deferred();
  18093. }
  18094. // return immidiatly if res are passed in
  18095. if (o.resStore) {
  18096. resStore = o.resStore;
  18097. initialized = true;
  18098. if (cb) cb(lngTranslate);
  18099. if (deferred) deferred.resolve(lngTranslate);
  18100. if (deferred) return deferred.promise();
  18101. return;
  18102. }
  18103. // languages to load
  18104. var lngsToLoad = f.toLanguages(o.lng);
  18105. if (typeof o.preload === 'string') o.preload = [o.preload];
  18106. for (var i = 0, l = o.preload.length; i < l; i++) {
  18107. var pres = f.toLanguages(o.preload[i]);
  18108. for (var y = 0, len = pres.length; y < len; y++) {
  18109. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18110. lngsToLoad.push(pres[y]);
  18111. }
  18112. }
  18113. }
  18114. // else load them
  18115. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18116. resStore = store;
  18117. initialized = true;
  18118. if (cb) cb(lngTranslate);
  18119. if (deferred) deferred.resolve(lngTranslate);
  18120. });
  18121. if (deferred) return deferred.promise();
  18122. }
  18123. function preload(lngs, cb) {
  18124. if (typeof lngs === 'string') lngs = [lngs];
  18125. for (var i = 0, l = lngs.length; i < l; i++) {
  18126. if (o.preload.indexOf(lngs[i]) < 0) {
  18127. o.preload.push(lngs[i]);
  18128. }
  18129. }
  18130. return init(cb);
  18131. }
  18132. function addResourceBundle(lng, ns, resources, deep) {
  18133. if (typeof ns !== 'string') {
  18134. resources = ns;
  18135. ns = o.ns.defaultNs;
  18136. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18137. o.ns.namespaces.push(ns);
  18138. }
  18139. resStore[lng] = resStore[lng] || {};
  18140. resStore[lng][ns] = resStore[lng][ns] || {};
  18141. if (deep) {
  18142. f.deepExtend(resStore[lng][ns], resources);
  18143. } else {
  18144. f.extend(resStore[lng][ns], resources);
  18145. }
  18146. }
  18147. function hasResourceBundle(lng, ns) {
  18148. if (typeof ns !== 'string') {
  18149. ns = o.ns.defaultNs;
  18150. }
  18151. resStore[lng] = resStore[lng] || {};
  18152. var res = resStore[lng][ns] || {};
  18153. var hasValues = false;
  18154. for(var prop in res) {
  18155. if (res.hasOwnProperty(prop)) {
  18156. hasValues = true;
  18157. }
  18158. }
  18159. return hasValues;
  18160. }
  18161. function removeResourceBundle(lng, ns) {
  18162. if (typeof ns !== 'string') {
  18163. ns = o.ns.defaultNs;
  18164. }
  18165. resStore[lng] = resStore[lng] || {};
  18166. resStore[lng][ns] = {};
  18167. }
  18168. function addResource(lng, ns, key, value) {
  18169. if (typeof ns !== 'string') {
  18170. resource = ns;
  18171. ns = o.ns.defaultNs;
  18172. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18173. o.ns.namespaces.push(ns);
  18174. }
  18175. resStore[lng] = resStore[lng] || {};
  18176. resStore[lng][ns] = resStore[lng][ns] || {};
  18177. var keys = key.split(o.keyseparator);
  18178. var x = 0;
  18179. var node = resStore[lng][ns];
  18180. var origRef = node;
  18181. while (keys[x]) {
  18182. if (x == keys.length - 1)
  18183. node[keys[x]] = value;
  18184. else {
  18185. if (node[keys[x]] == null)
  18186. node[keys[x]] = {};
  18187. node = node[keys[x]];
  18188. }
  18189. x++;
  18190. }
  18191. }
  18192. function addResources(lng, ns, resources) {
  18193. if (typeof ns !== 'string') {
  18194. resource = ns;
  18195. ns = o.ns.defaultNs;
  18196. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18197. o.ns.namespaces.push(ns);
  18198. }
  18199. for (var m in resources) {
  18200. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18201. }
  18202. }
  18203. function setDefaultNamespace(ns) {
  18204. o.ns.defaultNs = ns;
  18205. }
  18206. function loadNamespace(namespace, cb) {
  18207. loadNamespaces([namespace], cb);
  18208. }
  18209. function loadNamespaces(namespaces, cb) {
  18210. var opts = {
  18211. dynamicLoad: o.dynamicLoad,
  18212. resGetPath: o.resGetPath,
  18213. getAsync: o.getAsync,
  18214. customLoad: o.customLoad,
  18215. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18216. };
  18217. // languages to load
  18218. var lngsToLoad = f.toLanguages(o.lng);
  18219. if (typeof o.preload === 'string') o.preload = [o.preload];
  18220. for (var i = 0, l = o.preload.length; i < l; i++) {
  18221. var pres = f.toLanguages(o.preload[i]);
  18222. for (var y = 0, len = pres.length; y < len; y++) {
  18223. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18224. lngsToLoad.push(pres[y]);
  18225. }
  18226. }
  18227. }
  18228. // check if we have to load
  18229. var lngNeedLoad = [];
  18230. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18231. var needLoad = false;
  18232. var resSet = resStore[lngsToLoad[a]];
  18233. if (resSet) {
  18234. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18235. if (!resSet[namespaces[b]]) needLoad = true;
  18236. }
  18237. } else {
  18238. needLoad = true;
  18239. }
  18240. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18241. }
  18242. if (lngNeedLoad.length) {
  18243. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18244. var todo = namespaces.length * lngNeedLoad.length;
  18245. // load each file individual
  18246. f.each(namespaces, function(nsIndex, nsValue) {
  18247. // append namespace to namespace array
  18248. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18249. o.ns.namespaces.push(nsValue);
  18250. }
  18251. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18252. resStore[lngValue] = resStore[lngValue] || {};
  18253. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18254. todo--; // wait for all done befor callback
  18255. if (todo === 0 && cb) {
  18256. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18257. cb();
  18258. }
  18259. });
  18260. });
  18261. });
  18262. } else {
  18263. if (cb) cb();
  18264. }
  18265. }
  18266. function setLng(lng, options, cb) {
  18267. if (typeof options === 'function') {
  18268. cb = options;
  18269. options = {};
  18270. } else if (!options) {
  18271. options = {};
  18272. }
  18273. options.lng = lng;
  18274. return init(options, cb);
  18275. }
  18276. function lng() {
  18277. return currentLng;
  18278. }
  18279. function reload(cb) {
  18280. resStore = {};
  18281. setLng(currentLng, cb);
  18282. }
  18283. function addJqueryFunct() {
  18284. // $.t shortcut
  18285. $.t = $.t || translate;
  18286. function parse(ele, key, options) {
  18287. if (key.length === 0) return;
  18288. var attr = 'text';
  18289. if (key.indexOf('[') === 0) {
  18290. var parts = key.split(']');
  18291. key = parts[1];
  18292. attr = parts[0].substr(1, parts[0].length-1);
  18293. }
  18294. if (key.indexOf(';') === key.length-1) {
  18295. key = key.substr(0, key.length-2);
  18296. }
  18297. var optionsToUse;
  18298. if (attr === 'html') {
  18299. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18300. ele.html($.t(key, optionsToUse));
  18301. } else if (attr === 'text') {
  18302. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18303. ele.text($.t(key, optionsToUse));
  18304. } else if (attr === 'prepend') {
  18305. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18306. ele.prepend($.t(key, optionsToUse));
  18307. } else if (attr === 'append') {
  18308. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18309. ele.append($.t(key, optionsToUse));
  18310. } else if (attr.indexOf("data-") === 0) {
  18311. var dataAttr = attr.substr(("data-").length);
  18312. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18313. var translated = $.t(key, optionsToUse);
  18314. //we change into the data cache
  18315. ele.data(dataAttr, translated);
  18316. //we change into the dom
  18317. ele.attr(attr, translated);
  18318. } else {
  18319. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18320. ele.attr(attr, $.t(key, optionsToUse));
  18321. }
  18322. }
  18323. function localize(ele, options) {
  18324. var key = ele.attr(o.selectorAttr);
  18325. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18326. if (!key) return;
  18327. var target = ele
  18328. , targetSelector = ele.data("i18n-target");
  18329. if (targetSelector) {
  18330. target = ele.find(targetSelector) || ele;
  18331. }
  18332. if (!options && o.useDataAttrOptions === true) {
  18333. options = ele.data("i18n-options");
  18334. }
  18335. options = options || {};
  18336. if (key.indexOf(';') >= 0) {
  18337. var keys = key.split(';');
  18338. $.each(keys, function(m, k) {
  18339. if (k !== '') parse(target, k, options);
  18340. });
  18341. } else {
  18342. parse(target, key, options);
  18343. }
  18344. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18345. }
  18346. // fn
  18347. $.fn.i18n = function (options) {
  18348. return this.each(function() {
  18349. // localize element itself
  18350. localize($(this), options);
  18351. // localize childs
  18352. var elements = $(this).find('[' + o.selectorAttr + ']');
  18353. elements.each(function() {
  18354. localize($(this), options);
  18355. });
  18356. });
  18357. };
  18358. }
  18359. function applyReplacement(str, replacementHash, nestedKey, options) {
  18360. if (!str) return str;
  18361. options = options || replacementHash; // first call uses replacement hash combined with options
  18362. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18363. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18364. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18365. , unEscapingSuffix = 'HTML'+suffix;
  18366. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18367. f.each(hash, function(key, value) {
  18368. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18369. if (typeof value === 'object' && value !== null) {
  18370. str = applyReplacement(str, value, nextKey, options);
  18371. } else {
  18372. if (options.escapeInterpolation || o.escapeInterpolation) {
  18373. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18374. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18375. } else {
  18376. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18377. }
  18378. // str = options.escapeInterpolation;
  18379. }
  18380. });
  18381. return str;
  18382. }
  18383. // append it to functions
  18384. f.applyReplacement = applyReplacement;
  18385. function applyReuse(translated, options) {
  18386. var comma = ',';
  18387. var options_open = '{';
  18388. var options_close = '}';
  18389. var opts = f.extend({}, options);
  18390. delete opts.postProcess;
  18391. while (translated.indexOf(o.reusePrefix) != -1) {
  18392. replacementCounter++;
  18393. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18394. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18395. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18396. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18397. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18398. if (index_of_end_of_closing <= index_of_opening) {
  18399. f.error('there is an missing closing in following translation value', translated);
  18400. return '';
  18401. }
  18402. if (token_without_symbols.indexOf(comma) != -1) {
  18403. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18404. 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) {
  18405. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18406. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18407. try {
  18408. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18409. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18410. } catch (e) {
  18411. }
  18412. }
  18413. }
  18414. var translated_token = _translate(token_without_symbols, opts);
  18415. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18416. }
  18417. return translated;
  18418. }
  18419. function hasContext(options) {
  18420. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18421. }
  18422. function needsPlural(options, lng) {
  18423. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18424. }
  18425. function needsIndefiniteArticle(options) {
  18426. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18427. }
  18428. function exists(key, options) {
  18429. options = options || {};
  18430. var notFound = _getDefaultValue(key, options)
  18431. , found = _find(key, options);
  18432. return found !== undefined || found === notFound;
  18433. }
  18434. function translate(key, options) {
  18435. options = options || {};
  18436. if (!initialized) {
  18437. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18438. return options.defaultValue || '';
  18439. };
  18440. replacementCounter = 0;
  18441. return _translate.apply(null, arguments);
  18442. }
  18443. function _getDefaultValue(key, options) {
  18444. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18445. }
  18446. function _injectSprintfProcessor() {
  18447. var values = [];
  18448. // mh: build array from second argument onwards
  18449. for (var i = 1; i < arguments.length; i++) {
  18450. values.push(arguments[i]);
  18451. }
  18452. return {
  18453. postProcess: 'sprintf',
  18454. sprintf: values
  18455. };
  18456. }
  18457. function _translate(potentialKeys, options) {
  18458. if (options && typeof options !== 'object') {
  18459. if (o.shortcutFunction === 'sprintf') {
  18460. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18461. options = _injectSprintfProcessor.apply(null, arguments);
  18462. } else if (o.shortcutFunction === 'defaultValue') {
  18463. options = {
  18464. defaultValue: options
  18465. }
  18466. }
  18467. } else {
  18468. options = options || {};
  18469. }
  18470. if (typeof o.defaultVariables === 'object') {
  18471. options = f.extend({}, o.defaultVariables, options);
  18472. }
  18473. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18474. if (typeof potentialKeys === 'string') {
  18475. potentialKeys = [potentialKeys];
  18476. }
  18477. var key = potentialKeys[0];
  18478. if (potentialKeys.length > 1) {
  18479. for (var i = 0; i < potentialKeys.length; i++) {
  18480. key = potentialKeys[i];
  18481. if (exists(key, options)) {
  18482. break;
  18483. }
  18484. }
  18485. }
  18486. var notFound = _getDefaultValue(key, options)
  18487. , found = _find(key, options)
  18488. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18489. , ns = options.ns || o.ns.defaultNs
  18490. , parts;
  18491. // split ns and key
  18492. if (key.indexOf(o.nsseparator) > -1) {
  18493. parts = key.split(o.nsseparator);
  18494. ns = parts[0];
  18495. key = parts[1];
  18496. }
  18497. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18498. if (options.lng) {
  18499. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18500. } else {
  18501. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18502. }
  18503. }
  18504. var postProcessor = options.postProcess || o.postProcess;
  18505. if (found !== undefined && postProcessor) {
  18506. if (postProcessors[postProcessor]) {
  18507. found = postProcessors[postProcessor](found, key, options);
  18508. }
  18509. }
  18510. // process notFound if function exists
  18511. var splitNotFound = notFound;
  18512. if (notFound.indexOf(o.nsseparator) > -1) {
  18513. parts = notFound.split(o.nsseparator);
  18514. splitNotFound = parts[1];
  18515. }
  18516. if (splitNotFound === key && o.parseMissingKey) {
  18517. notFound = o.parseMissingKey(notFound);
  18518. }
  18519. if (found === undefined) {
  18520. notFound = applyReplacement(notFound, options);
  18521. notFound = applyReuse(notFound, options);
  18522. if (postProcessor && postProcessors[postProcessor]) {
  18523. var val = _getDefaultValue(key, options);
  18524. found = postProcessors[postProcessor](val, key, options);
  18525. }
  18526. }
  18527. return (found !== undefined) ? found : notFound;
  18528. }
  18529. function _find(key, options) {
  18530. options = options || {};
  18531. var optionWithoutCount, translated
  18532. , notFound = _getDefaultValue(key, options)
  18533. , lngs = languages;
  18534. if (!resStore) { return notFound; } // no resStore to translate from
  18535. // CI mode
  18536. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18537. // passed in lng
  18538. if (options.lngs) lngs = options.lngs;
  18539. if (options.lng) {
  18540. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18541. if (!resStore[lngs[0]]) {
  18542. var oldAsync = o.getAsync;
  18543. o.getAsync = false;
  18544. i18n.sync.load(lngs, o, function(err, store) {
  18545. f.extend(resStore, store);
  18546. o.getAsync = oldAsync;
  18547. });
  18548. }
  18549. }
  18550. var ns = options.ns || o.ns.defaultNs;
  18551. if (key.indexOf(o.nsseparator) > -1) {
  18552. var parts = key.split(o.nsseparator);
  18553. ns = parts[0];
  18554. key = parts[1];
  18555. }
  18556. if (hasContext(options)) {
  18557. optionWithoutCount = f.extend({}, options);
  18558. delete optionWithoutCount.context;
  18559. optionWithoutCount.defaultValue = o.contextNotFound;
  18560. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18561. translated = translate(contextKey, optionWithoutCount);
  18562. if (translated != o.contextNotFound) {
  18563. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18564. } // else continue translation with original/nonContext key
  18565. }
  18566. if (needsPlural(options, lngs[0])) {
  18567. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18568. delete optionWithoutCount.count;
  18569. delete optionWithoutCount.lng;
  18570. optionWithoutCount.defaultValue = o.pluralNotFound;
  18571. var pluralKey;
  18572. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18573. pluralKey = ns + o.nsseparator + key;
  18574. } else {
  18575. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18576. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18577. if (pluralExtension >= 0) {
  18578. pluralKey = pluralKey + '_' + pluralExtension;
  18579. } else if (pluralExtension === 1) {
  18580. pluralKey = ns + o.nsseparator + key; // singular
  18581. }
  18582. }
  18583. translated = translate(pluralKey, optionWithoutCount);
  18584. if (translated != o.pluralNotFound) {
  18585. return applyReplacement(translated, {
  18586. count: options.count,
  18587. interpolationPrefix: options.interpolationPrefix,
  18588. interpolationSuffix: options.interpolationSuffix
  18589. }); // apply replacement for count only
  18590. } else if (lngs.length > 1) {
  18591. // remove failed lng
  18592. var clone = lngs.slice();
  18593. clone.shift();
  18594. options = f.extend(options, { lngs: clone });
  18595. delete options.lng;
  18596. // retry with fallbacks
  18597. translated = translate(ns + o.nsseparator + key, options);
  18598. if (translated != o.pluralNotFound) return translated;
  18599. } else {
  18600. return translated;
  18601. }
  18602. }
  18603. if (needsIndefiniteArticle(options)) {
  18604. var optionsWithoutIndef = f.extend({}, options);
  18605. delete optionsWithoutIndef.indefinite_article;
  18606. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18607. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18608. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18609. translated = translate(indefiniteKey, optionsWithoutIndef);
  18610. if (translated != o.indefiniteNotFound) {
  18611. return translated;
  18612. }
  18613. }
  18614. var found;
  18615. var keys = key.split(o.keyseparator);
  18616. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18617. if (found !== undefined) break;
  18618. var l = lngs[i];
  18619. var x = 0;
  18620. var value = resStore[l] && resStore[l][ns];
  18621. while (keys[x]) {
  18622. value = value && value[keys[x]];
  18623. x++;
  18624. }
  18625. if (value !== undefined) {
  18626. var valueType = Object.prototype.toString.apply(value);
  18627. if (typeof value === 'string') {
  18628. value = applyReplacement(value, options);
  18629. value = applyReuse(value, options);
  18630. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18631. value = value.join('\n');
  18632. value = applyReplacement(value, options);
  18633. value = applyReuse(value, options);
  18634. } else if (value === null && o.fallbackOnNull === true) {
  18635. value = undefined;
  18636. } else if (value !== null) {
  18637. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18638. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18639. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18640. } else {
  18641. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18642. 'returned an object instead of string.';
  18643. f.log(value);
  18644. }
  18645. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18646. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18647. f.each(value, function(m) {
  18648. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18649. });
  18650. value = copy;
  18651. }
  18652. }
  18653. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18654. value = undefined;
  18655. found = value;
  18656. }
  18657. }
  18658. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18659. // set flag for fallback lookup - avoid recursion
  18660. options.isFallbackLookup = true;
  18661. if (o.fallbackNS.length) {
  18662. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  18663. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  18664. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  18665. /* compare value without namespace */
  18666. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  18667. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  18668. if (foundValue !== notFoundValue) break;
  18669. }
  18670. }
  18671. } else {
  18672. found = _find(key, options); // fallback to default NS
  18673. }
  18674. options.isFallbackLookup = false;
  18675. }
  18676. return found;
  18677. }
  18678. function detectLanguage() {
  18679. var detectedLng;
  18680. var whitelist = o.lngWhitelist || [];
  18681. var userLngChoices = [];
  18682. // get from qs
  18683. var qsParm = [];
  18684. if (typeof window !== 'undefined') {
  18685. (function() {
  18686. var query = window.location.search.substring(1);
  18687. var params = query.split('&');
  18688. for (var i=0; i<params.length; i++) {
  18689. var pos = params[i].indexOf('=');
  18690. if (pos > 0) {
  18691. var key = params[i].substring(0,pos);
  18692. if (key == o.detectLngQS) {
  18693. userLngChoices.push(params[i].substring(pos+1));
  18694. }
  18695. }
  18696. }
  18697. })();
  18698. }
  18699. // get from cookie
  18700. if (o.useCookie && typeof document !== 'undefined') {
  18701. var c = f.cookie.read(o.cookieName);
  18702. if (c) userLngChoices.push(c);
  18703. }
  18704. // get from localStorage
  18705. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  18706. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  18707. }
  18708. // get from navigator
  18709. if (typeof navigator !== 'undefined') {
  18710. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  18711. for (var i=0;i<navigator.languages.length;i++) {
  18712. userLngChoices.push(navigator.languages[i]);
  18713. }
  18714. }
  18715. if (navigator.userLanguage) {
  18716. userLngChoices.push(navigator.userLanguage);
  18717. }
  18718. if (navigator.language) {
  18719. userLngChoices.push(navigator.language);
  18720. }
  18721. }
  18722. (function() {
  18723. for (var i=0;i<userLngChoices.length;i++) {
  18724. var lng = userLngChoices[i];
  18725. if (lng.indexOf('-') > -1) {
  18726. var parts = lng.split('-');
  18727. lng = o.lowerCaseLng ?
  18728. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18729. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18730. }
  18731. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  18732. detectedLng = lng;
  18733. break;
  18734. }
  18735. }
  18736. })();
  18737. //fallback
  18738. if (!detectedLng){
  18739. detectedLng = o.fallbackLng[0];
  18740. }
  18741. return detectedLng;
  18742. }
  18743. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  18744. /* [code, name, numbers, pluralsType] */
  18745. var _rules = [
  18746. ["ach", "Acholi", [1,2], 1],
  18747. ["af", "Afrikaans",[1,2], 2],
  18748. ["ak", "Akan", [1,2], 1],
  18749. ["am", "Amharic", [1,2], 1],
  18750. ["an", "Aragonese",[1,2], 2],
  18751. ["ar", "Arabic", [0,1,2,3,11,100],5],
  18752. ["arn", "Mapudungun",[1,2], 1],
  18753. ["ast", "Asturian", [1,2], 2],
  18754. ["ay", "Aymará", [1], 3],
  18755. ["az", "Azerbaijani",[1,2],2],
  18756. ["be", "Belarusian",[1,2,5],4],
  18757. ["bg", "Bulgarian",[1,2], 2],
  18758. ["bn", "Bengali", [1,2], 2],
  18759. ["bo", "Tibetan", [1], 3],
  18760. ["br", "Breton", [1,2], 1],
  18761. ["bs", "Bosnian", [1,2,5],4],
  18762. ["ca", "Catalan", [1,2], 2],
  18763. ["cgg", "Chiga", [1], 3],
  18764. ["cs", "Czech", [1,2,5],6],
  18765. ["csb", "Kashubian",[1,2,5],7],
  18766. ["cy", "Welsh", [1,2,3,8],8],
  18767. ["da", "Danish", [1,2], 2],
  18768. ["de", "German", [1,2], 2],
  18769. ["dev", "Development Fallback", [1,2], 2],
  18770. ["dz", "Dzongkha", [1], 3],
  18771. ["el", "Greek", [1,2], 2],
  18772. ["en", "English", [1,2], 2],
  18773. ["eo", "Esperanto",[1,2], 2],
  18774. ["es", "Spanish", [1,2], 2],
  18775. ["es_ar","Argentinean Spanish", [1,2], 2],
  18776. ["et", "Estonian", [1,2], 2],
  18777. ["eu", "Basque", [1,2], 2],
  18778. ["fa", "Persian", [1], 3],
  18779. ["fi", "Finnish", [1,2], 2],
  18780. ["fil", "Filipino", [1,2], 1],
  18781. ["fo", "Faroese", [1,2], 2],
  18782. ["fr", "French", [1,2], 9],
  18783. ["fur", "Friulian", [1,2], 2],
  18784. ["fy", "Frisian", [1,2], 2],
  18785. ["ga", "Irish", [1,2,3,7,11],10],
  18786. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  18787. ["gl", "Galician", [1,2], 2],
  18788. ["gu", "Gujarati", [1,2], 2],
  18789. ["gun", "Gun", [1,2], 1],
  18790. ["ha", "Hausa", [1,2], 2],
  18791. ["he", "Hebrew", [1,2], 2],
  18792. ["hi", "Hindi", [1,2], 2],
  18793. ["hr", "Croatian", [1,2,5],4],
  18794. ["hu", "Hungarian",[1,2], 2],
  18795. ["hy", "Armenian", [1,2], 2],
  18796. ["ia", "Interlingua",[1,2],2],
  18797. ["id", "Indonesian",[1], 3],
  18798. ["is", "Icelandic",[1,2], 12],
  18799. ["it", "Italian", [1,2], 2],
  18800. ["ja", "Japanese", [1], 3],
  18801. ["jbo", "Lojban", [1], 3],
  18802. ["jv", "Javanese", [0,1], 13],
  18803. ["ka", "Georgian", [1], 3],
  18804. ["kk", "Kazakh", [1], 3],
  18805. ["km", "Khmer", [1], 3],
  18806. ["kn", "Kannada", [1,2], 2],
  18807. ["ko", "Korean", [1], 3],
  18808. ["ku", "Kurdish", [1,2], 2],
  18809. ["kw", "Cornish", [1,2,3,4],14],
  18810. ["ky", "Kyrgyz", [1], 3],
  18811. ["lb", "Letzeburgesch",[1,2],2],
  18812. ["ln", "Lingala", [1,2], 1],
  18813. ["lo", "Lao", [1], 3],
  18814. ["lt", "Lithuanian",[1,2,10],15],
  18815. ["lv", "Latvian", [1,2,0],16],
  18816. ["mai", "Maithili", [1,2], 2],
  18817. ["mfe", "Mauritian Creole",[1,2],1],
  18818. ["mg", "Malagasy", [1,2], 1],
  18819. ["mi", "Maori", [1,2], 1],
  18820. ["mk", "Macedonian",[1,2],17],
  18821. ["ml", "Malayalam",[1,2], 2],
  18822. ["mn", "Mongolian",[1,2], 2],
  18823. ["mnk", "Mandinka", [0,1,2],18],
  18824. ["mr", "Marathi", [1,2], 2],
  18825. ["ms", "Malay", [1], 3],
  18826. ["mt", "Maltese", [1,2,11,20],19],
  18827. ["nah", "Nahuatl", [1,2], 2],
  18828. ["nap", "Neapolitan",[1,2], 2],
  18829. ["nb", "Norwegian Bokmal",[1,2],2],
  18830. ["ne", "Nepali", [1,2], 2],
  18831. ["nl", "Dutch", [1,2], 2],
  18832. ["nn", "Norwegian Nynorsk",[1,2],2],
  18833. ["no", "Norwegian",[1,2], 2],
  18834. ["nso", "Northern Sotho",[1,2],2],
  18835. ["oc", "Occitan", [1,2], 1],
  18836. ["or", "Oriya", [2,1], 2],
  18837. ["pa", "Punjabi", [1,2], 2],
  18838. ["pap", "Papiamento",[1,2], 2],
  18839. ["pl", "Polish", [1,2,5],7],
  18840. ["pms", "Piemontese",[1,2], 2],
  18841. ["ps", "Pashto", [1,2], 2],
  18842. ["pt", "Portuguese",[1,2], 2],
  18843. ["pt_br","Brazilian Portuguese",[1,2], 2],
  18844. ["rm", "Romansh", [1,2], 2],
  18845. ["ro", "Romanian", [1,2,20],20],
  18846. ["ru", "Russian", [1,2,5],4],
  18847. ["sah", "Yakut", [1], 3],
  18848. ["sco", "Scots", [1,2], 2],
  18849. ["se", "Northern Sami",[1,2], 2],
  18850. ["si", "Sinhala", [1,2], 2],
  18851. ["sk", "Slovak", [1,2,5],6],
  18852. ["sl", "Slovenian",[5,1,2,3],21],
  18853. ["so", "Somali", [1,2], 2],
  18854. ["son", "Songhay", [1,2], 2],
  18855. ["sq", "Albanian", [1,2], 2],
  18856. ["sr", "Serbian", [1,2,5],4],
  18857. ["su", "Sundanese",[1], 3],
  18858. ["sv", "Swedish", [1,2], 2],
  18859. ["sw", "Swahili", [1,2], 2],
  18860. ["ta", "Tamil", [1,2], 2],
  18861. ["te", "Telugu", [1,2], 2],
  18862. ["tg", "Tajik", [1,2], 1],
  18863. ["th", "Thai", [1], 3],
  18864. ["ti", "Tigrinya", [1,2], 1],
  18865. ["tk", "Turkmen", [1,2], 2],
  18866. ["tr", "Turkish", [1,2], 1],
  18867. ["tt", "Tatar", [1], 3],
  18868. ["ug", "Uyghur", [1], 3],
  18869. ["uk", "Ukrainian",[1,2,5],4],
  18870. ["ur", "Urdu", [1,2], 2],
  18871. ["uz", "Uzbek", [1,2], 1],
  18872. ["vi", "Vietnamese",[1], 3],
  18873. ["wa", "Walloon", [1,2], 1],
  18874. ["wo", "Wolof", [1], 3],
  18875. ["yo", "Yoruba", [1,2], 2],
  18876. ["zh", "Chinese", [1], 3]
  18877. ];
  18878. var _rulesPluralsTypes = {
  18879. 1: function(n) {return Number(n > 1);},
  18880. 2: function(n) {return Number(n != 1);},
  18881. 3: function(n) {return 0;},
  18882. 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);},
  18883. 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);},
  18884. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  18885. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18886. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  18887. 9: function(n) {return Number(n >= 2);},
  18888. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  18889. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  18890. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  18891. 13: function(n) {return Number(n !== 0);},
  18892. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  18893. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18894. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  18895. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  18896. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  18897. 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);},
  18898. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  18899. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  18900. };
  18901. var pluralExtensions = {
  18902. rules: (function () {
  18903. var l, rules = {};
  18904. for (l=_rules.length; l-- ;) {
  18905. rules[_rules[l][0]] = {
  18906. name: _rules[l][1],
  18907. numbers: _rules[l][2],
  18908. plurals: _rulesPluralsTypes[_rules[l][3]]
  18909. }
  18910. }
  18911. return rules;
  18912. }()),
  18913. // you can add your own pluralExtensions
  18914. addRule: function(lng, obj) {
  18915. pluralExtensions.rules[lng] = obj;
  18916. },
  18917. setCurrentLng: function(lng) {
  18918. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  18919. var parts = lng.split('-');
  18920. pluralExtensions.currentRule = {
  18921. lng: lng,
  18922. rule: pluralExtensions.rules[parts[0]]
  18923. };
  18924. }
  18925. },
  18926. needsPlural: function(lng, count) {
  18927. var parts = lng.split('-');
  18928. var ext;
  18929. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18930. ext = pluralExtensions.currentRule.rule;
  18931. } else {
  18932. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  18933. }
  18934. if (ext && ext.numbers.length <= 1) {
  18935. return false;
  18936. } else {
  18937. return this.get(lng, count) !== 1;
  18938. }
  18939. },
  18940. get: function(lng, count) {
  18941. var parts = lng.split('-');
  18942. function getResult(l, c) {
  18943. var ext;
  18944. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18945. ext = pluralExtensions.currentRule.rule;
  18946. } else {
  18947. ext = pluralExtensions.rules[l];
  18948. }
  18949. if (ext) {
  18950. var i;
  18951. if (ext.noAbs) {
  18952. i = ext.plurals(c);
  18953. } else {
  18954. i = ext.plurals(Math.abs(c));
  18955. }
  18956. var number = ext.numbers[i];
  18957. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  18958. if (number === 2) {
  18959. number = -1; // regular plural
  18960. } else if (number === 1) {
  18961. number = 1; // singular
  18962. }
  18963. }//console.log(count + '-' + number);
  18964. return number;
  18965. } else {
  18966. return c === 1 ? '1' : '-1';
  18967. }
  18968. }
  18969. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  18970. }
  18971. };
  18972. var postProcessors = {};
  18973. var addPostProcessor = function(name, fc) {
  18974. postProcessors[name] = fc;
  18975. };
  18976. // sprintf support
  18977. var sprintf = (function() {
  18978. function get_type(variable) {
  18979. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  18980. }
  18981. function str_repeat(input, multiplier) {
  18982. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  18983. return output.join('');
  18984. }
  18985. var str_format = function() {
  18986. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  18987. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  18988. }
  18989. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  18990. };
  18991. str_format.format = function(parse_tree, argv) {
  18992. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  18993. for (i = 0; i < tree_length; i++) {
  18994. node_type = get_type(parse_tree[i]);
  18995. if (node_type === 'string') {
  18996. output.push(parse_tree[i]);
  18997. }
  18998. else if (node_type === 'array') {
  18999. match = parse_tree[i]; // convenience purposes only
  19000. if (match[2]) { // keyword argument
  19001. arg = argv[cursor];
  19002. for (k = 0; k < match[2].length; k++) {
  19003. if (!arg.hasOwnProperty(match[2][k])) {
  19004. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19005. }
  19006. arg = arg[match[2][k]];
  19007. }
  19008. }
  19009. else if (match[1]) { // positional argument (explicit)
  19010. arg = argv[match[1]];
  19011. }
  19012. else { // positional argument (implicit)
  19013. arg = argv[cursor++];
  19014. }
  19015. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19016. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19017. }
  19018. switch (match[8]) {
  19019. case 'b': arg = arg.toString(2); break;
  19020. case 'c': arg = String.fromCharCode(arg); break;
  19021. case 'd': arg = parseInt(arg, 10); break;
  19022. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19023. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19024. case 'o': arg = arg.toString(8); break;
  19025. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19026. case 'u': arg = Math.abs(arg); break;
  19027. case 'x': arg = arg.toString(16); break;
  19028. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19029. }
  19030. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19031. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19032. pad_length = match[6] - String(arg).length;
  19033. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19034. output.push(match[5] ? arg + pad : pad + arg);
  19035. }
  19036. }
  19037. return output.join('');
  19038. };
  19039. str_format.cache = {};
  19040. str_format.parse = function(fmt) {
  19041. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19042. while (_fmt) {
  19043. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19044. parse_tree.push(match[0]);
  19045. }
  19046. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19047. parse_tree.push('%');
  19048. }
  19049. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19050. if (match[2]) {
  19051. arg_names |= 1;
  19052. var field_list = [], replacement_field = match[2], field_match = [];
  19053. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19054. field_list.push(field_match[1]);
  19055. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19056. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19057. field_list.push(field_match[1]);
  19058. }
  19059. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19060. field_list.push(field_match[1]);
  19061. }
  19062. else {
  19063. throw('[sprintf] huh?');
  19064. }
  19065. }
  19066. }
  19067. else {
  19068. throw('[sprintf] huh?');
  19069. }
  19070. match[2] = field_list;
  19071. }
  19072. else {
  19073. arg_names |= 2;
  19074. }
  19075. if (arg_names === 3) {
  19076. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19077. }
  19078. parse_tree.push(match);
  19079. }
  19080. else {
  19081. throw('[sprintf] huh?');
  19082. }
  19083. _fmt = _fmt.substring(match[0].length);
  19084. }
  19085. return parse_tree;
  19086. };
  19087. return str_format;
  19088. })();
  19089. var vsprintf = function(fmt, argv) {
  19090. argv.unshift(fmt);
  19091. return sprintf.apply(null, argv);
  19092. };
  19093. addPostProcessor("sprintf", function(val, key, opts) {
  19094. if (!opts.sprintf) return val;
  19095. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19096. return vsprintf(val, opts.sprintf);
  19097. } else if (typeof opts.sprintf === 'object') {
  19098. return sprintf(val, opts.sprintf);
  19099. }
  19100. return val;
  19101. });
  19102. // public api interface
  19103. i18n.init = init;
  19104. i18n.setLng = setLng;
  19105. i18n.preload = preload;
  19106. i18n.addResourceBundle = addResourceBundle;
  19107. i18n.hasResourceBundle = hasResourceBundle;
  19108. i18n.addResource = addResource;
  19109. i18n.addResources = addResources;
  19110. i18n.removeResourceBundle = removeResourceBundle;
  19111. i18n.loadNamespace = loadNamespace;
  19112. i18n.loadNamespaces = loadNamespaces;
  19113. i18n.setDefaultNamespace = setDefaultNamespace;
  19114. i18n.t = translate;
  19115. i18n.translate = translate;
  19116. i18n.exists = exists;
  19117. i18n.detectLanguage = f.detectLanguage;
  19118. i18n.pluralExtensions = pluralExtensions;
  19119. i18n.sync = sync;
  19120. i18n.functions = f;
  19121. i18n.lng = lng;
  19122. i18n.addPostProcessor = addPostProcessor;
  19123. i18n.options = o;
  19124. })();
  19125. },{"jquery":"jquery"}],69:[function(require,module,exports){
  19126. // Top level file is just a mixin of submodules & constants
  19127. 'use strict';
  19128. var assign = require('./lib/utils/common').assign;
  19129. var deflate = require('./lib/deflate');
  19130. var inflate = require('./lib/inflate');
  19131. var constants = require('./lib/zlib/constants');
  19132. var pako = {};
  19133. assign(pako, deflate, inflate, constants);
  19134. module.exports = pako;
  19135. },{"./lib/deflate":70,"./lib/inflate":71,"./lib/utils/common":72,"./lib/zlib/constants":75}],70:[function(require,module,exports){
  19136. 'use strict';
  19137. var zlib_deflate = require('./zlib/deflate.js');
  19138. var utils = require('./utils/common');
  19139. var strings = require('./utils/strings');
  19140. var msg = require('./zlib/messages');
  19141. var zstream = require('./zlib/zstream');
  19142. var toString = Object.prototype.toString;
  19143. /* Public constants ==========================================================*/
  19144. /* ===========================================================================*/
  19145. var Z_NO_FLUSH = 0;
  19146. var Z_FINISH = 4;
  19147. var Z_OK = 0;
  19148. var Z_STREAM_END = 1;
  19149. var Z_SYNC_FLUSH = 2;
  19150. var Z_DEFAULT_COMPRESSION = -1;
  19151. var Z_DEFAULT_STRATEGY = 0;
  19152. var Z_DEFLATED = 8;
  19153. /* ===========================================================================*/
  19154. /**
  19155. * class Deflate
  19156. *
  19157. * Generic JS-style wrapper for zlib calls. If you don't need
  19158. * streaming behaviour - use more simple functions: [[deflate]],
  19159. * [[deflateRaw]] and [[gzip]].
  19160. **/
  19161. /* internal
  19162. * Deflate.chunks -> Array
  19163. *
  19164. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19165. **/
  19166. /**
  19167. * Deflate.result -> Uint8Array|Array
  19168. *
  19169. * Compressed result, generated by default [[Deflate#onData]]
  19170. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19171. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19172. * push a chunk with explicit flush (call [[Deflate#push]] with
  19173. * `Z_SYNC_FLUSH` param).
  19174. **/
  19175. /**
  19176. * Deflate.err -> Number
  19177. *
  19178. * Error code after deflate finished. 0 (Z_OK) on success.
  19179. * You will not need it in real life, because deflate errors
  19180. * are possible only on wrong options or bad `onData` / `onEnd`
  19181. * custom handlers.
  19182. **/
  19183. /**
  19184. * Deflate.msg -> String
  19185. *
  19186. * Error message, if [[Deflate.err]] != 0
  19187. **/
  19188. /**
  19189. * new Deflate(options)
  19190. * - options (Object): zlib deflate options.
  19191. *
  19192. * Creates new deflator instance with specified params. Throws exception
  19193. * on bad params. Supported options:
  19194. *
  19195. * - `level`
  19196. * - `windowBits`
  19197. * - `memLevel`
  19198. * - `strategy`
  19199. *
  19200. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19201. * for more information on these.
  19202. *
  19203. * Additional options, for internal needs:
  19204. *
  19205. * - `chunkSize` - size of generated data chunks (16K by default)
  19206. * - `raw` (Boolean) - do raw deflate
  19207. * - `gzip` (Boolean) - create gzip wrapper
  19208. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19209. * (each char code [0..255])
  19210. * - `header` (Object) - custom header for gzip
  19211. * - `text` (Boolean) - true if compressed data believed to be text
  19212. * - `time` (Number) - modification time, unix timestamp
  19213. * - `os` (Number) - operation system code
  19214. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19215. * - `name` (String) - file name (binary string)
  19216. * - `comment` (String) - comment (binary string)
  19217. * - `hcrc` (Boolean) - true if header crc should be added
  19218. *
  19219. * ##### Example:
  19220. *
  19221. * ```javascript
  19222. * var pako = require('pako')
  19223. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19224. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19225. *
  19226. * var deflate = new pako.Deflate({ level: 3});
  19227. *
  19228. * deflate.push(chunk1, false);
  19229. * deflate.push(chunk2, true); // true -> last chunk
  19230. *
  19231. * if (deflate.err) { throw new Error(deflate.err); }
  19232. *
  19233. * console.log(deflate.result);
  19234. * ```
  19235. **/
  19236. var Deflate = function(options) {
  19237. this.options = utils.assign({
  19238. level: Z_DEFAULT_COMPRESSION,
  19239. method: Z_DEFLATED,
  19240. chunkSize: 16384,
  19241. windowBits: 15,
  19242. memLevel: 8,
  19243. strategy: Z_DEFAULT_STRATEGY,
  19244. to: ''
  19245. }, options || {});
  19246. var opt = this.options;
  19247. if (opt.raw && (opt.windowBits > 0)) {
  19248. opt.windowBits = -opt.windowBits;
  19249. }
  19250. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19251. opt.windowBits += 16;
  19252. }
  19253. this.err = 0; // error code, if happens (0 = Z_OK)
  19254. this.msg = ''; // error message
  19255. this.ended = false; // used to avoid multiple onEnd() calls
  19256. this.chunks = []; // chunks of compressed data
  19257. this.strm = new zstream();
  19258. this.strm.avail_out = 0;
  19259. var status = zlib_deflate.deflateInit2(
  19260. this.strm,
  19261. opt.level,
  19262. opt.method,
  19263. opt.windowBits,
  19264. opt.memLevel,
  19265. opt.strategy
  19266. );
  19267. if (status !== Z_OK) {
  19268. throw new Error(msg[status]);
  19269. }
  19270. if (opt.header) {
  19271. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19272. }
  19273. };
  19274. /**
  19275. * Deflate#push(data[, mode]) -> Boolean
  19276. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19277. * converted to utf8 byte sequence.
  19278. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19279. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19280. *
  19281. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19282. * new compressed chunks. Returns `true` on success. The last data block must have
  19283. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19284. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19285. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19286. *
  19287. * On fail call [[Deflate#onEnd]] with error code and return false.
  19288. *
  19289. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19290. * array format is detected automatically). Also, don't skip last param and always
  19291. * use the same type in your code (boolean or number). That will improve JS speed.
  19292. *
  19293. * For regular `Array`-s make sure all elements are [0..255].
  19294. *
  19295. * ##### Example
  19296. *
  19297. * ```javascript
  19298. * push(chunk, false); // push one of data chunks
  19299. * ...
  19300. * push(chunk, true); // push last chunk
  19301. * ```
  19302. **/
  19303. Deflate.prototype.push = function(data, mode) {
  19304. var strm = this.strm;
  19305. var chunkSize = this.options.chunkSize;
  19306. var status, _mode;
  19307. if (this.ended) { return false; }
  19308. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19309. // Convert data if needed
  19310. if (typeof data === 'string') {
  19311. // If we need to compress text, change encoding to utf8.
  19312. strm.input = strings.string2buf(data);
  19313. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19314. strm.input = new Uint8Array(data);
  19315. } else {
  19316. strm.input = data;
  19317. }
  19318. strm.next_in = 0;
  19319. strm.avail_in = strm.input.length;
  19320. do {
  19321. if (strm.avail_out === 0) {
  19322. strm.output = new utils.Buf8(chunkSize);
  19323. strm.next_out = 0;
  19324. strm.avail_out = chunkSize;
  19325. }
  19326. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19327. if (status !== Z_STREAM_END && status !== Z_OK) {
  19328. this.onEnd(status);
  19329. this.ended = true;
  19330. return false;
  19331. }
  19332. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19333. if (this.options.to === 'string') {
  19334. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19335. } else {
  19336. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19337. }
  19338. }
  19339. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19340. // Finalize on the last chunk.
  19341. if (_mode === Z_FINISH) {
  19342. status = zlib_deflate.deflateEnd(this.strm);
  19343. this.onEnd(status);
  19344. this.ended = true;
  19345. return status === Z_OK;
  19346. }
  19347. // callback interim results if Z_SYNC_FLUSH.
  19348. if (_mode === Z_SYNC_FLUSH) {
  19349. this.onEnd(Z_OK);
  19350. strm.avail_out = 0;
  19351. return true;
  19352. }
  19353. return true;
  19354. };
  19355. /**
  19356. * Deflate#onData(chunk) -> Void
  19357. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19358. * on js engine support. When string output requested, each chunk
  19359. * will be string.
  19360. *
  19361. * By default, stores data blocks in `chunks[]` property and glue
  19362. * those in `onEnd`. Override this handler, if you need another behaviour.
  19363. **/
  19364. Deflate.prototype.onData = function(chunk) {
  19365. this.chunks.push(chunk);
  19366. };
  19367. /**
  19368. * Deflate#onEnd(status) -> Void
  19369. * - status (Number): deflate status. 0 (Z_OK) on success,
  19370. * other if not.
  19371. *
  19372. * Called once after you tell deflate that the input stream is
  19373. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19374. * or if an error happened. By default - join collected chunks,
  19375. * free memory and fill `results` / `err` properties.
  19376. **/
  19377. Deflate.prototype.onEnd = function(status) {
  19378. // On success - join
  19379. if (status === Z_OK) {
  19380. if (this.options.to === 'string') {
  19381. this.result = this.chunks.join('');
  19382. } else {
  19383. this.result = utils.flattenChunks(this.chunks);
  19384. }
  19385. }
  19386. this.chunks = [];
  19387. this.err = status;
  19388. this.msg = this.strm.msg;
  19389. };
  19390. /**
  19391. * deflate(data[, options]) -> Uint8Array|Array|String
  19392. * - data (Uint8Array|Array|String): input data to compress.
  19393. * - options (Object): zlib deflate options.
  19394. *
  19395. * Compress `data` with deflate alrorythm and `options`.
  19396. *
  19397. * Supported options are:
  19398. *
  19399. * - level
  19400. * - windowBits
  19401. * - memLevel
  19402. * - strategy
  19403. *
  19404. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19405. * for more information on these.
  19406. *
  19407. * Sugar (options):
  19408. *
  19409. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19410. * negative windowBits implicitly.
  19411. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19412. * (each char code [0..255])
  19413. *
  19414. * ##### Example:
  19415. *
  19416. * ```javascript
  19417. * var pako = require('pako')
  19418. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19419. *
  19420. * console.log(pako.deflate(data));
  19421. * ```
  19422. **/
  19423. function deflate(input, options) {
  19424. var deflator = new Deflate(options);
  19425. deflator.push(input, true);
  19426. // That will never happens, if you don't cheat with options :)
  19427. if (deflator.err) { throw deflator.msg; }
  19428. return deflator.result;
  19429. }
  19430. /**
  19431. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19432. * - data (Uint8Array|Array|String): input data to compress.
  19433. * - options (Object): zlib deflate options.
  19434. *
  19435. * The same as [[deflate]], but creates raw data, without wrapper
  19436. * (header and adler32 crc).
  19437. **/
  19438. function deflateRaw(input, options) {
  19439. options = options || {};
  19440. options.raw = true;
  19441. return deflate(input, options);
  19442. }
  19443. /**
  19444. * gzip(data[, options]) -> Uint8Array|Array|String
  19445. * - data (Uint8Array|Array|String): input data to compress.
  19446. * - options (Object): zlib deflate options.
  19447. *
  19448. * The same as [[deflate]], but create gzip wrapper instead of
  19449. * deflate one.
  19450. **/
  19451. function gzip(input, options) {
  19452. options = options || {};
  19453. options.gzip = true;
  19454. return deflate(input, options);
  19455. }
  19456. exports.Deflate = Deflate;
  19457. exports.deflate = deflate;
  19458. exports.deflateRaw = deflateRaw;
  19459. exports.gzip = gzip;
  19460. },{"./utils/common":72,"./utils/strings":73,"./zlib/deflate.js":77,"./zlib/messages":82,"./zlib/zstream":84}],71:[function(require,module,exports){
  19461. 'use strict';
  19462. var zlib_inflate = require('./zlib/inflate.js');
  19463. var utils = require('./utils/common');
  19464. var strings = require('./utils/strings');
  19465. var c = require('./zlib/constants');
  19466. var msg = require('./zlib/messages');
  19467. var zstream = require('./zlib/zstream');
  19468. var gzheader = require('./zlib/gzheader');
  19469. var toString = Object.prototype.toString;
  19470. /**
  19471. * class Inflate
  19472. *
  19473. * Generic JS-style wrapper for zlib calls. If you don't need
  19474. * streaming behaviour - use more simple functions: [[inflate]]
  19475. * and [[inflateRaw]].
  19476. **/
  19477. /* internal
  19478. * inflate.chunks -> Array
  19479. *
  19480. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19481. **/
  19482. /**
  19483. * Inflate.result -> Uint8Array|Array|String
  19484. *
  19485. * Uncompressed result, generated by default [[Inflate#onData]]
  19486. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19487. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19488. * push a chunk with explicit flush (call [[Inflate#push]] with
  19489. * `Z_SYNC_FLUSH` param).
  19490. **/
  19491. /**
  19492. * Inflate.err -> Number
  19493. *
  19494. * Error code after inflate finished. 0 (Z_OK) on success.
  19495. * Should be checked if broken data possible.
  19496. **/
  19497. /**
  19498. * Inflate.msg -> String
  19499. *
  19500. * Error message, if [[Inflate.err]] != 0
  19501. **/
  19502. /**
  19503. * new Inflate(options)
  19504. * - options (Object): zlib inflate options.
  19505. *
  19506. * Creates new inflator instance with specified params. Throws exception
  19507. * on bad params. Supported options:
  19508. *
  19509. * - `windowBits`
  19510. *
  19511. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19512. * for more information on these.
  19513. *
  19514. * Additional options, for internal needs:
  19515. *
  19516. * - `chunkSize` - size of generated data chunks (16K by default)
  19517. * - `raw` (Boolean) - do raw inflate
  19518. * - `to` (String) - if equal to 'string', then result will be converted
  19519. * from utf8 to utf16 (javascript) string. When string output requested,
  19520. * chunk length can differ from `chunkSize`, depending on content.
  19521. *
  19522. * By default, when no options set, autodetect deflate/gzip data format via
  19523. * wrapper header.
  19524. *
  19525. * ##### Example:
  19526. *
  19527. * ```javascript
  19528. * var pako = require('pako')
  19529. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19530. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19531. *
  19532. * var inflate = new pako.Inflate({ level: 3});
  19533. *
  19534. * inflate.push(chunk1, false);
  19535. * inflate.push(chunk2, true); // true -> last chunk
  19536. *
  19537. * if (inflate.err) { throw new Error(inflate.err); }
  19538. *
  19539. * console.log(inflate.result);
  19540. * ```
  19541. **/
  19542. var Inflate = function(options) {
  19543. this.options = utils.assign({
  19544. chunkSize: 16384,
  19545. windowBits: 0,
  19546. to: ''
  19547. }, options || {});
  19548. var opt = this.options;
  19549. // Force window size for `raw` data, if not set directly,
  19550. // because we have no header for autodetect.
  19551. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19552. opt.windowBits = -opt.windowBits;
  19553. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19554. }
  19555. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19556. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19557. !(options && options.windowBits)) {
  19558. opt.windowBits += 32;
  19559. }
  19560. // Gzip header has no info about windows size, we can do autodetect only
  19561. // for deflate. So, if window size not set, force it to max when gzip possible
  19562. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19563. // bit 3 (16) -> gzipped data
  19564. // bit 4 (32) -> autodetect gzip/deflate
  19565. if ((opt.windowBits & 15) === 0) {
  19566. opt.windowBits |= 15;
  19567. }
  19568. }
  19569. this.err = 0; // error code, if happens (0 = Z_OK)
  19570. this.msg = ''; // error message
  19571. this.ended = false; // used to avoid multiple onEnd() calls
  19572. this.chunks = []; // chunks of compressed data
  19573. this.strm = new zstream();
  19574. this.strm.avail_out = 0;
  19575. var status = zlib_inflate.inflateInit2(
  19576. this.strm,
  19577. opt.windowBits
  19578. );
  19579. if (status !== c.Z_OK) {
  19580. throw new Error(msg[status]);
  19581. }
  19582. this.header = new gzheader();
  19583. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19584. };
  19585. /**
  19586. * Inflate#push(data[, mode]) -> Boolean
  19587. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19588. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19589. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19590. *
  19591. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19592. * new output chunks. Returns `true` on success. The last data block must have
  19593. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19594. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19595. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  19596. *
  19597. * On fail call [[Inflate#onEnd]] with error code and return false.
  19598. *
  19599. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19600. * format is detected automatically). Also, don't skip last param and always
  19601. * use the same type in your code (boolean or number). That will improve JS speed.
  19602. *
  19603. * For regular `Array`-s make sure all elements are [0..255].
  19604. *
  19605. * ##### Example
  19606. *
  19607. * ```javascript
  19608. * push(chunk, false); // push one of data chunks
  19609. * ...
  19610. * push(chunk, true); // push last chunk
  19611. * ```
  19612. **/
  19613. Inflate.prototype.push = function(data, mode) {
  19614. var strm = this.strm;
  19615. var chunkSize = this.options.chunkSize;
  19616. var status, _mode;
  19617. var next_out_utf8, tail, utf8str;
  19618. if (this.ended) { return false; }
  19619. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19620. // Convert data if needed
  19621. if (typeof data === 'string') {
  19622. // Only binary strings can be decompressed on practice
  19623. strm.input = strings.binstring2buf(data);
  19624. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19625. strm.input = new Uint8Array(data);
  19626. } else {
  19627. strm.input = data;
  19628. }
  19629. strm.next_in = 0;
  19630. strm.avail_in = strm.input.length;
  19631. do {
  19632. if (strm.avail_out === 0) {
  19633. strm.output = new utils.Buf8(chunkSize);
  19634. strm.next_out = 0;
  19635. strm.avail_out = chunkSize;
  19636. }
  19637. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19638. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19639. this.onEnd(status);
  19640. this.ended = true;
  19641. return false;
  19642. }
  19643. if (strm.next_out) {
  19644. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  19645. if (this.options.to === 'string') {
  19646. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19647. tail = strm.next_out - next_out_utf8;
  19648. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19649. // move tail
  19650. strm.next_out = tail;
  19651. strm.avail_out = chunkSize - tail;
  19652. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19653. this.onData(utf8str);
  19654. } else {
  19655. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19656. }
  19657. }
  19658. }
  19659. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19660. if (status === c.Z_STREAM_END) {
  19661. _mode = c.Z_FINISH;
  19662. }
  19663. // Finalize on the last chunk.
  19664. if (_mode === c.Z_FINISH) {
  19665. status = zlib_inflate.inflateEnd(this.strm);
  19666. this.onEnd(status);
  19667. this.ended = true;
  19668. return status === c.Z_OK;
  19669. }
  19670. // callback interim results if Z_SYNC_FLUSH.
  19671. if (_mode === c.Z_SYNC_FLUSH) {
  19672. this.onEnd(c.Z_OK);
  19673. strm.avail_out = 0;
  19674. return true;
  19675. }
  19676. return true;
  19677. };
  19678. /**
  19679. * Inflate#onData(chunk) -> Void
  19680. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19681. * on js engine support. When string output requested, each chunk
  19682. * will be string.
  19683. *
  19684. * By default, stores data blocks in `chunks[]` property and glue
  19685. * those in `onEnd`. Override this handler, if you need another behaviour.
  19686. **/
  19687. Inflate.prototype.onData = function(chunk) {
  19688. this.chunks.push(chunk);
  19689. };
  19690. /**
  19691. * Inflate#onEnd(status) -> Void
  19692. * - status (Number): inflate status. 0 (Z_OK) on success,
  19693. * other if not.
  19694. *
  19695. * Called either after you tell inflate that the input stream is
  19696. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19697. * or if an error happened. By default - join collected chunks,
  19698. * free memory and fill `results` / `err` properties.
  19699. **/
  19700. Inflate.prototype.onEnd = function(status) {
  19701. // On success - join
  19702. if (status === c.Z_OK) {
  19703. if (this.options.to === 'string') {
  19704. // Glue & convert here, until we teach pako to send
  19705. // utf8 alligned strings to onData
  19706. this.result = this.chunks.join('');
  19707. } else {
  19708. this.result = utils.flattenChunks(this.chunks);
  19709. }
  19710. }
  19711. this.chunks = [];
  19712. this.err = status;
  19713. this.msg = this.strm.msg;
  19714. };
  19715. /**
  19716. * inflate(data[, options]) -> Uint8Array|Array|String
  19717. * - data (Uint8Array|Array|String): input data to decompress.
  19718. * - options (Object): zlib inflate options.
  19719. *
  19720. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19721. * format via wrapper header by default. That's why we don't provide
  19722. * separate `ungzip` method.
  19723. *
  19724. * Supported options are:
  19725. *
  19726. * - windowBits
  19727. *
  19728. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19729. * for more information.
  19730. *
  19731. * Sugar (options):
  19732. *
  19733. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19734. * negative windowBits implicitly.
  19735. * - `to` (String) - if equal to 'string', then result will be converted
  19736. * from utf8 to utf16 (javascript) string. When string output requested,
  19737. * chunk length can differ from `chunkSize`, depending on content.
  19738. *
  19739. *
  19740. * ##### Example:
  19741. *
  19742. * ```javascript
  19743. * var pako = require('pako')
  19744. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19745. * , output;
  19746. *
  19747. * try {
  19748. * output = pako.inflate(input);
  19749. * } catch (err)
  19750. * console.log(err);
  19751. * }
  19752. * ```
  19753. **/
  19754. function inflate(input, options) {
  19755. var inflator = new Inflate(options);
  19756. inflator.push(input, true);
  19757. // That will never happens, if you don't cheat with options :)
  19758. if (inflator.err) { throw inflator.msg; }
  19759. return inflator.result;
  19760. }
  19761. /**
  19762. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19763. * - data (Uint8Array|Array|String): input data to decompress.
  19764. * - options (Object): zlib inflate options.
  19765. *
  19766. * The same as [[inflate]], but creates raw data, without wrapper
  19767. * (header and adler32 crc).
  19768. **/
  19769. function inflateRaw(input, options) {
  19770. options = options || {};
  19771. options.raw = true;
  19772. return inflate(input, options);
  19773. }
  19774. /**
  19775. * ungzip(data[, options]) -> Uint8Array|Array|String
  19776. * - data (Uint8Array|Array|String): input data to decompress.
  19777. * - options (Object): zlib inflate options.
  19778. *
  19779. * Just shortcut to [[inflate]], because it autodetects format
  19780. * by header.content. Done for convenience.
  19781. **/
  19782. exports.Inflate = Inflate;
  19783. exports.inflate = inflate;
  19784. exports.inflateRaw = inflateRaw;
  19785. exports.ungzip = inflate;
  19786. },{"./utils/common":72,"./utils/strings":73,"./zlib/constants":75,"./zlib/gzheader":78,"./zlib/inflate.js":80,"./zlib/messages":82,"./zlib/zstream":84}],72:[function(require,module,exports){
  19787. 'use strict';
  19788. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19789. (typeof Uint16Array !== 'undefined') &&
  19790. (typeof Int32Array !== 'undefined');
  19791. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19792. var sources = Array.prototype.slice.call(arguments, 1);
  19793. while (sources.length) {
  19794. var source = sources.shift();
  19795. if (!source) { continue; }
  19796. if (typeof source !== 'object') {
  19797. throw new TypeError(source + 'must be non-object');
  19798. }
  19799. for (var p in source) {
  19800. if (source.hasOwnProperty(p)) {
  19801. obj[p] = source[p];
  19802. }
  19803. }
  19804. }
  19805. return obj;
  19806. };
  19807. // reduce buffer size, avoiding mem copy
  19808. exports.shrinkBuf = function (buf, size) {
  19809. if (buf.length === size) { return buf; }
  19810. if (buf.subarray) { return buf.subarray(0, size); }
  19811. buf.length = size;
  19812. return buf;
  19813. };
  19814. var fnTyped = {
  19815. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19816. if (src.subarray && dest.subarray) {
  19817. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19818. return;
  19819. }
  19820. // Fallback to ordinary array
  19821. for (var i=0; i<len; i++) {
  19822. dest[dest_offs + i] = src[src_offs + i];
  19823. }
  19824. },
  19825. // Join array of chunks to single array.
  19826. flattenChunks: function(chunks) {
  19827. var i, l, len, pos, chunk, result;
  19828. // calculate data length
  19829. len = 0;
  19830. for (i=0, l=chunks.length; i<l; i++) {
  19831. len += chunks[i].length;
  19832. }
  19833. // join chunks
  19834. result = new Uint8Array(len);
  19835. pos = 0;
  19836. for (i=0, l=chunks.length; i<l; i++) {
  19837. chunk = chunks[i];
  19838. result.set(chunk, pos);
  19839. pos += chunk.length;
  19840. }
  19841. return result;
  19842. }
  19843. };
  19844. var fnUntyped = {
  19845. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19846. for (var i=0; i<len; i++) {
  19847. dest[dest_offs + i] = src[src_offs + i];
  19848. }
  19849. },
  19850. // Join array of chunks to single array.
  19851. flattenChunks: function(chunks) {
  19852. return [].concat.apply([], chunks);
  19853. }
  19854. };
  19855. // Enable/Disable typed arrays use, for testing
  19856. //
  19857. exports.setTyped = function (on) {
  19858. if (on) {
  19859. exports.Buf8 = Uint8Array;
  19860. exports.Buf16 = Uint16Array;
  19861. exports.Buf32 = Int32Array;
  19862. exports.assign(exports, fnTyped);
  19863. } else {
  19864. exports.Buf8 = Array;
  19865. exports.Buf16 = Array;
  19866. exports.Buf32 = Array;
  19867. exports.assign(exports, fnUntyped);
  19868. }
  19869. };
  19870. exports.setTyped(TYPED_OK);
  19871. },{}],73:[function(require,module,exports){
  19872. // String encode/decode helpers
  19873. 'use strict';
  19874. var utils = require('./common');
  19875. // Quick check if we can use fast array to bin string conversion
  19876. //
  19877. // - apply(Array) can fail on Android 2.2
  19878. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19879. //
  19880. var STR_APPLY_OK = true;
  19881. var STR_APPLY_UIA_OK = true;
  19882. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19883. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  19884. // Table with utf8 lengths (calculated by first byte of sequence)
  19885. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  19886. // because max possible codepoint is 0x10ffff
  19887. var _utf8len = new utils.Buf8(256);
  19888. for (var q=0; q<256; q++) {
  19889. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  19890. }
  19891. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  19892. // convert string to array (typed, when possible)
  19893. exports.string2buf = function (str) {
  19894. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  19895. // count binary size
  19896. for (m_pos = 0; m_pos < str_len; m_pos++) {
  19897. c = str.charCodeAt(m_pos);
  19898. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19899. c2 = str.charCodeAt(m_pos+1);
  19900. if ((c2 & 0xfc00) === 0xdc00) {
  19901. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19902. m_pos++;
  19903. }
  19904. }
  19905. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  19906. }
  19907. // allocate buffer
  19908. buf = new utils.Buf8(buf_len);
  19909. // convert
  19910. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  19911. c = str.charCodeAt(m_pos);
  19912. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19913. c2 = str.charCodeAt(m_pos+1);
  19914. if ((c2 & 0xfc00) === 0xdc00) {
  19915. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19916. m_pos++;
  19917. }
  19918. }
  19919. if (c < 0x80) {
  19920. /* one byte */
  19921. buf[i++] = c;
  19922. } else if (c < 0x800) {
  19923. /* two bytes */
  19924. buf[i++] = 0xC0 | (c >>> 6);
  19925. buf[i++] = 0x80 | (c & 0x3f);
  19926. } else if (c < 0x10000) {
  19927. /* three bytes */
  19928. buf[i++] = 0xE0 | (c >>> 12);
  19929. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19930. buf[i++] = 0x80 | (c & 0x3f);
  19931. } else {
  19932. /* four bytes */
  19933. buf[i++] = 0xf0 | (c >>> 18);
  19934. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  19935. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19936. buf[i++] = 0x80 | (c & 0x3f);
  19937. }
  19938. }
  19939. return buf;
  19940. };
  19941. // Helper (used in 2 places)
  19942. function buf2binstring(buf, len) {
  19943. // use fallback for big arrays to avoid stack overflow
  19944. if (len < 65537) {
  19945. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  19946. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  19947. }
  19948. }
  19949. var result = '';
  19950. for (var i=0; i < len; i++) {
  19951. result += String.fromCharCode(buf[i]);
  19952. }
  19953. return result;
  19954. }
  19955. // Convert byte array to binary string
  19956. exports.buf2binstring = function(buf) {
  19957. return buf2binstring(buf, buf.length);
  19958. };
  19959. // Convert binary string (typed, when possible)
  19960. exports.binstring2buf = function(str) {
  19961. var buf = new utils.Buf8(str.length);
  19962. for (var i=0, len=buf.length; i < len; i++) {
  19963. buf[i] = str.charCodeAt(i);
  19964. }
  19965. return buf;
  19966. };
  19967. // convert array to string
  19968. exports.buf2string = function (buf, max) {
  19969. var i, out, c, c_len;
  19970. var len = max || buf.length;
  19971. // Reserve max possible length (2 words per char)
  19972. // NB: by unknown reasons, Array is significantly faster for
  19973. // String.fromCharCode.apply than Uint16Array.
  19974. var utf16buf = new Array(len*2);
  19975. for (out=0, i=0; i<len;) {
  19976. c = buf[i++];
  19977. // quick process ascii
  19978. if (c < 0x80) { utf16buf[out++] = c; continue; }
  19979. c_len = _utf8len[c];
  19980. // skip 5 & 6 byte codes
  19981. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  19982. // apply mask on first byte
  19983. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  19984. // join the rest
  19985. while (c_len > 1 && i < len) {
  19986. c = (c << 6) | (buf[i++] & 0x3f);
  19987. c_len--;
  19988. }
  19989. // terminated by end of string?
  19990. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  19991. if (c < 0x10000) {
  19992. utf16buf[out++] = c;
  19993. } else {
  19994. c -= 0x10000;
  19995. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  19996. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  19997. }
  19998. }
  19999. return buf2binstring(utf16buf, out);
  20000. };
  20001. // Calculate max possible position in utf8 buffer,
  20002. // that will not break sequence. If that's not possible
  20003. // - (very small limits) return max size as is.
  20004. //
  20005. // buf[] - utf8 bytes array
  20006. // max - length limit (mandatory);
  20007. exports.utf8border = function(buf, max) {
  20008. var pos;
  20009. max = max || buf.length;
  20010. if (max > buf.length) { max = buf.length; }
  20011. // go back from last position, until start of sequence found
  20012. pos = max-1;
  20013. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20014. // Fuckup - very small and broken sequence,
  20015. // return max, because we should return something anyway.
  20016. if (pos < 0) { return max; }
  20017. // If we came to start of buffer - that means vuffer is too small,
  20018. // return max too.
  20019. if (pos === 0) { return max; }
  20020. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20021. };
  20022. },{"./common":72}],74:[function(require,module,exports){
  20023. 'use strict';
  20024. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20025. // It doesn't worth to make additional optimizationa as in original.
  20026. // Small size is preferable.
  20027. function adler32(adler, buf, len, pos) {
  20028. var s1 = (adler & 0xffff) |0,
  20029. s2 = ((adler >>> 16) & 0xffff) |0,
  20030. n = 0;
  20031. while (len !== 0) {
  20032. // Set limit ~ twice less than 5552, to keep
  20033. // s2 in 31-bits, because we force signed ints.
  20034. // in other case %= will fail.
  20035. n = len > 2000 ? 2000 : len;
  20036. len -= n;
  20037. do {
  20038. s1 = (s1 + buf[pos++]) |0;
  20039. s2 = (s2 + s1) |0;
  20040. } while (--n);
  20041. s1 %= 65521;
  20042. s2 %= 65521;
  20043. }
  20044. return (s1 | (s2 << 16)) |0;
  20045. }
  20046. module.exports = adler32;
  20047. },{}],75:[function(require,module,exports){
  20048. module.exports = {
  20049. /* Allowed flush values; see deflate() and inflate() below for details */
  20050. Z_NO_FLUSH: 0,
  20051. Z_PARTIAL_FLUSH: 1,
  20052. Z_SYNC_FLUSH: 2,
  20053. Z_FULL_FLUSH: 3,
  20054. Z_FINISH: 4,
  20055. Z_BLOCK: 5,
  20056. Z_TREES: 6,
  20057. /* Return codes for the compression/decompression functions. Negative values
  20058. * are errors, positive values are used for special but normal events.
  20059. */
  20060. Z_OK: 0,
  20061. Z_STREAM_END: 1,
  20062. Z_NEED_DICT: 2,
  20063. Z_ERRNO: -1,
  20064. Z_STREAM_ERROR: -2,
  20065. Z_DATA_ERROR: -3,
  20066. //Z_MEM_ERROR: -4,
  20067. Z_BUF_ERROR: -5,
  20068. //Z_VERSION_ERROR: -6,
  20069. /* compression levels */
  20070. Z_NO_COMPRESSION: 0,
  20071. Z_BEST_SPEED: 1,
  20072. Z_BEST_COMPRESSION: 9,
  20073. Z_DEFAULT_COMPRESSION: -1,
  20074. Z_FILTERED: 1,
  20075. Z_HUFFMAN_ONLY: 2,
  20076. Z_RLE: 3,
  20077. Z_FIXED: 4,
  20078. Z_DEFAULT_STRATEGY: 0,
  20079. /* Possible values of the data_type field (though see inflate()) */
  20080. Z_BINARY: 0,
  20081. Z_TEXT: 1,
  20082. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20083. Z_UNKNOWN: 2,
  20084. /* The deflate compression method */
  20085. Z_DEFLATED: 8
  20086. //Z_NULL: null // Use -1 or null inline, depending on var type
  20087. };
  20088. },{}],76:[function(require,module,exports){
  20089. 'use strict';
  20090. // Note: we can't get significant speed boost here.
  20091. // So write code to minimize size - no pregenerated tables
  20092. // and array tools dependencies.
  20093. // Use ordinary array, since untyped makes no boost here
  20094. function makeTable() {
  20095. var c, table = [];
  20096. for (var n =0; n < 256; n++) {
  20097. c = n;
  20098. for (var k =0; k < 8; k++) {
  20099. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20100. }
  20101. table[n] = c;
  20102. }
  20103. return table;
  20104. }
  20105. // Create table on load. Just 255 signed longs. Not a problem.
  20106. var crcTable = makeTable();
  20107. function crc32(crc, buf, len, pos) {
  20108. var t = crcTable,
  20109. end = pos + len;
  20110. crc = crc ^ (-1);
  20111. for (var i = pos; i < end; i++) {
  20112. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20113. }
  20114. return (crc ^ (-1)); // >>> 0;
  20115. }
  20116. module.exports = crc32;
  20117. },{}],77:[function(require,module,exports){
  20118. 'use strict';
  20119. var utils = require('../utils/common');
  20120. var trees = require('./trees');
  20121. var adler32 = require('./adler32');
  20122. var crc32 = require('./crc32');
  20123. var msg = require('./messages');
  20124. /* Public constants ==========================================================*/
  20125. /* ===========================================================================*/
  20126. /* Allowed flush values; see deflate() and inflate() below for details */
  20127. var Z_NO_FLUSH = 0;
  20128. var Z_PARTIAL_FLUSH = 1;
  20129. //var Z_SYNC_FLUSH = 2;
  20130. var Z_FULL_FLUSH = 3;
  20131. var Z_FINISH = 4;
  20132. var Z_BLOCK = 5;
  20133. //var Z_TREES = 6;
  20134. /* Return codes for the compression/decompression functions. Negative values
  20135. * are errors, positive values are used for special but normal events.
  20136. */
  20137. var Z_OK = 0;
  20138. var Z_STREAM_END = 1;
  20139. //var Z_NEED_DICT = 2;
  20140. //var Z_ERRNO = -1;
  20141. var Z_STREAM_ERROR = -2;
  20142. var Z_DATA_ERROR = -3;
  20143. //var Z_MEM_ERROR = -4;
  20144. var Z_BUF_ERROR = -5;
  20145. //var Z_VERSION_ERROR = -6;
  20146. /* compression levels */
  20147. //var Z_NO_COMPRESSION = 0;
  20148. //var Z_BEST_SPEED = 1;
  20149. //var Z_BEST_COMPRESSION = 9;
  20150. var Z_DEFAULT_COMPRESSION = -1;
  20151. var Z_FILTERED = 1;
  20152. var Z_HUFFMAN_ONLY = 2;
  20153. var Z_RLE = 3;
  20154. var Z_FIXED = 4;
  20155. var Z_DEFAULT_STRATEGY = 0;
  20156. /* Possible values of the data_type field (though see inflate()) */
  20157. //var Z_BINARY = 0;
  20158. //var Z_TEXT = 1;
  20159. //var Z_ASCII = 1; // = Z_TEXT
  20160. var Z_UNKNOWN = 2;
  20161. /* The deflate compression method */
  20162. var Z_DEFLATED = 8;
  20163. /*============================================================================*/
  20164. var MAX_MEM_LEVEL = 9;
  20165. /* Maximum value for memLevel in deflateInit2 */
  20166. var MAX_WBITS = 15;
  20167. /* 32K LZ77 window */
  20168. var DEF_MEM_LEVEL = 8;
  20169. var LENGTH_CODES = 29;
  20170. /* number of length codes, not counting the special END_BLOCK code */
  20171. var LITERALS = 256;
  20172. /* number of literal bytes 0..255 */
  20173. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20174. /* number of Literal or Length codes, including the END_BLOCK code */
  20175. var D_CODES = 30;
  20176. /* number of distance codes */
  20177. var BL_CODES = 19;
  20178. /* number of codes used to transfer the bit lengths */
  20179. var HEAP_SIZE = 2*L_CODES + 1;
  20180. /* maximum heap size */
  20181. var MAX_BITS = 15;
  20182. /* All codes must not exceed MAX_BITS bits */
  20183. var MIN_MATCH = 3;
  20184. var MAX_MATCH = 258;
  20185. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20186. var PRESET_DICT = 0x20;
  20187. var INIT_STATE = 42;
  20188. var EXTRA_STATE = 69;
  20189. var NAME_STATE = 73;
  20190. var COMMENT_STATE = 91;
  20191. var HCRC_STATE = 103;
  20192. var BUSY_STATE = 113;
  20193. var FINISH_STATE = 666;
  20194. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20195. var BS_BLOCK_DONE = 2; /* block flush performed */
  20196. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20197. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20198. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20199. function err(strm, errorCode) {
  20200. strm.msg = msg[errorCode];
  20201. return errorCode;
  20202. }
  20203. function rank(f) {
  20204. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20205. }
  20206. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20207. /* =========================================================================
  20208. * Flush as much pending output as possible. All deflate() output goes
  20209. * through this function so some applications may wish to modify it
  20210. * to avoid allocating a large strm->output buffer and copying into it.
  20211. * (See also read_buf()).
  20212. */
  20213. function flush_pending(strm) {
  20214. var s = strm.state;
  20215. //_tr_flush_bits(s);
  20216. var len = s.pending;
  20217. if (len > strm.avail_out) {
  20218. len = strm.avail_out;
  20219. }
  20220. if (len === 0) { return; }
  20221. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20222. strm.next_out += len;
  20223. s.pending_out += len;
  20224. strm.total_out += len;
  20225. strm.avail_out -= len;
  20226. s.pending -= len;
  20227. if (s.pending === 0) {
  20228. s.pending_out = 0;
  20229. }
  20230. }
  20231. function flush_block_only (s, last) {
  20232. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20233. s.block_start = s.strstart;
  20234. flush_pending(s.strm);
  20235. }
  20236. function put_byte(s, b) {
  20237. s.pending_buf[s.pending++] = b;
  20238. }
  20239. /* =========================================================================
  20240. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20241. * IN assertion: the stream state is correct and there is enough room in
  20242. * pending_buf.
  20243. */
  20244. function putShortMSB(s, b) {
  20245. // put_byte(s, (Byte)(b >> 8));
  20246. // put_byte(s, (Byte)(b & 0xff));
  20247. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20248. s.pending_buf[s.pending++] = b & 0xff;
  20249. }
  20250. /* ===========================================================================
  20251. * Read a new buffer from the current input stream, update the adler32
  20252. * and total number of bytes read. All deflate() input goes through
  20253. * this function so some applications may wish to modify it to avoid
  20254. * allocating a large strm->input buffer and copying from it.
  20255. * (See also flush_pending()).
  20256. */
  20257. function read_buf(strm, buf, start, size) {
  20258. var len = strm.avail_in;
  20259. if (len > size) { len = size; }
  20260. if (len === 0) { return 0; }
  20261. strm.avail_in -= len;
  20262. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20263. if (strm.state.wrap === 1) {
  20264. strm.adler = adler32(strm.adler, buf, len, start);
  20265. }
  20266. else if (strm.state.wrap === 2) {
  20267. strm.adler = crc32(strm.adler, buf, len, start);
  20268. }
  20269. strm.next_in += len;
  20270. strm.total_in += len;
  20271. return len;
  20272. }
  20273. /* ===========================================================================
  20274. * Set match_start to the longest match starting at the given string and
  20275. * return its length. Matches shorter or equal to prev_length are discarded,
  20276. * in which case the result is equal to prev_length and match_start is
  20277. * garbage.
  20278. * IN assertions: cur_match is the head of the hash chain for the current
  20279. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20280. * OUT assertion: the match length is not greater than s->lookahead.
  20281. */
  20282. function longest_match(s, cur_match) {
  20283. var chain_length = s.max_chain_length; /* max hash chain length */
  20284. var scan = s.strstart; /* current string */
  20285. var match; /* matched string */
  20286. var len; /* length of current match */
  20287. var best_len = s.prev_length; /* best match length so far */
  20288. var nice_match = s.nice_match; /* stop if match long enough */
  20289. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20290. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20291. var _win = s.window; // shortcut
  20292. var wmask = s.w_mask;
  20293. var prev = s.prev;
  20294. /* Stop when cur_match becomes <= limit. To simplify the code,
  20295. * we prevent matches with the string of window index 0.
  20296. */
  20297. var strend = s.strstart + MAX_MATCH;
  20298. var scan_end1 = _win[scan + best_len - 1];
  20299. var scan_end = _win[scan + best_len];
  20300. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20301. * It is easy to get rid of this optimization if necessary.
  20302. */
  20303. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20304. /* Do not waste too much time if we already have a good match: */
  20305. if (s.prev_length >= s.good_match) {
  20306. chain_length >>= 2;
  20307. }
  20308. /* Do not look for matches beyond the end of the input. This is necessary
  20309. * to make deflate deterministic.
  20310. */
  20311. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20312. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20313. do {
  20314. // Assert(cur_match < s->strstart, "no future");
  20315. match = cur_match;
  20316. /* Skip to next match if the match length cannot increase
  20317. * or if the match length is less than 2. Note that the checks below
  20318. * for insufficient lookahead only occur occasionally for performance
  20319. * reasons. Therefore uninitialized memory will be accessed, and
  20320. * conditional jumps will be made that depend on those values.
  20321. * However the length of the match is limited to the lookahead, so
  20322. * the output of deflate is not affected by the uninitialized values.
  20323. */
  20324. if (_win[match + best_len] !== scan_end ||
  20325. _win[match + best_len - 1] !== scan_end1 ||
  20326. _win[match] !== _win[scan] ||
  20327. _win[++match] !== _win[scan + 1]) {
  20328. continue;
  20329. }
  20330. /* The check at best_len-1 can be removed because it will be made
  20331. * again later. (This heuristic is not always a win.)
  20332. * It is not necessary to compare scan[2] and match[2] since they
  20333. * are always equal when the other bytes match, given that
  20334. * the hash keys are equal and that HASH_BITS >= 8.
  20335. */
  20336. scan += 2;
  20337. match++;
  20338. // Assert(*scan == *match, "match[2]?");
  20339. /* We check for insufficient lookahead only every 8th comparison;
  20340. * the 256th check will be made at strstart+258.
  20341. */
  20342. do {
  20343. /*jshint noempty:false*/
  20344. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20345. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20346. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20347. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20348. scan < strend);
  20349. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20350. len = MAX_MATCH - (strend - scan);
  20351. scan = strend - MAX_MATCH;
  20352. if (len > best_len) {
  20353. s.match_start = cur_match;
  20354. best_len = len;
  20355. if (len >= nice_match) {
  20356. break;
  20357. }
  20358. scan_end1 = _win[scan + best_len - 1];
  20359. scan_end = _win[scan + best_len];
  20360. }
  20361. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20362. if (best_len <= s.lookahead) {
  20363. return best_len;
  20364. }
  20365. return s.lookahead;
  20366. }
  20367. /* ===========================================================================
  20368. * Fill the window when the lookahead becomes insufficient.
  20369. * Updates strstart and lookahead.
  20370. *
  20371. * IN assertion: lookahead < MIN_LOOKAHEAD
  20372. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20373. * At least one byte has been read, or avail_in == 0; reads are
  20374. * performed for at least two bytes (required for the zip translate_eol
  20375. * option -- not supported here).
  20376. */
  20377. function fill_window(s) {
  20378. var _w_size = s.w_size;
  20379. var p, n, m, more, str;
  20380. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20381. do {
  20382. more = s.window_size - s.lookahead - s.strstart;
  20383. // JS ints have 32 bit, block below not needed
  20384. /* Deal with !@#$% 64K limit: */
  20385. //if (sizeof(int) <= 2) {
  20386. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20387. // more = wsize;
  20388. //
  20389. // } else if (more == (unsigned)(-1)) {
  20390. // /* Very unlikely, but possible on 16 bit machine if
  20391. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20392. // */
  20393. // more--;
  20394. // }
  20395. //}
  20396. /* If the window is almost full and there is insufficient lookahead,
  20397. * move the upper half to the lower one to make room in the upper half.
  20398. */
  20399. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20400. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20401. s.match_start -= _w_size;
  20402. s.strstart -= _w_size;
  20403. /* we now have strstart >= MAX_DIST */
  20404. s.block_start -= _w_size;
  20405. /* Slide the hash table (could be avoided with 32 bit values
  20406. at the expense of memory usage). We slide even when level == 0
  20407. to keep the hash table consistent if we switch back to level > 0
  20408. later. (Using level 0 permanently is not an optimal usage of
  20409. zlib, so we don't care about this pathological case.)
  20410. */
  20411. n = s.hash_size;
  20412. p = n;
  20413. do {
  20414. m = s.head[--p];
  20415. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20416. } while (--n);
  20417. n = _w_size;
  20418. p = n;
  20419. do {
  20420. m = s.prev[--p];
  20421. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20422. /* If n is not on any hash chain, prev[n] is garbage but
  20423. * its value will never be used.
  20424. */
  20425. } while (--n);
  20426. more += _w_size;
  20427. }
  20428. if (s.strm.avail_in === 0) {
  20429. break;
  20430. }
  20431. /* If there was no sliding:
  20432. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20433. * more == window_size - lookahead - strstart
  20434. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20435. * => more >= window_size - 2*WSIZE + 2
  20436. * In the BIG_MEM or MMAP case (not yet supported),
  20437. * window_size == input_size + MIN_LOOKAHEAD &&
  20438. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20439. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20440. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20441. */
  20442. //Assert(more >= 2, "more < 2");
  20443. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20444. s.lookahead += n;
  20445. /* Initialize the hash value now that we have some input: */
  20446. if (s.lookahead + s.insert >= MIN_MATCH) {
  20447. str = s.strstart - s.insert;
  20448. s.ins_h = s.window[str];
  20449. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20450. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20451. //#if MIN_MATCH != 3
  20452. // Call update_hash() MIN_MATCH-3 more times
  20453. //#endif
  20454. while (s.insert) {
  20455. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20456. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20457. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20458. s.head[s.ins_h] = str;
  20459. str++;
  20460. s.insert--;
  20461. if (s.lookahead + s.insert < MIN_MATCH) {
  20462. break;
  20463. }
  20464. }
  20465. }
  20466. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20467. * but this is not important since only literal bytes will be emitted.
  20468. */
  20469. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20470. /* If the WIN_INIT bytes after the end of the current data have never been
  20471. * written, then zero those bytes in order to avoid memory check reports of
  20472. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20473. * the longest match routines. Update the high water mark for the next
  20474. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20475. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20476. */
  20477. // if (s.high_water < s.window_size) {
  20478. // var curr = s.strstart + s.lookahead;
  20479. // var init = 0;
  20480. //
  20481. // if (s.high_water < curr) {
  20482. // /* Previous high water mark below current data -- zero WIN_INIT
  20483. // * bytes or up to end of window, whichever is less.
  20484. // */
  20485. // init = s.window_size - curr;
  20486. // if (init > WIN_INIT)
  20487. // init = WIN_INIT;
  20488. // zmemzero(s->window + curr, (unsigned)init);
  20489. // s->high_water = curr + init;
  20490. // }
  20491. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20492. // /* High water mark at or above current data, but below current data
  20493. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20494. // * to end of window, whichever is less.
  20495. // */
  20496. // init = (ulg)curr + WIN_INIT - s->high_water;
  20497. // if (init > s->window_size - s->high_water)
  20498. // init = s->window_size - s->high_water;
  20499. // zmemzero(s->window + s->high_water, (unsigned)init);
  20500. // s->high_water += init;
  20501. // }
  20502. // }
  20503. //
  20504. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20505. // "not enough room for search");
  20506. }
  20507. /* ===========================================================================
  20508. * Copy without compression as much as possible from the input stream, return
  20509. * the current block state.
  20510. * This function does not insert new strings in the dictionary since
  20511. * uncompressible data is probably not useful. This function is used
  20512. * only for the level=0 compression option.
  20513. * NOTE: this function should be optimized to avoid extra copying from
  20514. * window to pending_buf.
  20515. */
  20516. function deflate_stored(s, flush) {
  20517. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20518. * to pending_buf_size, and each stored block has a 5 byte header:
  20519. */
  20520. var max_block_size = 0xffff;
  20521. if (max_block_size > s.pending_buf_size - 5) {
  20522. max_block_size = s.pending_buf_size - 5;
  20523. }
  20524. /* Copy as much as possible from input to output: */
  20525. for (;;) {
  20526. /* Fill the window as much as possible: */
  20527. if (s.lookahead <= 1) {
  20528. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20529. // s->block_start >= (long)s->w_size, "slide too late");
  20530. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20531. // s.block_start >= s.w_size)) {
  20532. // throw new Error("slide too late");
  20533. // }
  20534. fill_window(s);
  20535. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20536. return BS_NEED_MORE;
  20537. }
  20538. if (s.lookahead === 0) {
  20539. break;
  20540. }
  20541. /* flush the current block */
  20542. }
  20543. //Assert(s->block_start >= 0L, "block gone");
  20544. // if (s.block_start < 0) throw new Error("block gone");
  20545. s.strstart += s.lookahead;
  20546. s.lookahead = 0;
  20547. /* Emit a stored block if pending_buf will be full: */
  20548. var max_start = s.block_start + max_block_size;
  20549. if (s.strstart === 0 || s.strstart >= max_start) {
  20550. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20551. s.lookahead = s.strstart - max_start;
  20552. s.strstart = max_start;
  20553. /*** FLUSH_BLOCK(s, 0); ***/
  20554. flush_block_only(s, false);
  20555. if (s.strm.avail_out === 0) {
  20556. return BS_NEED_MORE;
  20557. }
  20558. /***/
  20559. }
  20560. /* Flush if we may have to slide, otherwise block_start may become
  20561. * negative and the data will be gone:
  20562. */
  20563. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20564. /*** FLUSH_BLOCK(s, 0); ***/
  20565. flush_block_only(s, false);
  20566. if (s.strm.avail_out === 0) {
  20567. return BS_NEED_MORE;
  20568. }
  20569. /***/
  20570. }
  20571. }
  20572. s.insert = 0;
  20573. if (flush === Z_FINISH) {
  20574. /*** FLUSH_BLOCK(s, 1); ***/
  20575. flush_block_only(s, true);
  20576. if (s.strm.avail_out === 0) {
  20577. return BS_FINISH_STARTED;
  20578. }
  20579. /***/
  20580. return BS_FINISH_DONE;
  20581. }
  20582. if (s.strstart > s.block_start) {
  20583. /*** FLUSH_BLOCK(s, 0); ***/
  20584. flush_block_only(s, false);
  20585. if (s.strm.avail_out === 0) {
  20586. return BS_NEED_MORE;
  20587. }
  20588. /***/
  20589. }
  20590. return BS_NEED_MORE;
  20591. }
  20592. /* ===========================================================================
  20593. * Compress as much as possible from the input stream, return the current
  20594. * block state.
  20595. * This function does not perform lazy evaluation of matches and inserts
  20596. * new strings in the dictionary only for unmatched strings or for short
  20597. * matches. It is used only for the fast compression options.
  20598. */
  20599. function deflate_fast(s, flush) {
  20600. var hash_head; /* head of the hash chain */
  20601. var bflush; /* set if current block must be flushed */
  20602. for (;;) {
  20603. /* Make sure that we always have enough lookahead, except
  20604. * at the end of the input file. We need MAX_MATCH bytes
  20605. * for the next match, plus MIN_MATCH bytes to insert the
  20606. * string following the next match.
  20607. */
  20608. if (s.lookahead < MIN_LOOKAHEAD) {
  20609. fill_window(s);
  20610. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20611. return BS_NEED_MORE;
  20612. }
  20613. if (s.lookahead === 0) {
  20614. break; /* flush the current block */
  20615. }
  20616. }
  20617. /* Insert the string window[strstart .. strstart+2] in the
  20618. * dictionary, and set hash_head to the head of the hash chain:
  20619. */
  20620. hash_head = 0/*NIL*/;
  20621. if (s.lookahead >= MIN_MATCH) {
  20622. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20623. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20624. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20625. s.head[s.ins_h] = s.strstart;
  20626. /***/
  20627. }
  20628. /* Find the longest match, discarding those <= prev_length.
  20629. * At this point we have always match_length < MIN_MATCH
  20630. */
  20631. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20632. /* To simplify the code, we prevent matches with the string
  20633. * of window index 0 (in particular we have to avoid a match
  20634. * of the string with itself at the start of the input file).
  20635. */
  20636. s.match_length = longest_match(s, hash_head);
  20637. /* longest_match() sets match_start */
  20638. }
  20639. if (s.match_length >= MIN_MATCH) {
  20640. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20641. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20642. s.match_length - MIN_MATCH, bflush); ***/
  20643. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20644. s.lookahead -= s.match_length;
  20645. /* Insert new strings in the hash table only if the match length
  20646. * is not too large. This saves time but degrades compression.
  20647. */
  20648. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20649. s.match_length--; /* string at strstart already in table */
  20650. do {
  20651. s.strstart++;
  20652. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20653. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20654. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20655. s.head[s.ins_h] = s.strstart;
  20656. /***/
  20657. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20658. * always MIN_MATCH bytes ahead.
  20659. */
  20660. } while (--s.match_length !== 0);
  20661. s.strstart++;
  20662. } else
  20663. {
  20664. s.strstart += s.match_length;
  20665. s.match_length = 0;
  20666. s.ins_h = s.window[s.strstart];
  20667. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20668. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20669. //#if MIN_MATCH != 3
  20670. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20671. //#endif
  20672. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20673. * matter since it will be recomputed at next deflate call.
  20674. */
  20675. }
  20676. } else {
  20677. /* No match, output a literal byte */
  20678. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20679. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20680. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20681. s.lookahead--;
  20682. s.strstart++;
  20683. }
  20684. if (bflush) {
  20685. /*** FLUSH_BLOCK(s, 0); ***/
  20686. flush_block_only(s, false);
  20687. if (s.strm.avail_out === 0) {
  20688. return BS_NEED_MORE;
  20689. }
  20690. /***/
  20691. }
  20692. }
  20693. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20694. if (flush === Z_FINISH) {
  20695. /*** FLUSH_BLOCK(s, 1); ***/
  20696. flush_block_only(s, true);
  20697. if (s.strm.avail_out === 0) {
  20698. return BS_FINISH_STARTED;
  20699. }
  20700. /***/
  20701. return BS_FINISH_DONE;
  20702. }
  20703. if (s.last_lit) {
  20704. /*** FLUSH_BLOCK(s, 0); ***/
  20705. flush_block_only(s, false);
  20706. if (s.strm.avail_out === 0) {
  20707. return BS_NEED_MORE;
  20708. }
  20709. /***/
  20710. }
  20711. return BS_BLOCK_DONE;
  20712. }
  20713. /* ===========================================================================
  20714. * Same as above, but achieves better compression. We use a lazy
  20715. * evaluation for matches: a match is finally adopted only if there is
  20716. * no better match at the next window position.
  20717. */
  20718. function deflate_slow(s, flush) {
  20719. var hash_head; /* head of hash chain */
  20720. var bflush; /* set if current block must be flushed */
  20721. var max_insert;
  20722. /* Process the input block. */
  20723. for (;;) {
  20724. /* Make sure that we always have enough lookahead, except
  20725. * at the end of the input file. We need MAX_MATCH bytes
  20726. * for the next match, plus MIN_MATCH bytes to insert the
  20727. * string following the next match.
  20728. */
  20729. if (s.lookahead < MIN_LOOKAHEAD) {
  20730. fill_window(s);
  20731. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20732. return BS_NEED_MORE;
  20733. }
  20734. if (s.lookahead === 0) { break; } /* flush the current block */
  20735. }
  20736. /* Insert the string window[strstart .. strstart+2] in the
  20737. * dictionary, and set hash_head to the head of the hash chain:
  20738. */
  20739. hash_head = 0/*NIL*/;
  20740. if (s.lookahead >= MIN_MATCH) {
  20741. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20742. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20743. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20744. s.head[s.ins_h] = s.strstart;
  20745. /***/
  20746. }
  20747. /* Find the longest match, discarding those <= prev_length.
  20748. */
  20749. s.prev_length = s.match_length;
  20750. s.prev_match = s.match_start;
  20751. s.match_length = MIN_MATCH-1;
  20752. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20753. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20754. /* To simplify the code, we prevent matches with the string
  20755. * of window index 0 (in particular we have to avoid a match
  20756. * of the string with itself at the start of the input file).
  20757. */
  20758. s.match_length = longest_match(s, hash_head);
  20759. /* longest_match() sets match_start */
  20760. if (s.match_length <= 5 &&
  20761. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20762. /* If prev_match is also MIN_MATCH, match_start is garbage
  20763. * but we will ignore the current match anyway.
  20764. */
  20765. s.match_length = MIN_MATCH-1;
  20766. }
  20767. }
  20768. /* If there was a match at the previous step and the current
  20769. * match is not better, output the previous match:
  20770. */
  20771. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20772. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20773. /* Do not insert strings in hash table beyond this. */
  20774. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20775. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20776. s.prev_length - MIN_MATCH, bflush);***/
  20777. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20778. /* Insert in hash table all strings up to the end of the match.
  20779. * strstart-1 and strstart are already inserted. If there is not
  20780. * enough lookahead, the last two strings are not inserted in
  20781. * the hash table.
  20782. */
  20783. s.lookahead -= s.prev_length-1;
  20784. s.prev_length -= 2;
  20785. do {
  20786. if (++s.strstart <= max_insert) {
  20787. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20788. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20789. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20790. s.head[s.ins_h] = s.strstart;
  20791. /***/
  20792. }
  20793. } while (--s.prev_length !== 0);
  20794. s.match_available = 0;
  20795. s.match_length = MIN_MATCH-1;
  20796. s.strstart++;
  20797. if (bflush) {
  20798. /*** FLUSH_BLOCK(s, 0); ***/
  20799. flush_block_only(s, false);
  20800. if (s.strm.avail_out === 0) {
  20801. return BS_NEED_MORE;
  20802. }
  20803. /***/
  20804. }
  20805. } else if (s.match_available) {
  20806. /* If there was no match at the previous position, output a
  20807. * single literal. If there was a match but the current match
  20808. * is longer, truncate the previous match to a single literal.
  20809. */
  20810. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20811. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20812. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20813. if (bflush) {
  20814. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20815. flush_block_only(s, false);
  20816. /***/
  20817. }
  20818. s.strstart++;
  20819. s.lookahead--;
  20820. if (s.strm.avail_out === 0) {
  20821. return BS_NEED_MORE;
  20822. }
  20823. } else {
  20824. /* There is no previous match to compare with, wait for
  20825. * the next step to decide.
  20826. */
  20827. s.match_available = 1;
  20828. s.strstart++;
  20829. s.lookahead--;
  20830. }
  20831. }
  20832. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20833. if (s.match_available) {
  20834. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20835. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20836. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20837. s.match_available = 0;
  20838. }
  20839. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20840. if (flush === Z_FINISH) {
  20841. /*** FLUSH_BLOCK(s, 1); ***/
  20842. flush_block_only(s, true);
  20843. if (s.strm.avail_out === 0) {
  20844. return BS_FINISH_STARTED;
  20845. }
  20846. /***/
  20847. return BS_FINISH_DONE;
  20848. }
  20849. if (s.last_lit) {
  20850. /*** FLUSH_BLOCK(s, 0); ***/
  20851. flush_block_only(s, false);
  20852. if (s.strm.avail_out === 0) {
  20853. return BS_NEED_MORE;
  20854. }
  20855. /***/
  20856. }
  20857. return BS_BLOCK_DONE;
  20858. }
  20859. /* ===========================================================================
  20860. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20861. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20862. * deflate switches away from Z_RLE.)
  20863. */
  20864. function deflate_rle(s, flush) {
  20865. var bflush; /* set if current block must be flushed */
  20866. var prev; /* byte at distance one to match */
  20867. var scan, strend; /* scan goes up to strend for length of run */
  20868. var _win = s.window;
  20869. for (;;) {
  20870. /* Make sure that we always have enough lookahead, except
  20871. * at the end of the input file. We need MAX_MATCH bytes
  20872. * for the longest run, plus one for the unrolled loop.
  20873. */
  20874. if (s.lookahead <= MAX_MATCH) {
  20875. fill_window(s);
  20876. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20877. return BS_NEED_MORE;
  20878. }
  20879. if (s.lookahead === 0) { break; } /* flush the current block */
  20880. }
  20881. /* See how many times the previous byte repeats */
  20882. s.match_length = 0;
  20883. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  20884. scan = s.strstart - 1;
  20885. prev = _win[scan];
  20886. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  20887. strend = s.strstart + MAX_MATCH;
  20888. do {
  20889. /*jshint noempty:false*/
  20890. } while (prev === _win[++scan] && prev === _win[++scan] &&
  20891. prev === _win[++scan] && prev === _win[++scan] &&
  20892. prev === _win[++scan] && prev === _win[++scan] &&
  20893. prev === _win[++scan] && prev === _win[++scan] &&
  20894. scan < strend);
  20895. s.match_length = MAX_MATCH - (strend - scan);
  20896. if (s.match_length > s.lookahead) {
  20897. s.match_length = s.lookahead;
  20898. }
  20899. }
  20900. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  20901. }
  20902. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  20903. if (s.match_length >= MIN_MATCH) {
  20904. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  20905. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  20906. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  20907. s.lookahead -= s.match_length;
  20908. s.strstart += s.match_length;
  20909. s.match_length = 0;
  20910. } else {
  20911. /* No match, output a literal byte */
  20912. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20913. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20914. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20915. s.lookahead--;
  20916. s.strstart++;
  20917. }
  20918. if (bflush) {
  20919. /*** FLUSH_BLOCK(s, 0); ***/
  20920. flush_block_only(s, false);
  20921. if (s.strm.avail_out === 0) {
  20922. return BS_NEED_MORE;
  20923. }
  20924. /***/
  20925. }
  20926. }
  20927. s.insert = 0;
  20928. if (flush === Z_FINISH) {
  20929. /*** FLUSH_BLOCK(s, 1); ***/
  20930. flush_block_only(s, true);
  20931. if (s.strm.avail_out === 0) {
  20932. return BS_FINISH_STARTED;
  20933. }
  20934. /***/
  20935. return BS_FINISH_DONE;
  20936. }
  20937. if (s.last_lit) {
  20938. /*** FLUSH_BLOCK(s, 0); ***/
  20939. flush_block_only(s, false);
  20940. if (s.strm.avail_out === 0) {
  20941. return BS_NEED_MORE;
  20942. }
  20943. /***/
  20944. }
  20945. return BS_BLOCK_DONE;
  20946. }
  20947. /* ===========================================================================
  20948. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  20949. * (It will be regenerated if this run of deflate switches away from Huffman.)
  20950. */
  20951. function deflate_huff(s, flush) {
  20952. var bflush; /* set if current block must be flushed */
  20953. for (;;) {
  20954. /* Make sure that we have a literal to write. */
  20955. if (s.lookahead === 0) {
  20956. fill_window(s);
  20957. if (s.lookahead === 0) {
  20958. if (flush === Z_NO_FLUSH) {
  20959. return BS_NEED_MORE;
  20960. }
  20961. break; /* flush the current block */
  20962. }
  20963. }
  20964. /* Output a literal byte */
  20965. s.match_length = 0;
  20966. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20967. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20968. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20969. s.lookahead--;
  20970. s.strstart++;
  20971. if (bflush) {
  20972. /*** FLUSH_BLOCK(s, 0); ***/
  20973. flush_block_only(s, false);
  20974. if (s.strm.avail_out === 0) {
  20975. return BS_NEED_MORE;
  20976. }
  20977. /***/
  20978. }
  20979. }
  20980. s.insert = 0;
  20981. if (flush === Z_FINISH) {
  20982. /*** FLUSH_BLOCK(s, 1); ***/
  20983. flush_block_only(s, true);
  20984. if (s.strm.avail_out === 0) {
  20985. return BS_FINISH_STARTED;
  20986. }
  20987. /***/
  20988. return BS_FINISH_DONE;
  20989. }
  20990. if (s.last_lit) {
  20991. /*** FLUSH_BLOCK(s, 0); ***/
  20992. flush_block_only(s, false);
  20993. if (s.strm.avail_out === 0) {
  20994. return BS_NEED_MORE;
  20995. }
  20996. /***/
  20997. }
  20998. return BS_BLOCK_DONE;
  20999. }
  21000. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21001. * the desired pack level (0..9). The values given below have been tuned to
  21002. * exclude worst case performance for pathological files. Better values may be
  21003. * found for specific files.
  21004. */
  21005. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21006. this.good_length = good_length;
  21007. this.max_lazy = max_lazy;
  21008. this.nice_length = nice_length;
  21009. this.max_chain = max_chain;
  21010. this.func = func;
  21011. };
  21012. var configuration_table;
  21013. configuration_table = [
  21014. /* good lazy nice chain */
  21015. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21016. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21017. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21018. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21019. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21020. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21021. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21022. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21023. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21024. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21025. ];
  21026. /* ===========================================================================
  21027. * Initialize the "longest match" routines for a new zlib stream
  21028. */
  21029. function lm_init(s) {
  21030. s.window_size = 2 * s.w_size;
  21031. /*** CLEAR_HASH(s); ***/
  21032. zero(s.head); // Fill with NIL (= 0);
  21033. /* Set the default configuration parameters:
  21034. */
  21035. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21036. s.good_match = configuration_table[s.level].good_length;
  21037. s.nice_match = configuration_table[s.level].nice_length;
  21038. s.max_chain_length = configuration_table[s.level].max_chain;
  21039. s.strstart = 0;
  21040. s.block_start = 0;
  21041. s.lookahead = 0;
  21042. s.insert = 0;
  21043. s.match_length = s.prev_length = MIN_MATCH - 1;
  21044. s.match_available = 0;
  21045. s.ins_h = 0;
  21046. }
  21047. function DeflateState() {
  21048. this.strm = null; /* pointer back to this zlib stream */
  21049. this.status = 0; /* as the name implies */
  21050. this.pending_buf = null; /* output still pending */
  21051. this.pending_buf_size = 0; /* size of pending_buf */
  21052. this.pending_out = 0; /* next pending byte to output to the stream */
  21053. this.pending = 0; /* nb of bytes in the pending buffer */
  21054. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21055. this.gzhead = null; /* gzip header information to write */
  21056. this.gzindex = 0; /* where in extra, name, or comment */
  21057. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21058. this.last_flush = -1; /* value of flush param for previous deflate call */
  21059. this.w_size = 0; /* LZ77 window size (32K by default) */
  21060. this.w_bits = 0; /* log2(w_size) (8..16) */
  21061. this.w_mask = 0; /* w_size - 1 */
  21062. this.window = null;
  21063. /* Sliding window. Input bytes are read into the second half of the window,
  21064. * and move to the first half later to keep a dictionary of at least wSize
  21065. * bytes. With this organization, matches are limited to a distance of
  21066. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21067. * performed with a length multiple of the block size.
  21068. */
  21069. this.window_size = 0;
  21070. /* Actual size of window: 2*wSize, except when the user input buffer
  21071. * is directly used as sliding window.
  21072. */
  21073. this.prev = null;
  21074. /* Link to older string with same hash index. To limit the size of this
  21075. * array to 64K, this link is maintained only for the last 32K strings.
  21076. * An index in this array is thus a window index modulo 32K.
  21077. */
  21078. this.head = null; /* Heads of the hash chains or NIL. */
  21079. this.ins_h = 0; /* hash index of string to be inserted */
  21080. this.hash_size = 0; /* number of elements in hash table */
  21081. this.hash_bits = 0; /* log2(hash_size) */
  21082. this.hash_mask = 0; /* hash_size-1 */
  21083. this.hash_shift = 0;
  21084. /* Number of bits by which ins_h must be shifted at each input
  21085. * step. It must be such that after MIN_MATCH steps, the oldest
  21086. * byte no longer takes part in the hash key, that is:
  21087. * hash_shift * MIN_MATCH >= hash_bits
  21088. */
  21089. this.block_start = 0;
  21090. /* Window position at the beginning of the current output block. Gets
  21091. * negative when the window is moved backwards.
  21092. */
  21093. this.match_length = 0; /* length of best match */
  21094. this.prev_match = 0; /* previous match */
  21095. this.match_available = 0; /* set if previous match exists */
  21096. this.strstart = 0; /* start of string to insert */
  21097. this.match_start = 0; /* start of matching string */
  21098. this.lookahead = 0; /* number of valid bytes ahead in window */
  21099. this.prev_length = 0;
  21100. /* Length of the best match at previous step. Matches not greater than this
  21101. * are discarded. This is used in the lazy match evaluation.
  21102. */
  21103. this.max_chain_length = 0;
  21104. /* To speed up deflation, hash chains are never searched beyond this
  21105. * length. A higher limit improves compression ratio but degrades the
  21106. * speed.
  21107. */
  21108. this.max_lazy_match = 0;
  21109. /* Attempt to find a better match only when the current match is strictly
  21110. * smaller than this value. This mechanism is used only for compression
  21111. * levels >= 4.
  21112. */
  21113. // That's alias to max_lazy_match, don't use directly
  21114. //this.max_insert_length = 0;
  21115. /* Insert new strings in the hash table only if the match length is not
  21116. * greater than this length. This saves time but degrades compression.
  21117. * max_insert_length is used only for compression levels <= 3.
  21118. */
  21119. this.level = 0; /* compression level (1..9) */
  21120. this.strategy = 0; /* favor or force Huffman coding*/
  21121. this.good_match = 0;
  21122. /* Use a faster search when the previous match is longer than this */
  21123. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21124. /* used by trees.c: */
  21125. /* Didn't use ct_data typedef below to suppress compiler warning */
  21126. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21127. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21128. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21129. // Use flat array of DOUBLE size, with interleaved fata,
  21130. // because JS does not support effective
  21131. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21132. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21133. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21134. zero(this.dyn_ltree);
  21135. zero(this.dyn_dtree);
  21136. zero(this.bl_tree);
  21137. this.l_desc = null; /* desc. for literal tree */
  21138. this.d_desc = null; /* desc. for distance tree */
  21139. this.bl_desc = null; /* desc. for bit length tree */
  21140. //ush bl_count[MAX_BITS+1];
  21141. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21142. /* number of codes at each bit length for an optimal tree */
  21143. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21144. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21145. zero(this.heap);
  21146. this.heap_len = 0; /* number of elements in the heap */
  21147. this.heap_max = 0; /* element of largest frequency */
  21148. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21149. * The same heap array is used to build all trees.
  21150. */
  21151. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21152. zero(this.depth);
  21153. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21154. */
  21155. this.l_buf = 0; /* buffer index for literals or lengths */
  21156. this.lit_bufsize = 0;
  21157. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21158. * limiting lit_bufsize to 64K:
  21159. * - frequencies can be kept in 16 bit counters
  21160. * - if compression is not successful for the first block, all input
  21161. * data is still in the window so we can still emit a stored block even
  21162. * when input comes from standard input. (This can also be done for
  21163. * all blocks if lit_bufsize is not greater than 32K.)
  21164. * - if compression is not successful for a file smaller than 64K, we can
  21165. * even emit a stored file instead of a stored block (saving 5 bytes).
  21166. * This is applicable only for zip (not gzip or zlib).
  21167. * - creating new Huffman trees less frequently may not provide fast
  21168. * adaptation to changes in the input data statistics. (Take for
  21169. * example a binary file with poorly compressible code followed by
  21170. * a highly compressible string table.) Smaller buffer sizes give
  21171. * fast adaptation but have of course the overhead of transmitting
  21172. * trees more frequently.
  21173. * - I can't count above 4
  21174. */
  21175. this.last_lit = 0; /* running index in l_buf */
  21176. this.d_buf = 0;
  21177. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21178. * the same number of elements. To use different lengths, an extra flag
  21179. * array would be necessary.
  21180. */
  21181. this.opt_len = 0; /* bit length of current block with optimal trees */
  21182. this.static_len = 0; /* bit length of current block with static trees */
  21183. this.matches = 0; /* number of string matches in current block */
  21184. this.insert = 0; /* bytes at end of window left to insert */
  21185. this.bi_buf = 0;
  21186. /* Output buffer. bits are inserted starting at the bottom (least
  21187. * significant bits).
  21188. */
  21189. this.bi_valid = 0;
  21190. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21191. * are always zero.
  21192. */
  21193. // Used for window memory init. We safely ignore it for JS. That makes
  21194. // sense only for pointers and memory check tools.
  21195. //this.high_water = 0;
  21196. /* High water mark offset in window for initialized bytes -- bytes above
  21197. * this are set to zero in order to avoid memory check warnings when
  21198. * longest match routines access bytes past the input. This is then
  21199. * updated to the new high water mark.
  21200. */
  21201. }
  21202. function deflateResetKeep(strm) {
  21203. var s;
  21204. if (!strm || !strm.state) {
  21205. return err(strm, Z_STREAM_ERROR);
  21206. }
  21207. strm.total_in = strm.total_out = 0;
  21208. strm.data_type = Z_UNKNOWN;
  21209. s = strm.state;
  21210. s.pending = 0;
  21211. s.pending_out = 0;
  21212. if (s.wrap < 0) {
  21213. s.wrap = -s.wrap;
  21214. /* was made negative by deflate(..., Z_FINISH); */
  21215. }
  21216. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21217. strm.adler = (s.wrap === 2) ?
  21218. 0 // crc32(0, Z_NULL, 0)
  21219. :
  21220. 1; // adler32(0, Z_NULL, 0)
  21221. s.last_flush = Z_NO_FLUSH;
  21222. trees._tr_init(s);
  21223. return Z_OK;
  21224. }
  21225. function deflateReset(strm) {
  21226. var ret = deflateResetKeep(strm);
  21227. if (ret === Z_OK) {
  21228. lm_init(strm.state);
  21229. }
  21230. return ret;
  21231. }
  21232. function deflateSetHeader(strm, head) {
  21233. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21234. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21235. strm.state.gzhead = head;
  21236. return Z_OK;
  21237. }
  21238. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21239. if (!strm) { // === Z_NULL
  21240. return Z_STREAM_ERROR;
  21241. }
  21242. var wrap = 1;
  21243. if (level === Z_DEFAULT_COMPRESSION) {
  21244. level = 6;
  21245. }
  21246. if (windowBits < 0) { /* suppress zlib wrapper */
  21247. wrap = 0;
  21248. windowBits = -windowBits;
  21249. }
  21250. else if (windowBits > 15) {
  21251. wrap = 2; /* write gzip wrapper instead */
  21252. windowBits -= 16;
  21253. }
  21254. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21255. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21256. strategy < 0 || strategy > Z_FIXED) {
  21257. return err(strm, Z_STREAM_ERROR);
  21258. }
  21259. if (windowBits === 8) {
  21260. windowBits = 9;
  21261. }
  21262. /* until 256-byte window bug fixed */
  21263. var s = new DeflateState();
  21264. strm.state = s;
  21265. s.strm = strm;
  21266. s.wrap = wrap;
  21267. s.gzhead = null;
  21268. s.w_bits = windowBits;
  21269. s.w_size = 1 << s.w_bits;
  21270. s.w_mask = s.w_size - 1;
  21271. s.hash_bits = memLevel + 7;
  21272. s.hash_size = 1 << s.hash_bits;
  21273. s.hash_mask = s.hash_size - 1;
  21274. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21275. s.window = new utils.Buf8(s.w_size * 2);
  21276. s.head = new utils.Buf16(s.hash_size);
  21277. s.prev = new utils.Buf16(s.w_size);
  21278. // Don't need mem init magic for JS.
  21279. //s.high_water = 0; /* nothing written to s->window yet */
  21280. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21281. s.pending_buf_size = s.lit_bufsize * 4;
  21282. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21283. s.d_buf = s.lit_bufsize >> 1;
  21284. s.l_buf = (1 + 2) * s.lit_bufsize;
  21285. s.level = level;
  21286. s.strategy = strategy;
  21287. s.method = method;
  21288. return deflateReset(strm);
  21289. }
  21290. function deflateInit(strm, level) {
  21291. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21292. }
  21293. function deflate(strm, flush) {
  21294. var old_flush, s;
  21295. var beg, val; // for gzip header write only
  21296. if (!strm || !strm.state ||
  21297. flush > Z_BLOCK || flush < 0) {
  21298. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21299. }
  21300. s = strm.state;
  21301. if (!strm.output ||
  21302. (!strm.input && strm.avail_in !== 0) ||
  21303. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21304. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21305. }
  21306. s.strm = strm; /* just in case */
  21307. old_flush = s.last_flush;
  21308. s.last_flush = flush;
  21309. /* Write the header */
  21310. if (s.status === INIT_STATE) {
  21311. if (s.wrap === 2) { // GZIP header
  21312. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21313. put_byte(s, 31);
  21314. put_byte(s, 139);
  21315. put_byte(s, 8);
  21316. if (!s.gzhead) { // s->gzhead == Z_NULL
  21317. put_byte(s, 0);
  21318. put_byte(s, 0);
  21319. put_byte(s, 0);
  21320. put_byte(s, 0);
  21321. put_byte(s, 0);
  21322. put_byte(s, s.level === 9 ? 2 :
  21323. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21324. 4 : 0));
  21325. put_byte(s, OS_CODE);
  21326. s.status = BUSY_STATE;
  21327. }
  21328. else {
  21329. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21330. (s.gzhead.hcrc ? 2 : 0) +
  21331. (!s.gzhead.extra ? 0 : 4) +
  21332. (!s.gzhead.name ? 0 : 8) +
  21333. (!s.gzhead.comment ? 0 : 16)
  21334. );
  21335. put_byte(s, s.gzhead.time & 0xff);
  21336. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21337. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21338. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21339. put_byte(s, s.level === 9 ? 2 :
  21340. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21341. 4 : 0));
  21342. put_byte(s, s.gzhead.os & 0xff);
  21343. if (s.gzhead.extra && s.gzhead.extra.length) {
  21344. put_byte(s, s.gzhead.extra.length & 0xff);
  21345. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21346. }
  21347. if (s.gzhead.hcrc) {
  21348. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21349. }
  21350. s.gzindex = 0;
  21351. s.status = EXTRA_STATE;
  21352. }
  21353. }
  21354. else // DEFLATE header
  21355. {
  21356. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21357. var level_flags = -1;
  21358. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21359. level_flags = 0;
  21360. } else if (s.level < 6) {
  21361. level_flags = 1;
  21362. } else if (s.level === 6) {
  21363. level_flags = 2;
  21364. } else {
  21365. level_flags = 3;
  21366. }
  21367. header |= (level_flags << 6);
  21368. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21369. header += 31 - (header % 31);
  21370. s.status = BUSY_STATE;
  21371. putShortMSB(s, header);
  21372. /* Save the adler32 of the preset dictionary: */
  21373. if (s.strstart !== 0) {
  21374. putShortMSB(s, strm.adler >>> 16);
  21375. putShortMSB(s, strm.adler & 0xffff);
  21376. }
  21377. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21378. }
  21379. }
  21380. //#ifdef GZIP
  21381. if (s.status === EXTRA_STATE) {
  21382. if (s.gzhead.extra/* != Z_NULL*/) {
  21383. beg = s.pending; /* start of bytes to update crc */
  21384. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21385. if (s.pending === s.pending_buf_size) {
  21386. if (s.gzhead.hcrc && s.pending > beg) {
  21387. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21388. }
  21389. flush_pending(strm);
  21390. beg = s.pending;
  21391. if (s.pending === s.pending_buf_size) {
  21392. break;
  21393. }
  21394. }
  21395. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21396. s.gzindex++;
  21397. }
  21398. if (s.gzhead.hcrc && s.pending > beg) {
  21399. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21400. }
  21401. if (s.gzindex === s.gzhead.extra.length) {
  21402. s.gzindex = 0;
  21403. s.status = NAME_STATE;
  21404. }
  21405. }
  21406. else {
  21407. s.status = NAME_STATE;
  21408. }
  21409. }
  21410. if (s.status === NAME_STATE) {
  21411. if (s.gzhead.name/* != Z_NULL*/) {
  21412. beg = s.pending; /* start of bytes to update crc */
  21413. //int val;
  21414. do {
  21415. if (s.pending === s.pending_buf_size) {
  21416. if (s.gzhead.hcrc && s.pending > beg) {
  21417. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21418. }
  21419. flush_pending(strm);
  21420. beg = s.pending;
  21421. if (s.pending === s.pending_buf_size) {
  21422. val = 1;
  21423. break;
  21424. }
  21425. }
  21426. // JS specific: little magic to add zero terminator to end of string
  21427. if (s.gzindex < s.gzhead.name.length) {
  21428. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21429. } else {
  21430. val = 0;
  21431. }
  21432. put_byte(s, val);
  21433. } while (val !== 0);
  21434. if (s.gzhead.hcrc && s.pending > beg) {
  21435. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21436. }
  21437. if (val === 0) {
  21438. s.gzindex = 0;
  21439. s.status = COMMENT_STATE;
  21440. }
  21441. }
  21442. else {
  21443. s.status = COMMENT_STATE;
  21444. }
  21445. }
  21446. if (s.status === COMMENT_STATE) {
  21447. if (s.gzhead.comment/* != Z_NULL*/) {
  21448. beg = s.pending; /* start of bytes to update crc */
  21449. //int val;
  21450. do {
  21451. if (s.pending === s.pending_buf_size) {
  21452. if (s.gzhead.hcrc && s.pending > beg) {
  21453. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21454. }
  21455. flush_pending(strm);
  21456. beg = s.pending;
  21457. if (s.pending === s.pending_buf_size) {
  21458. val = 1;
  21459. break;
  21460. }
  21461. }
  21462. // JS specific: little magic to add zero terminator to end of string
  21463. if (s.gzindex < s.gzhead.comment.length) {
  21464. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21465. } else {
  21466. val = 0;
  21467. }
  21468. put_byte(s, val);
  21469. } while (val !== 0);
  21470. if (s.gzhead.hcrc && s.pending > beg) {
  21471. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21472. }
  21473. if (val === 0) {
  21474. s.status = HCRC_STATE;
  21475. }
  21476. }
  21477. else {
  21478. s.status = HCRC_STATE;
  21479. }
  21480. }
  21481. if (s.status === HCRC_STATE) {
  21482. if (s.gzhead.hcrc) {
  21483. if (s.pending + 2 > s.pending_buf_size) {
  21484. flush_pending(strm);
  21485. }
  21486. if (s.pending + 2 <= s.pending_buf_size) {
  21487. put_byte(s, strm.adler & 0xff);
  21488. put_byte(s, (strm.adler >> 8) & 0xff);
  21489. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21490. s.status = BUSY_STATE;
  21491. }
  21492. }
  21493. else {
  21494. s.status = BUSY_STATE;
  21495. }
  21496. }
  21497. //#endif
  21498. /* Flush as much pending output as possible */
  21499. if (s.pending !== 0) {
  21500. flush_pending(strm);
  21501. if (strm.avail_out === 0) {
  21502. /* Since avail_out is 0, deflate will be called again with
  21503. * more output space, but possibly with both pending and
  21504. * avail_in equal to zero. There won't be anything to do,
  21505. * but this is not an error situation so make sure we
  21506. * return OK instead of BUF_ERROR at next call of deflate:
  21507. */
  21508. s.last_flush = -1;
  21509. return Z_OK;
  21510. }
  21511. /* Make sure there is something to do and avoid duplicate consecutive
  21512. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21513. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21514. */
  21515. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21516. flush !== Z_FINISH) {
  21517. return err(strm, Z_BUF_ERROR);
  21518. }
  21519. /* User must not provide more input after the first FINISH: */
  21520. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21521. return err(strm, Z_BUF_ERROR);
  21522. }
  21523. /* Start a new block or continue the current one.
  21524. */
  21525. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21526. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21527. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21528. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21529. configuration_table[s.level].func(s, flush));
  21530. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21531. s.status = FINISH_STATE;
  21532. }
  21533. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21534. if (strm.avail_out === 0) {
  21535. s.last_flush = -1;
  21536. /* avoid BUF_ERROR next call, see above */
  21537. }
  21538. return Z_OK;
  21539. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21540. * of deflate should use the same flush parameter to make sure
  21541. * that the flush is complete. So we don't have to output an
  21542. * empty block here, this will be done at next call. This also
  21543. * ensures that for a very small output buffer, we emit at most
  21544. * one empty block.
  21545. */
  21546. }
  21547. if (bstate === BS_BLOCK_DONE) {
  21548. if (flush === Z_PARTIAL_FLUSH) {
  21549. trees._tr_align(s);
  21550. }
  21551. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21552. trees._tr_stored_block(s, 0, 0, false);
  21553. /* For a full flush, this empty block will be recognized
  21554. * as a special marker by inflate_sync().
  21555. */
  21556. if (flush === Z_FULL_FLUSH) {
  21557. /*** CLEAR_HASH(s); ***/ /* forget history */
  21558. zero(s.head); // Fill with NIL (= 0);
  21559. if (s.lookahead === 0) {
  21560. s.strstart = 0;
  21561. s.block_start = 0;
  21562. s.insert = 0;
  21563. }
  21564. }
  21565. }
  21566. flush_pending(strm);
  21567. if (strm.avail_out === 0) {
  21568. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21569. return Z_OK;
  21570. }
  21571. }
  21572. }
  21573. //Assert(strm->avail_out > 0, "bug2");
  21574. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21575. if (flush !== Z_FINISH) { return Z_OK; }
  21576. if (s.wrap <= 0) { return Z_STREAM_END; }
  21577. /* Write the trailer */
  21578. if (s.wrap === 2) {
  21579. put_byte(s, strm.adler & 0xff);
  21580. put_byte(s, (strm.adler >> 8) & 0xff);
  21581. put_byte(s, (strm.adler >> 16) & 0xff);
  21582. put_byte(s, (strm.adler >> 24) & 0xff);
  21583. put_byte(s, strm.total_in & 0xff);
  21584. put_byte(s, (strm.total_in >> 8) & 0xff);
  21585. put_byte(s, (strm.total_in >> 16) & 0xff);
  21586. put_byte(s, (strm.total_in >> 24) & 0xff);
  21587. }
  21588. else
  21589. {
  21590. putShortMSB(s, strm.adler >>> 16);
  21591. putShortMSB(s, strm.adler & 0xffff);
  21592. }
  21593. flush_pending(strm);
  21594. /* If avail_out is zero, the application will call deflate again
  21595. * to flush the rest.
  21596. */
  21597. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21598. /* write the trailer only once! */
  21599. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21600. }
  21601. function deflateEnd(strm) {
  21602. var status;
  21603. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21604. return Z_STREAM_ERROR;
  21605. }
  21606. status = strm.state.status;
  21607. if (status !== INIT_STATE &&
  21608. status !== EXTRA_STATE &&
  21609. status !== NAME_STATE &&
  21610. status !== COMMENT_STATE &&
  21611. status !== HCRC_STATE &&
  21612. status !== BUSY_STATE &&
  21613. status !== FINISH_STATE
  21614. ) {
  21615. return err(strm, Z_STREAM_ERROR);
  21616. }
  21617. strm.state = null;
  21618. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21619. }
  21620. /* =========================================================================
  21621. * Copy the source state to the destination state
  21622. */
  21623. //function deflateCopy(dest, source) {
  21624. //
  21625. //}
  21626. exports.deflateInit = deflateInit;
  21627. exports.deflateInit2 = deflateInit2;
  21628. exports.deflateReset = deflateReset;
  21629. exports.deflateResetKeep = deflateResetKeep;
  21630. exports.deflateSetHeader = deflateSetHeader;
  21631. exports.deflate = deflate;
  21632. exports.deflateEnd = deflateEnd;
  21633. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21634. /* Not implemented
  21635. exports.deflateBound = deflateBound;
  21636. exports.deflateCopy = deflateCopy;
  21637. exports.deflateSetDictionary = deflateSetDictionary;
  21638. exports.deflateParams = deflateParams;
  21639. exports.deflatePending = deflatePending;
  21640. exports.deflatePrime = deflatePrime;
  21641. exports.deflateTune = deflateTune;
  21642. */
  21643. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./messages":82,"./trees":83}],78:[function(require,module,exports){
  21644. 'use strict';
  21645. function GZheader() {
  21646. /* true if compressed data believed to be text */
  21647. this.text = 0;
  21648. /* modification time */
  21649. this.time = 0;
  21650. /* extra flags (not used when writing a gzip file) */
  21651. this.xflags = 0;
  21652. /* operating system */
  21653. this.os = 0;
  21654. /* pointer to extra field or Z_NULL if none */
  21655. this.extra = null;
  21656. /* extra field length (valid if extra != Z_NULL) */
  21657. this.extra_len = 0; // Actually, we don't need it in JS,
  21658. // but leave for few code modifications
  21659. //
  21660. // Setup limits is not necessary because in js we should not preallocate memory
  21661. // for inflate use constant limit in 65536 bytes
  21662. //
  21663. /* space at extra (only when reading header) */
  21664. // this.extra_max = 0;
  21665. /* pointer to zero-terminated file name or Z_NULL */
  21666. this.name = '';
  21667. /* space at name (only when reading header) */
  21668. // this.name_max = 0;
  21669. /* pointer to zero-terminated comment or Z_NULL */
  21670. this.comment = '';
  21671. /* space at comment (only when reading header) */
  21672. // this.comm_max = 0;
  21673. /* true if there was or will be a header crc */
  21674. this.hcrc = 0;
  21675. /* true when done reading gzip header (not used when writing a gzip file) */
  21676. this.done = false;
  21677. }
  21678. module.exports = GZheader;
  21679. },{}],79:[function(require,module,exports){
  21680. 'use strict';
  21681. // See state defs from inflate.js
  21682. var BAD = 30; /* got a data error -- remain here until reset */
  21683. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21684. /*
  21685. Decode literal, length, and distance codes and write out the resulting
  21686. literal and match bytes until either not enough input or output is
  21687. available, an end-of-block is encountered, or a data error is encountered.
  21688. When large enough input and output buffers are supplied to inflate(), for
  21689. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21690. inflate execution time is spent in this routine.
  21691. Entry assumptions:
  21692. state.mode === LEN
  21693. strm.avail_in >= 6
  21694. strm.avail_out >= 258
  21695. start >= strm.avail_out
  21696. state.bits < 8
  21697. On return, state.mode is one of:
  21698. LEN -- ran out of enough output space or enough available input
  21699. TYPE -- reached end of block code, inflate() to interpret next block
  21700. BAD -- error in block data
  21701. Notes:
  21702. - The maximum input bits used by a length/distance pair is 15 bits for the
  21703. length code, 5 bits for the length extra, 15 bits for the distance code,
  21704. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21705. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21706. checking for available input while decoding.
  21707. - The maximum bytes that a single length/distance pair can output is 258
  21708. bytes, which is the maximum length that can be coded. inflate_fast()
  21709. requires strm.avail_out >= 258 for each loop to avoid checking for
  21710. output space.
  21711. */
  21712. module.exports = function inflate_fast(strm, start) {
  21713. var state;
  21714. var _in; /* local strm.input */
  21715. var last; /* have enough input while in < last */
  21716. var _out; /* local strm.output */
  21717. var beg; /* inflate()'s initial strm.output */
  21718. var end; /* while out < end, enough space available */
  21719. //#ifdef INFLATE_STRICT
  21720. var dmax; /* maximum distance from zlib header */
  21721. //#endif
  21722. var wsize; /* window size or zero if not using window */
  21723. var whave; /* valid bytes in the window */
  21724. var wnext; /* window write index */
  21725. var window; /* allocated sliding window, if wsize != 0 */
  21726. var hold; /* local strm.hold */
  21727. var bits; /* local strm.bits */
  21728. var lcode; /* local strm.lencode */
  21729. var dcode; /* local strm.distcode */
  21730. var lmask; /* mask for first level of length codes */
  21731. var dmask; /* mask for first level of distance codes */
  21732. var here; /* retrieved table entry */
  21733. var op; /* code bits, operation, extra bits, or */
  21734. /* window position, window bytes to copy */
  21735. var len; /* match length, unused bytes */
  21736. var dist; /* match distance */
  21737. var from; /* where to copy match from */
  21738. var from_source;
  21739. var input, output; // JS specific, because we have no pointers
  21740. /* copy state to local variables */
  21741. state = strm.state;
  21742. //here = state.here;
  21743. _in = strm.next_in;
  21744. input = strm.input;
  21745. last = _in + (strm.avail_in - 5);
  21746. _out = strm.next_out;
  21747. output = strm.output;
  21748. beg = _out - (start - strm.avail_out);
  21749. end = _out + (strm.avail_out - 257);
  21750. //#ifdef INFLATE_STRICT
  21751. dmax = state.dmax;
  21752. //#endif
  21753. wsize = state.wsize;
  21754. whave = state.whave;
  21755. wnext = state.wnext;
  21756. window = state.window;
  21757. hold = state.hold;
  21758. bits = state.bits;
  21759. lcode = state.lencode;
  21760. dcode = state.distcode;
  21761. lmask = (1 << state.lenbits) - 1;
  21762. dmask = (1 << state.distbits) - 1;
  21763. /* decode literals and length/distances until end-of-block or not enough
  21764. input data or output space */
  21765. top:
  21766. do {
  21767. if (bits < 15) {
  21768. hold += input[_in++] << bits;
  21769. bits += 8;
  21770. hold += input[_in++] << bits;
  21771. bits += 8;
  21772. }
  21773. here = lcode[hold & lmask];
  21774. dolen:
  21775. for (;;) { // Goto emulation
  21776. op = here >>> 24/*here.bits*/;
  21777. hold >>>= op;
  21778. bits -= op;
  21779. op = (here >>> 16) & 0xff/*here.op*/;
  21780. if (op === 0) { /* literal */
  21781. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21782. // "inflate: literal '%c'\n" :
  21783. // "inflate: literal 0x%02x\n", here.val));
  21784. output[_out++] = here & 0xffff/*here.val*/;
  21785. }
  21786. else if (op & 16) { /* length base */
  21787. len = here & 0xffff/*here.val*/;
  21788. op &= 15; /* number of extra bits */
  21789. if (op) {
  21790. if (bits < op) {
  21791. hold += input[_in++] << bits;
  21792. bits += 8;
  21793. }
  21794. len += hold & ((1 << op) - 1);
  21795. hold >>>= op;
  21796. bits -= op;
  21797. }
  21798. //Tracevv((stderr, "inflate: length %u\n", len));
  21799. if (bits < 15) {
  21800. hold += input[_in++] << bits;
  21801. bits += 8;
  21802. hold += input[_in++] << bits;
  21803. bits += 8;
  21804. }
  21805. here = dcode[hold & dmask];
  21806. dodist:
  21807. for (;;) { // goto emulation
  21808. op = here >>> 24/*here.bits*/;
  21809. hold >>>= op;
  21810. bits -= op;
  21811. op = (here >>> 16) & 0xff/*here.op*/;
  21812. if (op & 16) { /* distance base */
  21813. dist = here & 0xffff/*here.val*/;
  21814. op &= 15; /* number of extra bits */
  21815. if (bits < op) {
  21816. hold += input[_in++] << bits;
  21817. bits += 8;
  21818. if (bits < op) {
  21819. hold += input[_in++] << bits;
  21820. bits += 8;
  21821. }
  21822. }
  21823. dist += hold & ((1 << op) - 1);
  21824. //#ifdef INFLATE_STRICT
  21825. if (dist > dmax) {
  21826. strm.msg = 'invalid distance too far back';
  21827. state.mode = BAD;
  21828. break top;
  21829. }
  21830. //#endif
  21831. hold >>>= op;
  21832. bits -= op;
  21833. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21834. op = _out - beg; /* max distance in output */
  21835. if (dist > op) { /* see if copy from window */
  21836. op = dist - op; /* distance back in window */
  21837. if (op > whave) {
  21838. if (state.sane) {
  21839. strm.msg = 'invalid distance too far back';
  21840. state.mode = BAD;
  21841. break top;
  21842. }
  21843. // (!) This block is disabled in zlib defailts,
  21844. // don't enable it for binary compatibility
  21845. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21846. // if (len <= op - whave) {
  21847. // do {
  21848. // output[_out++] = 0;
  21849. // } while (--len);
  21850. // continue top;
  21851. // }
  21852. // len -= op - whave;
  21853. // do {
  21854. // output[_out++] = 0;
  21855. // } while (--op > whave);
  21856. // if (op === 0) {
  21857. // from = _out - dist;
  21858. // do {
  21859. // output[_out++] = output[from++];
  21860. // } while (--len);
  21861. // continue top;
  21862. // }
  21863. //#endif
  21864. }
  21865. from = 0; // window index
  21866. from_source = window;
  21867. if (wnext === 0) { /* very common case */
  21868. from += wsize - op;
  21869. if (op < len) { /* some from window */
  21870. len -= op;
  21871. do {
  21872. output[_out++] = window[from++];
  21873. } while (--op);
  21874. from = _out - dist; /* rest from output */
  21875. from_source = output;
  21876. }
  21877. }
  21878. else if (wnext < op) { /* wrap around window */
  21879. from += wsize + wnext - op;
  21880. op -= wnext;
  21881. if (op < len) { /* some from end of window */
  21882. len -= op;
  21883. do {
  21884. output[_out++] = window[from++];
  21885. } while (--op);
  21886. from = 0;
  21887. if (wnext < len) { /* some from start of window */
  21888. op = wnext;
  21889. len -= op;
  21890. do {
  21891. output[_out++] = window[from++];
  21892. } while (--op);
  21893. from = _out - dist; /* rest from output */
  21894. from_source = output;
  21895. }
  21896. }
  21897. }
  21898. else { /* contiguous in window */
  21899. from += wnext - op;
  21900. if (op < len) { /* some from window */
  21901. len -= op;
  21902. do {
  21903. output[_out++] = window[from++];
  21904. } while (--op);
  21905. from = _out - dist; /* rest from output */
  21906. from_source = output;
  21907. }
  21908. }
  21909. while (len > 2) {
  21910. output[_out++] = from_source[from++];
  21911. output[_out++] = from_source[from++];
  21912. output[_out++] = from_source[from++];
  21913. len -= 3;
  21914. }
  21915. if (len) {
  21916. output[_out++] = from_source[from++];
  21917. if (len > 1) {
  21918. output[_out++] = from_source[from++];
  21919. }
  21920. }
  21921. }
  21922. else {
  21923. from = _out - dist; /* copy direct from output */
  21924. do { /* minimum length is three */
  21925. output[_out++] = output[from++];
  21926. output[_out++] = output[from++];
  21927. output[_out++] = output[from++];
  21928. len -= 3;
  21929. } while (len > 2);
  21930. if (len) {
  21931. output[_out++] = output[from++];
  21932. if (len > 1) {
  21933. output[_out++] = output[from++];
  21934. }
  21935. }
  21936. }
  21937. }
  21938. else if ((op & 64) === 0) { /* 2nd level distance code */
  21939. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21940. continue dodist;
  21941. }
  21942. else {
  21943. strm.msg = 'invalid distance code';
  21944. state.mode = BAD;
  21945. break top;
  21946. }
  21947. break; // need to emulate goto via "continue"
  21948. }
  21949. }
  21950. else if ((op & 64) === 0) { /* 2nd level length code */
  21951. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21952. continue dolen;
  21953. }
  21954. else if (op & 32) { /* end-of-block */
  21955. //Tracevv((stderr, "inflate: end of block\n"));
  21956. state.mode = TYPE;
  21957. break top;
  21958. }
  21959. else {
  21960. strm.msg = 'invalid literal/length code';
  21961. state.mode = BAD;
  21962. break top;
  21963. }
  21964. break; // need to emulate goto via "continue"
  21965. }
  21966. } while (_in < last && _out < end);
  21967. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  21968. len = bits >> 3;
  21969. _in -= len;
  21970. bits -= len << 3;
  21971. hold &= (1 << bits) - 1;
  21972. /* update state and return */
  21973. strm.next_in = _in;
  21974. strm.next_out = _out;
  21975. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  21976. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  21977. state.hold = hold;
  21978. state.bits = bits;
  21979. return;
  21980. };
  21981. },{}],80:[function(require,module,exports){
  21982. 'use strict';
  21983. var utils = require('../utils/common');
  21984. var adler32 = require('./adler32');
  21985. var crc32 = require('./crc32');
  21986. var inflate_fast = require('./inffast');
  21987. var inflate_table = require('./inftrees');
  21988. var CODES = 0;
  21989. var LENS = 1;
  21990. var DISTS = 2;
  21991. /* Public constants ==========================================================*/
  21992. /* ===========================================================================*/
  21993. /* Allowed flush values; see deflate() and inflate() below for details */
  21994. //var Z_NO_FLUSH = 0;
  21995. //var Z_PARTIAL_FLUSH = 1;
  21996. //var Z_SYNC_FLUSH = 2;
  21997. //var Z_FULL_FLUSH = 3;
  21998. var Z_FINISH = 4;
  21999. var Z_BLOCK = 5;
  22000. var Z_TREES = 6;
  22001. /* Return codes for the compression/decompression functions. Negative values
  22002. * are errors, positive values are used for special but normal events.
  22003. */
  22004. var Z_OK = 0;
  22005. var Z_STREAM_END = 1;
  22006. var Z_NEED_DICT = 2;
  22007. //var Z_ERRNO = -1;
  22008. var Z_STREAM_ERROR = -2;
  22009. var Z_DATA_ERROR = -3;
  22010. var Z_MEM_ERROR = -4;
  22011. var Z_BUF_ERROR = -5;
  22012. //var Z_VERSION_ERROR = -6;
  22013. /* The deflate compression method */
  22014. var Z_DEFLATED = 8;
  22015. /* STATES ====================================================================*/
  22016. /* ===========================================================================*/
  22017. var HEAD = 1; /* i: waiting for magic header */
  22018. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22019. var TIME = 3; /* i: waiting for modification time (gzip) */
  22020. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22021. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22022. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22023. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22024. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22025. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22026. var DICTID = 10; /* i: waiting for dictionary check value */
  22027. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22028. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22029. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22030. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22031. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22032. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22033. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22034. var LENLENS = 18; /* i: waiting for code length code lengths */
  22035. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22036. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22037. var LEN = 21; /* i: waiting for length/lit/eob code */
  22038. var LENEXT = 22; /* i: waiting for length extra bits */
  22039. var DIST = 23; /* i: waiting for distance code */
  22040. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22041. var MATCH = 25; /* o: waiting for output space to copy string */
  22042. var LIT = 26; /* o: waiting for output space to write literal */
  22043. var CHECK = 27; /* i: waiting for 32-bit check value */
  22044. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22045. var DONE = 29; /* finished check, done -- remain here until reset */
  22046. var BAD = 30; /* got a data error -- remain here until reset */
  22047. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22048. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22049. /* ===========================================================================*/
  22050. var ENOUGH_LENS = 852;
  22051. var ENOUGH_DISTS = 592;
  22052. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22053. var MAX_WBITS = 15;
  22054. /* 32K LZ77 window */
  22055. var DEF_WBITS = MAX_WBITS;
  22056. function ZSWAP32(q) {
  22057. return (((q >>> 24) & 0xff) +
  22058. ((q >>> 8) & 0xff00) +
  22059. ((q & 0xff00) << 8) +
  22060. ((q & 0xff) << 24));
  22061. }
  22062. function InflateState() {
  22063. this.mode = 0; /* current inflate mode */
  22064. this.last = false; /* true if processing last block */
  22065. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22066. this.havedict = false; /* true if dictionary provided */
  22067. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22068. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22069. this.check = 0; /* protected copy of check value */
  22070. this.total = 0; /* protected copy of output count */
  22071. // TODO: may be {}
  22072. this.head = null; /* where to save gzip header information */
  22073. /* sliding window */
  22074. this.wbits = 0; /* log base 2 of requested window size */
  22075. this.wsize = 0; /* window size or zero if not using window */
  22076. this.whave = 0; /* valid bytes in the window */
  22077. this.wnext = 0; /* window write index */
  22078. this.window = null; /* allocated sliding window, if needed */
  22079. /* bit accumulator */
  22080. this.hold = 0; /* input bit accumulator */
  22081. this.bits = 0; /* number of bits in "in" */
  22082. /* for string and stored block copying */
  22083. this.length = 0; /* literal or length of data to copy */
  22084. this.offset = 0; /* distance back to copy string from */
  22085. /* for table and code decoding */
  22086. this.extra = 0; /* extra bits needed */
  22087. /* fixed and dynamic code tables */
  22088. this.lencode = null; /* starting table for length/literal codes */
  22089. this.distcode = null; /* starting table for distance codes */
  22090. this.lenbits = 0; /* index bits for lencode */
  22091. this.distbits = 0; /* index bits for distcode */
  22092. /* dynamic table building */
  22093. this.ncode = 0; /* number of code length code lengths */
  22094. this.nlen = 0; /* number of length code lengths */
  22095. this.ndist = 0; /* number of distance code lengths */
  22096. this.have = 0; /* number of code lengths in lens[] */
  22097. this.next = null; /* next available space in codes[] */
  22098. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22099. this.work = new utils.Buf16(288); /* work area for code table building */
  22100. /*
  22101. because we don't have pointers in js, we use lencode and distcode directly
  22102. as buffers so we don't need codes
  22103. */
  22104. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22105. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22106. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22107. this.sane = 0; /* if false, allow invalid distance too far */
  22108. this.back = 0; /* bits back of last unprocessed length/lit */
  22109. this.was = 0; /* initial length of match */
  22110. }
  22111. function inflateResetKeep(strm) {
  22112. var state;
  22113. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22114. state = strm.state;
  22115. strm.total_in = strm.total_out = state.total = 0;
  22116. strm.msg = ''; /*Z_NULL*/
  22117. if (state.wrap) { /* to support ill-conceived Java test suite */
  22118. strm.adler = state.wrap & 1;
  22119. }
  22120. state.mode = HEAD;
  22121. state.last = 0;
  22122. state.havedict = 0;
  22123. state.dmax = 32768;
  22124. state.head = null/*Z_NULL*/;
  22125. state.hold = 0;
  22126. state.bits = 0;
  22127. //state.lencode = state.distcode = state.next = state.codes;
  22128. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22129. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22130. state.sane = 1;
  22131. state.back = -1;
  22132. //Tracev((stderr, "inflate: reset\n"));
  22133. return Z_OK;
  22134. }
  22135. function inflateReset(strm) {
  22136. var state;
  22137. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22138. state = strm.state;
  22139. state.wsize = 0;
  22140. state.whave = 0;
  22141. state.wnext = 0;
  22142. return inflateResetKeep(strm);
  22143. }
  22144. function inflateReset2(strm, windowBits) {
  22145. var wrap;
  22146. var state;
  22147. /* get the state */
  22148. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22149. state = strm.state;
  22150. /* extract wrap request from windowBits parameter */
  22151. if (windowBits < 0) {
  22152. wrap = 0;
  22153. windowBits = -windowBits;
  22154. }
  22155. else {
  22156. wrap = (windowBits >> 4) + 1;
  22157. if (windowBits < 48) {
  22158. windowBits &= 15;
  22159. }
  22160. }
  22161. /* set number of window bits, free window if different */
  22162. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22163. return Z_STREAM_ERROR;
  22164. }
  22165. if (state.window !== null && state.wbits !== windowBits) {
  22166. state.window = null;
  22167. }
  22168. /* update state and reset the rest of it */
  22169. state.wrap = wrap;
  22170. state.wbits = windowBits;
  22171. return inflateReset(strm);
  22172. }
  22173. function inflateInit2(strm, windowBits) {
  22174. var ret;
  22175. var state;
  22176. if (!strm) { return Z_STREAM_ERROR; }
  22177. //strm.msg = Z_NULL; /* in case we return an error */
  22178. state = new InflateState();
  22179. //if (state === Z_NULL) return Z_MEM_ERROR;
  22180. //Tracev((stderr, "inflate: allocated\n"));
  22181. strm.state = state;
  22182. state.window = null/*Z_NULL*/;
  22183. ret = inflateReset2(strm, windowBits);
  22184. if (ret !== Z_OK) {
  22185. strm.state = null/*Z_NULL*/;
  22186. }
  22187. return ret;
  22188. }
  22189. function inflateInit(strm) {
  22190. return inflateInit2(strm, DEF_WBITS);
  22191. }
  22192. /*
  22193. Return state with length and distance decoding tables and index sizes set to
  22194. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22195. If BUILDFIXED is defined, then instead this routine builds the tables the
  22196. first time it's called, and returns those tables the first time and
  22197. thereafter. This reduces the size of the code by about 2K bytes, in
  22198. exchange for a little execution time. However, BUILDFIXED should not be
  22199. used for threaded applications, since the rewriting of the tables and virgin
  22200. may not be thread-safe.
  22201. */
  22202. var virgin = true;
  22203. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22204. function fixedtables(state) {
  22205. /* build fixed huffman tables if first call (may not be thread safe) */
  22206. if (virgin) {
  22207. var sym;
  22208. lenfix = new utils.Buf32(512);
  22209. distfix = new utils.Buf32(32);
  22210. /* literal/length table */
  22211. sym = 0;
  22212. while (sym < 144) { state.lens[sym++] = 8; }
  22213. while (sym < 256) { state.lens[sym++] = 9; }
  22214. while (sym < 280) { state.lens[sym++] = 7; }
  22215. while (sym < 288) { state.lens[sym++] = 8; }
  22216. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22217. /* distance table */
  22218. sym = 0;
  22219. while (sym < 32) { state.lens[sym++] = 5; }
  22220. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22221. /* do this just once */
  22222. virgin = false;
  22223. }
  22224. state.lencode = lenfix;
  22225. state.lenbits = 9;
  22226. state.distcode = distfix;
  22227. state.distbits = 5;
  22228. }
  22229. /*
  22230. Update the window with the last wsize (normally 32K) bytes written before
  22231. returning. If window does not exist yet, create it. This is only called
  22232. when a window is already in use, or when output has been written during this
  22233. inflate call, but the end of the deflate stream has not been reached yet.
  22234. It is also called to create a window for dictionary data when a dictionary
  22235. is loaded.
  22236. Providing output buffers larger than 32K to inflate() should provide a speed
  22237. advantage, since only the last 32K of output is copied to the sliding window
  22238. upon return from inflate(), and since all distances after the first 32K of
  22239. output will fall in the output data, making match copies simpler and faster.
  22240. The advantage may be dependent on the size of the processor's data caches.
  22241. */
  22242. function updatewindow(strm, src, end, copy) {
  22243. var dist;
  22244. var state = strm.state;
  22245. /* if it hasn't been done already, allocate space for the window */
  22246. if (state.window === null) {
  22247. state.wsize = 1 << state.wbits;
  22248. state.wnext = 0;
  22249. state.whave = 0;
  22250. state.window = new utils.Buf8(state.wsize);
  22251. }
  22252. /* copy state->wsize or less output bytes into the circular window */
  22253. if (copy >= state.wsize) {
  22254. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22255. state.wnext = 0;
  22256. state.whave = state.wsize;
  22257. }
  22258. else {
  22259. dist = state.wsize - state.wnext;
  22260. if (dist > copy) {
  22261. dist = copy;
  22262. }
  22263. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22264. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22265. copy -= dist;
  22266. if (copy) {
  22267. //zmemcpy(state->window, end - copy, copy);
  22268. utils.arraySet(state.window,src, end - copy, copy, 0);
  22269. state.wnext = copy;
  22270. state.whave = state.wsize;
  22271. }
  22272. else {
  22273. state.wnext += dist;
  22274. if (state.wnext === state.wsize) { state.wnext = 0; }
  22275. if (state.whave < state.wsize) { state.whave += dist; }
  22276. }
  22277. }
  22278. return 0;
  22279. }
  22280. function inflate(strm, flush) {
  22281. var state;
  22282. var input, output; // input/output buffers
  22283. var next; /* next input INDEX */
  22284. var put; /* next output INDEX */
  22285. var have, left; /* available input and output */
  22286. var hold; /* bit buffer */
  22287. var bits; /* bits in bit buffer */
  22288. var _in, _out; /* save starting available input and output */
  22289. var copy; /* number of stored or match bytes to copy */
  22290. var from; /* where to copy match bytes from */
  22291. var from_source;
  22292. var here = 0; /* current decoding table entry */
  22293. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22294. //var last; /* parent table entry */
  22295. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22296. var len; /* length to copy for repeats, bits to drop */
  22297. var ret; /* return code */
  22298. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22299. var opts;
  22300. var n; // temporary var for NEED_BITS
  22301. var order = /* permutation of code lengths */
  22302. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22303. if (!strm || !strm.state || !strm.output ||
  22304. (!strm.input && strm.avail_in !== 0)) {
  22305. return Z_STREAM_ERROR;
  22306. }
  22307. state = strm.state;
  22308. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22309. //--- LOAD() ---
  22310. put = strm.next_out;
  22311. output = strm.output;
  22312. left = strm.avail_out;
  22313. next = strm.next_in;
  22314. input = strm.input;
  22315. have = strm.avail_in;
  22316. hold = state.hold;
  22317. bits = state.bits;
  22318. //---
  22319. _in = have;
  22320. _out = left;
  22321. ret = Z_OK;
  22322. inf_leave: // goto emulation
  22323. for (;;) {
  22324. switch (state.mode) {
  22325. case HEAD:
  22326. if (state.wrap === 0) {
  22327. state.mode = TYPEDO;
  22328. break;
  22329. }
  22330. //=== NEEDBITS(16);
  22331. while (bits < 16) {
  22332. if (have === 0) { break inf_leave; }
  22333. have--;
  22334. hold += input[next++] << bits;
  22335. bits += 8;
  22336. }
  22337. //===//
  22338. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22339. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22340. //=== CRC2(state.check, hold);
  22341. hbuf[0] = hold & 0xff;
  22342. hbuf[1] = (hold >>> 8) & 0xff;
  22343. state.check = crc32(state.check, hbuf, 2, 0);
  22344. //===//
  22345. //=== INITBITS();
  22346. hold = 0;
  22347. bits = 0;
  22348. //===//
  22349. state.mode = FLAGS;
  22350. break;
  22351. }
  22352. state.flags = 0; /* expect zlib header */
  22353. if (state.head) {
  22354. state.head.done = false;
  22355. }
  22356. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22357. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22358. strm.msg = 'incorrect header check';
  22359. state.mode = BAD;
  22360. break;
  22361. }
  22362. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22363. strm.msg = 'unknown compression method';
  22364. state.mode = BAD;
  22365. break;
  22366. }
  22367. //--- DROPBITS(4) ---//
  22368. hold >>>= 4;
  22369. bits -= 4;
  22370. //---//
  22371. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22372. if (state.wbits === 0) {
  22373. state.wbits = len;
  22374. }
  22375. else if (len > state.wbits) {
  22376. strm.msg = 'invalid window size';
  22377. state.mode = BAD;
  22378. break;
  22379. }
  22380. state.dmax = 1 << len;
  22381. //Tracev((stderr, "inflate: zlib header ok\n"));
  22382. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22383. state.mode = hold & 0x200 ? DICTID : TYPE;
  22384. //=== INITBITS();
  22385. hold = 0;
  22386. bits = 0;
  22387. //===//
  22388. break;
  22389. case FLAGS:
  22390. //=== NEEDBITS(16); */
  22391. while (bits < 16) {
  22392. if (have === 0) { break inf_leave; }
  22393. have--;
  22394. hold += input[next++] << bits;
  22395. bits += 8;
  22396. }
  22397. //===//
  22398. state.flags = hold;
  22399. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22400. strm.msg = 'unknown compression method';
  22401. state.mode = BAD;
  22402. break;
  22403. }
  22404. if (state.flags & 0xe000) {
  22405. strm.msg = 'unknown header flags set';
  22406. state.mode = BAD;
  22407. break;
  22408. }
  22409. if (state.head) {
  22410. state.head.text = ((hold >> 8) & 1);
  22411. }
  22412. if (state.flags & 0x0200) {
  22413. //=== CRC2(state.check, hold);
  22414. hbuf[0] = hold & 0xff;
  22415. hbuf[1] = (hold >>> 8) & 0xff;
  22416. state.check = crc32(state.check, hbuf, 2, 0);
  22417. //===//
  22418. }
  22419. //=== INITBITS();
  22420. hold = 0;
  22421. bits = 0;
  22422. //===//
  22423. state.mode = TIME;
  22424. /* falls through */
  22425. case TIME:
  22426. //=== NEEDBITS(32); */
  22427. while (bits < 32) {
  22428. if (have === 0) { break inf_leave; }
  22429. have--;
  22430. hold += input[next++] << bits;
  22431. bits += 8;
  22432. }
  22433. //===//
  22434. if (state.head) {
  22435. state.head.time = hold;
  22436. }
  22437. if (state.flags & 0x0200) {
  22438. //=== CRC4(state.check, hold)
  22439. hbuf[0] = hold & 0xff;
  22440. hbuf[1] = (hold >>> 8) & 0xff;
  22441. hbuf[2] = (hold >>> 16) & 0xff;
  22442. hbuf[3] = (hold >>> 24) & 0xff;
  22443. state.check = crc32(state.check, hbuf, 4, 0);
  22444. //===
  22445. }
  22446. //=== INITBITS();
  22447. hold = 0;
  22448. bits = 0;
  22449. //===//
  22450. state.mode = OS;
  22451. /* falls through */
  22452. case OS:
  22453. //=== NEEDBITS(16); */
  22454. while (bits < 16) {
  22455. if (have === 0) { break inf_leave; }
  22456. have--;
  22457. hold += input[next++] << bits;
  22458. bits += 8;
  22459. }
  22460. //===//
  22461. if (state.head) {
  22462. state.head.xflags = (hold & 0xff);
  22463. state.head.os = (hold >> 8);
  22464. }
  22465. if (state.flags & 0x0200) {
  22466. //=== CRC2(state.check, hold);
  22467. hbuf[0] = hold & 0xff;
  22468. hbuf[1] = (hold >>> 8) & 0xff;
  22469. state.check = crc32(state.check, hbuf, 2, 0);
  22470. //===//
  22471. }
  22472. //=== INITBITS();
  22473. hold = 0;
  22474. bits = 0;
  22475. //===//
  22476. state.mode = EXLEN;
  22477. /* falls through */
  22478. case EXLEN:
  22479. if (state.flags & 0x0400) {
  22480. //=== NEEDBITS(16); */
  22481. while (bits < 16) {
  22482. if (have === 0) { break inf_leave; }
  22483. have--;
  22484. hold += input[next++] << bits;
  22485. bits += 8;
  22486. }
  22487. //===//
  22488. state.length = hold;
  22489. if (state.head) {
  22490. state.head.extra_len = hold;
  22491. }
  22492. if (state.flags & 0x0200) {
  22493. //=== CRC2(state.check, hold);
  22494. hbuf[0] = hold & 0xff;
  22495. hbuf[1] = (hold >>> 8) & 0xff;
  22496. state.check = crc32(state.check, hbuf, 2, 0);
  22497. //===//
  22498. }
  22499. //=== INITBITS();
  22500. hold = 0;
  22501. bits = 0;
  22502. //===//
  22503. }
  22504. else if (state.head) {
  22505. state.head.extra = null/*Z_NULL*/;
  22506. }
  22507. state.mode = EXTRA;
  22508. /* falls through */
  22509. case EXTRA:
  22510. if (state.flags & 0x0400) {
  22511. copy = state.length;
  22512. if (copy > have) { copy = have; }
  22513. if (copy) {
  22514. if (state.head) {
  22515. len = state.head.extra_len - state.length;
  22516. if (!state.head.extra) {
  22517. // Use untyped array for more conveniend processing later
  22518. state.head.extra = new Array(state.head.extra_len);
  22519. }
  22520. utils.arraySet(
  22521. state.head.extra,
  22522. input,
  22523. next,
  22524. // extra field is limited to 65536 bytes
  22525. // - no need for additional size check
  22526. copy,
  22527. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22528. len
  22529. );
  22530. //zmemcpy(state.head.extra + len, next,
  22531. // len + copy > state.head.extra_max ?
  22532. // state.head.extra_max - len : copy);
  22533. }
  22534. if (state.flags & 0x0200) {
  22535. state.check = crc32(state.check, input, copy, next);
  22536. }
  22537. have -= copy;
  22538. next += copy;
  22539. state.length -= copy;
  22540. }
  22541. if (state.length) { break inf_leave; }
  22542. }
  22543. state.length = 0;
  22544. state.mode = NAME;
  22545. /* falls through */
  22546. case NAME:
  22547. if (state.flags & 0x0800) {
  22548. if (have === 0) { break inf_leave; }
  22549. copy = 0;
  22550. do {
  22551. // TODO: 2 or 1 bytes?
  22552. len = input[next + copy++];
  22553. /* use constant limit because in js we should not preallocate memory */
  22554. if (state.head && len &&
  22555. (state.length < 65536 /*state.head.name_max*/)) {
  22556. state.head.name += String.fromCharCode(len);
  22557. }
  22558. } while (len && copy < have);
  22559. if (state.flags & 0x0200) {
  22560. state.check = crc32(state.check, input, copy, next);
  22561. }
  22562. have -= copy;
  22563. next += copy;
  22564. if (len) { break inf_leave; }
  22565. }
  22566. else if (state.head) {
  22567. state.head.name = null;
  22568. }
  22569. state.length = 0;
  22570. state.mode = COMMENT;
  22571. /* falls through */
  22572. case COMMENT:
  22573. if (state.flags & 0x1000) {
  22574. if (have === 0) { break inf_leave; }
  22575. copy = 0;
  22576. do {
  22577. len = input[next + copy++];
  22578. /* use constant limit because in js we should not preallocate memory */
  22579. if (state.head && len &&
  22580. (state.length < 65536 /*state.head.comm_max*/)) {
  22581. state.head.comment += String.fromCharCode(len);
  22582. }
  22583. } while (len && copy < have);
  22584. if (state.flags & 0x0200) {
  22585. state.check = crc32(state.check, input, copy, next);
  22586. }
  22587. have -= copy;
  22588. next += copy;
  22589. if (len) { break inf_leave; }
  22590. }
  22591. else if (state.head) {
  22592. state.head.comment = null;
  22593. }
  22594. state.mode = HCRC;
  22595. /* falls through */
  22596. case HCRC:
  22597. if (state.flags & 0x0200) {
  22598. //=== NEEDBITS(16); */
  22599. while (bits < 16) {
  22600. if (have === 0) { break inf_leave; }
  22601. have--;
  22602. hold += input[next++] << bits;
  22603. bits += 8;
  22604. }
  22605. //===//
  22606. if (hold !== (state.check & 0xffff)) {
  22607. strm.msg = 'header crc mismatch';
  22608. state.mode = BAD;
  22609. break;
  22610. }
  22611. //=== INITBITS();
  22612. hold = 0;
  22613. bits = 0;
  22614. //===//
  22615. }
  22616. if (state.head) {
  22617. state.head.hcrc = ((state.flags >> 9) & 1);
  22618. state.head.done = true;
  22619. }
  22620. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22621. state.mode = TYPE;
  22622. break;
  22623. case DICTID:
  22624. //=== NEEDBITS(32); */
  22625. while (bits < 32) {
  22626. if (have === 0) { break inf_leave; }
  22627. have--;
  22628. hold += input[next++] << bits;
  22629. bits += 8;
  22630. }
  22631. //===//
  22632. strm.adler = state.check = ZSWAP32(hold);
  22633. //=== INITBITS();
  22634. hold = 0;
  22635. bits = 0;
  22636. //===//
  22637. state.mode = DICT;
  22638. /* falls through */
  22639. case DICT:
  22640. if (state.havedict === 0) {
  22641. //--- RESTORE() ---
  22642. strm.next_out = put;
  22643. strm.avail_out = left;
  22644. strm.next_in = next;
  22645. strm.avail_in = have;
  22646. state.hold = hold;
  22647. state.bits = bits;
  22648. //---
  22649. return Z_NEED_DICT;
  22650. }
  22651. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22652. state.mode = TYPE;
  22653. /* falls through */
  22654. case TYPE:
  22655. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22656. /* falls through */
  22657. case TYPEDO:
  22658. if (state.last) {
  22659. //--- BYTEBITS() ---//
  22660. hold >>>= bits & 7;
  22661. bits -= bits & 7;
  22662. //---//
  22663. state.mode = CHECK;
  22664. break;
  22665. }
  22666. //=== NEEDBITS(3); */
  22667. while (bits < 3) {
  22668. if (have === 0) { break inf_leave; }
  22669. have--;
  22670. hold += input[next++] << bits;
  22671. bits += 8;
  22672. }
  22673. //===//
  22674. state.last = (hold & 0x01)/*BITS(1)*/;
  22675. //--- DROPBITS(1) ---//
  22676. hold >>>= 1;
  22677. bits -= 1;
  22678. //---//
  22679. switch ((hold & 0x03)/*BITS(2)*/) {
  22680. case 0: /* stored block */
  22681. //Tracev((stderr, "inflate: stored block%s\n",
  22682. // state.last ? " (last)" : ""));
  22683. state.mode = STORED;
  22684. break;
  22685. case 1: /* fixed block */
  22686. fixedtables(state);
  22687. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22688. // state.last ? " (last)" : ""));
  22689. state.mode = LEN_; /* decode codes */
  22690. if (flush === Z_TREES) {
  22691. //--- DROPBITS(2) ---//
  22692. hold >>>= 2;
  22693. bits -= 2;
  22694. //---//
  22695. break inf_leave;
  22696. }
  22697. break;
  22698. case 2: /* dynamic block */
  22699. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22700. // state.last ? " (last)" : ""));
  22701. state.mode = TABLE;
  22702. break;
  22703. case 3:
  22704. strm.msg = 'invalid block type';
  22705. state.mode = BAD;
  22706. }
  22707. //--- DROPBITS(2) ---//
  22708. hold >>>= 2;
  22709. bits -= 2;
  22710. //---//
  22711. break;
  22712. case STORED:
  22713. //--- BYTEBITS() ---// /* go to byte boundary */
  22714. hold >>>= bits & 7;
  22715. bits -= bits & 7;
  22716. //---//
  22717. //=== NEEDBITS(32); */
  22718. while (bits < 32) {
  22719. if (have === 0) { break inf_leave; }
  22720. have--;
  22721. hold += input[next++] << bits;
  22722. bits += 8;
  22723. }
  22724. //===//
  22725. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22726. strm.msg = 'invalid stored block lengths';
  22727. state.mode = BAD;
  22728. break;
  22729. }
  22730. state.length = hold & 0xffff;
  22731. //Tracev((stderr, "inflate: stored length %u\n",
  22732. // state.length));
  22733. //=== INITBITS();
  22734. hold = 0;
  22735. bits = 0;
  22736. //===//
  22737. state.mode = COPY_;
  22738. if (flush === Z_TREES) { break inf_leave; }
  22739. /* falls through */
  22740. case COPY_:
  22741. state.mode = COPY;
  22742. /* falls through */
  22743. case COPY:
  22744. copy = state.length;
  22745. if (copy) {
  22746. if (copy > have) { copy = have; }
  22747. if (copy > left) { copy = left; }
  22748. if (copy === 0) { break inf_leave; }
  22749. //--- zmemcpy(put, next, copy); ---
  22750. utils.arraySet(output, input, next, copy, put);
  22751. //---//
  22752. have -= copy;
  22753. next += copy;
  22754. left -= copy;
  22755. put += copy;
  22756. state.length -= copy;
  22757. break;
  22758. }
  22759. //Tracev((stderr, "inflate: stored end\n"));
  22760. state.mode = TYPE;
  22761. break;
  22762. case TABLE:
  22763. //=== NEEDBITS(14); */
  22764. while (bits < 14) {
  22765. if (have === 0) { break inf_leave; }
  22766. have--;
  22767. hold += input[next++] << bits;
  22768. bits += 8;
  22769. }
  22770. //===//
  22771. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22772. //--- DROPBITS(5) ---//
  22773. hold >>>= 5;
  22774. bits -= 5;
  22775. //---//
  22776. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22777. //--- DROPBITS(5) ---//
  22778. hold >>>= 5;
  22779. bits -= 5;
  22780. //---//
  22781. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22782. //--- DROPBITS(4) ---//
  22783. hold >>>= 4;
  22784. bits -= 4;
  22785. //---//
  22786. //#ifndef PKZIP_BUG_WORKAROUND
  22787. if (state.nlen > 286 || state.ndist > 30) {
  22788. strm.msg = 'too many length or distance symbols';
  22789. state.mode = BAD;
  22790. break;
  22791. }
  22792. //#endif
  22793. //Tracev((stderr, "inflate: table sizes ok\n"));
  22794. state.have = 0;
  22795. state.mode = LENLENS;
  22796. /* falls through */
  22797. case LENLENS:
  22798. while (state.have < state.ncode) {
  22799. //=== NEEDBITS(3);
  22800. while (bits < 3) {
  22801. if (have === 0) { break inf_leave; }
  22802. have--;
  22803. hold += input[next++] << bits;
  22804. bits += 8;
  22805. }
  22806. //===//
  22807. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22808. //--- DROPBITS(3) ---//
  22809. hold >>>= 3;
  22810. bits -= 3;
  22811. //---//
  22812. }
  22813. while (state.have < 19) {
  22814. state.lens[order[state.have++]] = 0;
  22815. }
  22816. // We have separate tables & no pointers. 2 commented lines below not needed.
  22817. //state.next = state.codes;
  22818. //state.lencode = state.next;
  22819. // Switch to use dynamic table
  22820. state.lencode = state.lendyn;
  22821. state.lenbits = 7;
  22822. opts = {bits: state.lenbits};
  22823. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22824. state.lenbits = opts.bits;
  22825. if (ret) {
  22826. strm.msg = 'invalid code lengths set';
  22827. state.mode = BAD;
  22828. break;
  22829. }
  22830. //Tracev((stderr, "inflate: code lengths ok\n"));
  22831. state.have = 0;
  22832. state.mode = CODELENS;
  22833. /* falls through */
  22834. case CODELENS:
  22835. while (state.have < state.nlen + state.ndist) {
  22836. for (;;) {
  22837. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22838. here_bits = here >>> 24;
  22839. here_op = (here >>> 16) & 0xff;
  22840. here_val = here & 0xffff;
  22841. if ((here_bits) <= bits) { break; }
  22842. //--- PULLBYTE() ---//
  22843. if (have === 0) { break inf_leave; }
  22844. have--;
  22845. hold += input[next++] << bits;
  22846. bits += 8;
  22847. //---//
  22848. }
  22849. if (here_val < 16) {
  22850. //--- DROPBITS(here.bits) ---//
  22851. hold >>>= here_bits;
  22852. bits -= here_bits;
  22853. //---//
  22854. state.lens[state.have++] = here_val;
  22855. }
  22856. else {
  22857. if (here_val === 16) {
  22858. //=== NEEDBITS(here.bits + 2);
  22859. n = here_bits + 2;
  22860. while (bits < n) {
  22861. if (have === 0) { break inf_leave; }
  22862. have--;
  22863. hold += input[next++] << bits;
  22864. bits += 8;
  22865. }
  22866. //===//
  22867. //--- DROPBITS(here.bits) ---//
  22868. hold >>>= here_bits;
  22869. bits -= here_bits;
  22870. //---//
  22871. if (state.have === 0) {
  22872. strm.msg = 'invalid bit length repeat';
  22873. state.mode = BAD;
  22874. break;
  22875. }
  22876. len = state.lens[state.have - 1];
  22877. copy = 3 + (hold & 0x03);//BITS(2);
  22878. //--- DROPBITS(2) ---//
  22879. hold >>>= 2;
  22880. bits -= 2;
  22881. //---//
  22882. }
  22883. else if (here_val === 17) {
  22884. //=== NEEDBITS(here.bits + 3);
  22885. n = here_bits + 3;
  22886. while (bits < n) {
  22887. if (have === 0) { break inf_leave; }
  22888. have--;
  22889. hold += input[next++] << bits;
  22890. bits += 8;
  22891. }
  22892. //===//
  22893. //--- DROPBITS(here.bits) ---//
  22894. hold >>>= here_bits;
  22895. bits -= here_bits;
  22896. //---//
  22897. len = 0;
  22898. copy = 3 + (hold & 0x07);//BITS(3);
  22899. //--- DROPBITS(3) ---//
  22900. hold >>>= 3;
  22901. bits -= 3;
  22902. //---//
  22903. }
  22904. else {
  22905. //=== NEEDBITS(here.bits + 7);
  22906. n = here_bits + 7;
  22907. while (bits < n) {
  22908. if (have === 0) { break inf_leave; }
  22909. have--;
  22910. hold += input[next++] << bits;
  22911. bits += 8;
  22912. }
  22913. //===//
  22914. //--- DROPBITS(here.bits) ---//
  22915. hold >>>= here_bits;
  22916. bits -= here_bits;
  22917. //---//
  22918. len = 0;
  22919. copy = 11 + (hold & 0x7f);//BITS(7);
  22920. //--- DROPBITS(7) ---//
  22921. hold >>>= 7;
  22922. bits -= 7;
  22923. //---//
  22924. }
  22925. if (state.have + copy > state.nlen + state.ndist) {
  22926. strm.msg = 'invalid bit length repeat';
  22927. state.mode = BAD;
  22928. break;
  22929. }
  22930. while (copy--) {
  22931. state.lens[state.have++] = len;
  22932. }
  22933. }
  22934. }
  22935. /* handle error breaks in while */
  22936. if (state.mode === BAD) { break; }
  22937. /* check for end-of-block code (better have one) */
  22938. if (state.lens[256] === 0) {
  22939. strm.msg = 'invalid code -- missing end-of-block';
  22940. state.mode = BAD;
  22941. break;
  22942. }
  22943. /* build code tables -- note: do not change the lenbits or distbits
  22944. values here (9 and 6) without reading the comments in inftrees.h
  22945. concerning the ENOUGH constants, which depend on those values */
  22946. state.lenbits = 9;
  22947. opts = {bits: state.lenbits};
  22948. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  22949. // We have separate tables & no pointers. 2 commented lines below not needed.
  22950. // state.next_index = opts.table_index;
  22951. state.lenbits = opts.bits;
  22952. // state.lencode = state.next;
  22953. if (ret) {
  22954. strm.msg = 'invalid literal/lengths set';
  22955. state.mode = BAD;
  22956. break;
  22957. }
  22958. state.distbits = 6;
  22959. //state.distcode.copy(state.codes);
  22960. // Switch to use dynamic table
  22961. state.distcode = state.distdyn;
  22962. opts = {bits: state.distbits};
  22963. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  22964. // We have separate tables & no pointers. 2 commented lines below not needed.
  22965. // state.next_index = opts.table_index;
  22966. state.distbits = opts.bits;
  22967. // state.distcode = state.next;
  22968. if (ret) {
  22969. strm.msg = 'invalid distances set';
  22970. state.mode = BAD;
  22971. break;
  22972. }
  22973. //Tracev((stderr, 'inflate: codes ok\n'));
  22974. state.mode = LEN_;
  22975. if (flush === Z_TREES) { break inf_leave; }
  22976. /* falls through */
  22977. case LEN_:
  22978. state.mode = LEN;
  22979. /* falls through */
  22980. case LEN:
  22981. if (have >= 6 && left >= 258) {
  22982. //--- RESTORE() ---
  22983. strm.next_out = put;
  22984. strm.avail_out = left;
  22985. strm.next_in = next;
  22986. strm.avail_in = have;
  22987. state.hold = hold;
  22988. state.bits = bits;
  22989. //---
  22990. inflate_fast(strm, _out);
  22991. //--- LOAD() ---
  22992. put = strm.next_out;
  22993. output = strm.output;
  22994. left = strm.avail_out;
  22995. next = strm.next_in;
  22996. input = strm.input;
  22997. have = strm.avail_in;
  22998. hold = state.hold;
  22999. bits = state.bits;
  23000. //---
  23001. if (state.mode === TYPE) {
  23002. state.back = -1;
  23003. }
  23004. break;
  23005. }
  23006. state.back = 0;
  23007. for (;;) {
  23008. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23009. here_bits = here >>> 24;
  23010. here_op = (here >>> 16) & 0xff;
  23011. here_val = here & 0xffff;
  23012. if (here_bits <= bits) { break; }
  23013. //--- PULLBYTE() ---//
  23014. if (have === 0) { break inf_leave; }
  23015. have--;
  23016. hold += input[next++] << bits;
  23017. bits += 8;
  23018. //---//
  23019. }
  23020. if (here_op && (here_op & 0xf0) === 0) {
  23021. last_bits = here_bits;
  23022. last_op = here_op;
  23023. last_val = here_val;
  23024. for (;;) {
  23025. here = state.lencode[last_val +
  23026. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23027. here_bits = here >>> 24;
  23028. here_op = (here >>> 16) & 0xff;
  23029. here_val = here & 0xffff;
  23030. if ((last_bits + here_bits) <= bits) { break; }
  23031. //--- PULLBYTE() ---//
  23032. if (have === 0) { break inf_leave; }
  23033. have--;
  23034. hold += input[next++] << bits;
  23035. bits += 8;
  23036. //---//
  23037. }
  23038. //--- DROPBITS(last.bits) ---//
  23039. hold >>>= last_bits;
  23040. bits -= last_bits;
  23041. //---//
  23042. state.back += last_bits;
  23043. }
  23044. //--- DROPBITS(here.bits) ---//
  23045. hold >>>= here_bits;
  23046. bits -= here_bits;
  23047. //---//
  23048. state.back += here_bits;
  23049. state.length = here_val;
  23050. if (here_op === 0) {
  23051. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23052. // "inflate: literal '%c'\n" :
  23053. // "inflate: literal 0x%02x\n", here.val));
  23054. state.mode = LIT;
  23055. break;
  23056. }
  23057. if (here_op & 32) {
  23058. //Tracevv((stderr, "inflate: end of block\n"));
  23059. state.back = -1;
  23060. state.mode = TYPE;
  23061. break;
  23062. }
  23063. if (here_op & 64) {
  23064. strm.msg = 'invalid literal/length code';
  23065. state.mode = BAD;
  23066. break;
  23067. }
  23068. state.extra = here_op & 15;
  23069. state.mode = LENEXT;
  23070. /* falls through */
  23071. case LENEXT:
  23072. if (state.extra) {
  23073. //=== NEEDBITS(state.extra);
  23074. n = state.extra;
  23075. while (bits < n) {
  23076. if (have === 0) { break inf_leave; }
  23077. have--;
  23078. hold += input[next++] << bits;
  23079. bits += 8;
  23080. }
  23081. //===//
  23082. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23083. //--- DROPBITS(state.extra) ---//
  23084. hold >>>= state.extra;
  23085. bits -= state.extra;
  23086. //---//
  23087. state.back += state.extra;
  23088. }
  23089. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23090. state.was = state.length;
  23091. state.mode = DIST;
  23092. /* falls through */
  23093. case DIST:
  23094. for (;;) {
  23095. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23096. here_bits = here >>> 24;
  23097. here_op = (here >>> 16) & 0xff;
  23098. here_val = here & 0xffff;
  23099. if ((here_bits) <= bits) { break; }
  23100. //--- PULLBYTE() ---//
  23101. if (have === 0) { break inf_leave; }
  23102. have--;
  23103. hold += input[next++] << bits;
  23104. bits += 8;
  23105. //---//
  23106. }
  23107. if ((here_op & 0xf0) === 0) {
  23108. last_bits = here_bits;
  23109. last_op = here_op;
  23110. last_val = here_val;
  23111. for (;;) {
  23112. here = state.distcode[last_val +
  23113. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23114. here_bits = here >>> 24;
  23115. here_op = (here >>> 16) & 0xff;
  23116. here_val = here & 0xffff;
  23117. if ((last_bits + here_bits) <= bits) { break; }
  23118. //--- PULLBYTE() ---//
  23119. if (have === 0) { break inf_leave; }
  23120. have--;
  23121. hold += input[next++] << bits;
  23122. bits += 8;
  23123. //---//
  23124. }
  23125. //--- DROPBITS(last.bits) ---//
  23126. hold >>>= last_bits;
  23127. bits -= last_bits;
  23128. //---//
  23129. state.back += last_bits;
  23130. }
  23131. //--- DROPBITS(here.bits) ---//
  23132. hold >>>= here_bits;
  23133. bits -= here_bits;
  23134. //---//
  23135. state.back += here_bits;
  23136. if (here_op & 64) {
  23137. strm.msg = 'invalid distance code';
  23138. state.mode = BAD;
  23139. break;
  23140. }
  23141. state.offset = here_val;
  23142. state.extra = (here_op) & 15;
  23143. state.mode = DISTEXT;
  23144. /* falls through */
  23145. case DISTEXT:
  23146. if (state.extra) {
  23147. //=== NEEDBITS(state.extra);
  23148. n = state.extra;
  23149. while (bits < n) {
  23150. if (have === 0) { break inf_leave; }
  23151. have--;
  23152. hold += input[next++] << bits;
  23153. bits += 8;
  23154. }
  23155. //===//
  23156. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23157. //--- DROPBITS(state.extra) ---//
  23158. hold >>>= state.extra;
  23159. bits -= state.extra;
  23160. //---//
  23161. state.back += state.extra;
  23162. }
  23163. //#ifdef INFLATE_STRICT
  23164. if (state.offset > state.dmax) {
  23165. strm.msg = 'invalid distance too far back';
  23166. state.mode = BAD;
  23167. break;
  23168. }
  23169. //#endif
  23170. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23171. state.mode = MATCH;
  23172. /* falls through */
  23173. case MATCH:
  23174. if (left === 0) { break inf_leave; }
  23175. copy = _out - left;
  23176. if (state.offset > copy) { /* copy from window */
  23177. copy = state.offset - copy;
  23178. if (copy > state.whave) {
  23179. if (state.sane) {
  23180. strm.msg = 'invalid distance too far back';
  23181. state.mode = BAD;
  23182. break;
  23183. }
  23184. // (!) This block is disabled in zlib defailts,
  23185. // don't enable it for binary compatibility
  23186. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23187. // Trace((stderr, "inflate.c too far\n"));
  23188. // copy -= state.whave;
  23189. // if (copy > state.length) { copy = state.length; }
  23190. // if (copy > left) { copy = left; }
  23191. // left -= copy;
  23192. // state.length -= copy;
  23193. // do {
  23194. // output[put++] = 0;
  23195. // } while (--copy);
  23196. // if (state.length === 0) { state.mode = LEN; }
  23197. // break;
  23198. //#endif
  23199. }
  23200. if (copy > state.wnext) {
  23201. copy -= state.wnext;
  23202. from = state.wsize - copy;
  23203. }
  23204. else {
  23205. from = state.wnext - copy;
  23206. }
  23207. if (copy > state.length) { copy = state.length; }
  23208. from_source = state.window;
  23209. }
  23210. else { /* copy from output */
  23211. from_source = output;
  23212. from = put - state.offset;
  23213. copy = state.length;
  23214. }
  23215. if (copy > left) { copy = left; }
  23216. left -= copy;
  23217. state.length -= copy;
  23218. do {
  23219. output[put++] = from_source[from++];
  23220. } while (--copy);
  23221. if (state.length === 0) { state.mode = LEN; }
  23222. break;
  23223. case LIT:
  23224. if (left === 0) { break inf_leave; }
  23225. output[put++] = state.length;
  23226. left--;
  23227. state.mode = LEN;
  23228. break;
  23229. case CHECK:
  23230. if (state.wrap) {
  23231. //=== NEEDBITS(32);
  23232. while (bits < 32) {
  23233. if (have === 0) { break inf_leave; }
  23234. have--;
  23235. // Use '|' insdead of '+' to make sure that result is signed
  23236. hold |= input[next++] << bits;
  23237. bits += 8;
  23238. }
  23239. //===//
  23240. _out -= left;
  23241. strm.total_out += _out;
  23242. state.total += _out;
  23243. if (_out) {
  23244. strm.adler = state.check =
  23245. /*UPDATE(state.check, put - _out, _out);*/
  23246. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23247. }
  23248. _out = left;
  23249. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23250. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23251. strm.msg = 'incorrect data check';
  23252. state.mode = BAD;
  23253. break;
  23254. }
  23255. //=== INITBITS();
  23256. hold = 0;
  23257. bits = 0;
  23258. //===//
  23259. //Tracev((stderr, "inflate: check matches trailer\n"));
  23260. }
  23261. state.mode = LENGTH;
  23262. /* falls through */
  23263. case LENGTH:
  23264. if (state.wrap && state.flags) {
  23265. //=== NEEDBITS(32);
  23266. while (bits < 32) {
  23267. if (have === 0) { break inf_leave; }
  23268. have--;
  23269. hold += input[next++] << bits;
  23270. bits += 8;
  23271. }
  23272. //===//
  23273. if (hold !== (state.total & 0xffffffff)) {
  23274. strm.msg = 'incorrect length check';
  23275. state.mode = BAD;
  23276. break;
  23277. }
  23278. //=== INITBITS();
  23279. hold = 0;
  23280. bits = 0;
  23281. //===//
  23282. //Tracev((stderr, "inflate: length matches trailer\n"));
  23283. }
  23284. state.mode = DONE;
  23285. /* falls through */
  23286. case DONE:
  23287. ret = Z_STREAM_END;
  23288. break inf_leave;
  23289. case BAD:
  23290. ret = Z_DATA_ERROR;
  23291. break inf_leave;
  23292. case MEM:
  23293. return Z_MEM_ERROR;
  23294. case SYNC:
  23295. /* falls through */
  23296. default:
  23297. return Z_STREAM_ERROR;
  23298. }
  23299. }
  23300. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23301. /*
  23302. Return from inflate(), updating the total counts and the check value.
  23303. If there was no progress during the inflate() call, return a buffer
  23304. error. Call updatewindow() to create and/or update the window state.
  23305. Note: a memory error from inflate() is non-recoverable.
  23306. */
  23307. //--- RESTORE() ---
  23308. strm.next_out = put;
  23309. strm.avail_out = left;
  23310. strm.next_in = next;
  23311. strm.avail_in = have;
  23312. state.hold = hold;
  23313. state.bits = bits;
  23314. //---
  23315. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23316. (state.mode < CHECK || flush !== Z_FINISH))) {
  23317. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23318. state.mode = MEM;
  23319. return Z_MEM_ERROR;
  23320. }
  23321. }
  23322. _in -= strm.avail_in;
  23323. _out -= strm.avail_out;
  23324. strm.total_in += _in;
  23325. strm.total_out += _out;
  23326. state.total += _out;
  23327. if (state.wrap && _out) {
  23328. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23329. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23330. }
  23331. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23332. (state.mode === TYPE ? 128 : 0) +
  23333. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23334. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23335. ret = Z_BUF_ERROR;
  23336. }
  23337. return ret;
  23338. }
  23339. function inflateEnd(strm) {
  23340. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23341. return Z_STREAM_ERROR;
  23342. }
  23343. var state = strm.state;
  23344. if (state.window) {
  23345. state.window = null;
  23346. }
  23347. strm.state = null;
  23348. return Z_OK;
  23349. }
  23350. function inflateGetHeader(strm, head) {
  23351. var state;
  23352. /* check state */
  23353. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23354. state = strm.state;
  23355. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23356. /* save header structure */
  23357. state.head = head;
  23358. head.done = false;
  23359. return Z_OK;
  23360. }
  23361. exports.inflateReset = inflateReset;
  23362. exports.inflateReset2 = inflateReset2;
  23363. exports.inflateResetKeep = inflateResetKeep;
  23364. exports.inflateInit = inflateInit;
  23365. exports.inflateInit2 = inflateInit2;
  23366. exports.inflate = inflate;
  23367. exports.inflateEnd = inflateEnd;
  23368. exports.inflateGetHeader = inflateGetHeader;
  23369. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23370. /* Not implemented
  23371. exports.inflateCopy = inflateCopy;
  23372. exports.inflateGetDictionary = inflateGetDictionary;
  23373. exports.inflateMark = inflateMark;
  23374. exports.inflatePrime = inflatePrime;
  23375. exports.inflateSetDictionary = inflateSetDictionary;
  23376. exports.inflateSync = inflateSync;
  23377. exports.inflateSyncPoint = inflateSyncPoint;
  23378. exports.inflateUndermine = inflateUndermine;
  23379. */
  23380. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./inffast":79,"./inftrees":81}],81:[function(require,module,exports){
  23381. 'use strict';
  23382. var utils = require('../utils/common');
  23383. var MAXBITS = 15;
  23384. var ENOUGH_LENS = 852;
  23385. var ENOUGH_DISTS = 592;
  23386. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23387. var CODES = 0;
  23388. var LENS = 1;
  23389. var DISTS = 2;
  23390. var lbase = [ /* Length codes 257..285 base */
  23391. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23392. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23393. ];
  23394. var lext = [ /* Length codes 257..285 extra */
  23395. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23396. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23397. ];
  23398. var dbase = [ /* Distance codes 0..29 base */
  23399. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23400. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23401. 8193, 12289, 16385, 24577, 0, 0
  23402. ];
  23403. var dext = [ /* Distance codes 0..29 extra */
  23404. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23405. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23406. 28, 28, 29, 29, 64, 64
  23407. ];
  23408. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23409. {
  23410. var bits = opts.bits;
  23411. //here = opts.here; /* table entry for duplication */
  23412. var len = 0; /* a code's length in bits */
  23413. var sym = 0; /* index of code symbols */
  23414. var min = 0, max = 0; /* minimum and maximum code lengths */
  23415. var root = 0; /* number of index bits for root table */
  23416. var curr = 0; /* number of index bits for current table */
  23417. var drop = 0; /* code bits to drop for sub-table */
  23418. var left = 0; /* number of prefix codes available */
  23419. var used = 0; /* code entries in table used */
  23420. var huff = 0; /* Huffman code */
  23421. var incr; /* for incrementing code, index */
  23422. var fill; /* index for replicating entries */
  23423. var low; /* low bits for current root entry */
  23424. var mask; /* mask for low root bits */
  23425. var next; /* next available space in table */
  23426. var base = null; /* base value table to use */
  23427. var base_index = 0;
  23428. // var shoextra; /* extra bits table to use */
  23429. var end; /* use base and extra for symbol > end */
  23430. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23431. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23432. var extra = null;
  23433. var extra_index = 0;
  23434. var here_bits, here_op, here_val;
  23435. /*
  23436. Process a set of code lengths to create a canonical Huffman code. The
  23437. code lengths are lens[0..codes-1]. Each length corresponds to the
  23438. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23439. symbols by length from short to long, and retaining the symbol order
  23440. for codes with equal lengths. Then the code starts with all zero bits
  23441. for the first code of the shortest length, and the codes are integer
  23442. increments for the same length, and zeros are appended as the length
  23443. increases. For the deflate format, these bits are stored backwards
  23444. from their more natural integer increment ordering, and so when the
  23445. decoding tables are built in the large loop below, the integer codes
  23446. are incremented backwards.
  23447. This routine assumes, but does not check, that all of the entries in
  23448. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23449. 1..MAXBITS is interpreted as that code length. zero means that that
  23450. symbol does not occur in this code.
  23451. The codes are sorted by computing a count of codes for each length,
  23452. creating from that a table of starting indices for each length in the
  23453. sorted table, and then entering the symbols in order in the sorted
  23454. table. The sorted table is work[], with that space being provided by
  23455. the caller.
  23456. The length counts are used for other purposes as well, i.e. finding
  23457. the minimum and maximum length codes, determining if there are any
  23458. codes at all, checking for a valid set of lengths, and looking ahead
  23459. at length counts to determine sub-table sizes when building the
  23460. decoding tables.
  23461. */
  23462. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23463. for (len = 0; len <= MAXBITS; len++) {
  23464. count[len] = 0;
  23465. }
  23466. for (sym = 0; sym < codes; sym++) {
  23467. count[lens[lens_index + sym]]++;
  23468. }
  23469. /* bound code lengths, force root to be within code lengths */
  23470. root = bits;
  23471. for (max = MAXBITS; max >= 1; max--) {
  23472. if (count[max] !== 0) { break; }
  23473. }
  23474. if (root > max) {
  23475. root = max;
  23476. }
  23477. if (max === 0) { /* no symbols to code at all */
  23478. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23479. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23480. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23481. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23482. //table.op[opts.table_index] = 64;
  23483. //table.bits[opts.table_index] = 1;
  23484. //table.val[opts.table_index++] = 0;
  23485. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23486. opts.bits = 1;
  23487. return 0; /* no symbols, but wait for decoding to report error */
  23488. }
  23489. for (min = 1; min < max; min++) {
  23490. if (count[min] !== 0) { break; }
  23491. }
  23492. if (root < min) {
  23493. root = min;
  23494. }
  23495. /* check for an over-subscribed or incomplete set of lengths */
  23496. left = 1;
  23497. for (len = 1; len <= MAXBITS; len++) {
  23498. left <<= 1;
  23499. left -= count[len];
  23500. if (left < 0) {
  23501. return -1;
  23502. } /* over-subscribed */
  23503. }
  23504. if (left > 0 && (type === CODES || max !== 1)) {
  23505. return -1; /* incomplete set */
  23506. }
  23507. /* generate offsets into symbol table for each length for sorting */
  23508. offs[1] = 0;
  23509. for (len = 1; len < MAXBITS; len++) {
  23510. offs[len + 1] = offs[len] + count[len];
  23511. }
  23512. /* sort symbols by length, by symbol order within each length */
  23513. for (sym = 0; sym < codes; sym++) {
  23514. if (lens[lens_index + sym] !== 0) {
  23515. work[offs[lens[lens_index + sym]]++] = sym;
  23516. }
  23517. }
  23518. /*
  23519. Create and fill in decoding tables. In this loop, the table being
  23520. filled is at next and has curr index bits. The code being used is huff
  23521. with length len. That code is converted to an index by dropping drop
  23522. bits off of the bottom. For codes where len is less than drop + curr,
  23523. those top drop + curr - len bits are incremented through all values to
  23524. fill the table with replicated entries.
  23525. root is the number of index bits for the root table. When len exceeds
  23526. root, sub-tables are created pointed to by the root entry with an index
  23527. of the low root bits of huff. This is saved in low to check for when a
  23528. new sub-table should be started. drop is zero when the root table is
  23529. being filled, and drop is root when sub-tables are being filled.
  23530. When a new sub-table is needed, it is necessary to look ahead in the
  23531. code lengths to determine what size sub-table is needed. The length
  23532. counts are used for this, and so count[] is decremented as codes are
  23533. entered in the tables.
  23534. used keeps track of how many table entries have been allocated from the
  23535. provided *table space. It is checked for LENS and DIST tables against
  23536. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23537. the initial root table size constants. See the comments in inftrees.h
  23538. for more information.
  23539. sym increments through all symbols, and the loop terminates when
  23540. all codes of length max, i.e. all codes, have been processed. This
  23541. routine permits incomplete codes, so another loop after this one fills
  23542. in the rest of the decoding tables with invalid code markers.
  23543. */
  23544. /* set up for code type */
  23545. // poor man optimization - use if-else instead of switch,
  23546. // to avoid deopts in old v8
  23547. if (type === CODES) {
  23548. base = extra = work; /* dummy value--not used */
  23549. end = 19;
  23550. } else if (type === LENS) {
  23551. base = lbase;
  23552. base_index -= 257;
  23553. extra = lext;
  23554. extra_index -= 257;
  23555. end = 256;
  23556. } else { /* DISTS */
  23557. base = dbase;
  23558. extra = dext;
  23559. end = -1;
  23560. }
  23561. /* initialize opts for loop */
  23562. huff = 0; /* starting code */
  23563. sym = 0; /* starting code symbol */
  23564. len = min; /* starting code length */
  23565. next = table_index; /* current table to fill in */
  23566. curr = root; /* current table index bits */
  23567. drop = 0; /* current bits to drop from code for index */
  23568. low = -1; /* trigger new sub-table when len > root */
  23569. used = 1 << root; /* use root table entries */
  23570. mask = used - 1; /* mask for comparing low */
  23571. /* check available table space */
  23572. if ((type === LENS && used > ENOUGH_LENS) ||
  23573. (type === DISTS && used > ENOUGH_DISTS)) {
  23574. return 1;
  23575. }
  23576. var i=0;
  23577. /* process all codes and make table entries */
  23578. for (;;) {
  23579. i++;
  23580. /* create table entry */
  23581. here_bits = len - drop;
  23582. if (work[sym] < end) {
  23583. here_op = 0;
  23584. here_val = work[sym];
  23585. }
  23586. else if (work[sym] > end) {
  23587. here_op = extra[extra_index + work[sym]];
  23588. here_val = base[base_index + work[sym]];
  23589. }
  23590. else {
  23591. here_op = 32 + 64; /* end of block */
  23592. here_val = 0;
  23593. }
  23594. /* replicate for those indices with low len bits equal to huff */
  23595. incr = 1 << (len - drop);
  23596. fill = 1 << curr;
  23597. min = fill; /* save offset to next table */
  23598. do {
  23599. fill -= incr;
  23600. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23601. } while (fill !== 0);
  23602. /* backwards increment the len-bit code huff */
  23603. incr = 1 << (len - 1);
  23604. while (huff & incr) {
  23605. incr >>= 1;
  23606. }
  23607. if (incr !== 0) {
  23608. huff &= incr - 1;
  23609. huff += incr;
  23610. } else {
  23611. huff = 0;
  23612. }
  23613. /* go to next symbol, update count, len */
  23614. sym++;
  23615. if (--count[len] === 0) {
  23616. if (len === max) { break; }
  23617. len = lens[lens_index + work[sym]];
  23618. }
  23619. /* create new sub-table if needed */
  23620. if (len > root && (huff & mask) !== low) {
  23621. /* if first time, transition to sub-tables */
  23622. if (drop === 0) {
  23623. drop = root;
  23624. }
  23625. /* increment past last table */
  23626. next += min; /* here min is 1 << curr */
  23627. /* determine length of next table */
  23628. curr = len - drop;
  23629. left = 1 << curr;
  23630. while (curr + drop < max) {
  23631. left -= count[curr + drop];
  23632. if (left <= 0) { break; }
  23633. curr++;
  23634. left <<= 1;
  23635. }
  23636. /* check for enough space */
  23637. used += 1 << curr;
  23638. if ((type === LENS && used > ENOUGH_LENS) ||
  23639. (type === DISTS && used > ENOUGH_DISTS)) {
  23640. return 1;
  23641. }
  23642. /* point entry in root table to sub-table */
  23643. low = huff & mask;
  23644. /*table.op[low] = curr;
  23645. table.bits[low] = root;
  23646. table.val[low] = next - opts.table_index;*/
  23647. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23648. }
  23649. }
  23650. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23651. at most one remaining entry, since if the code is incomplete, the
  23652. maximum code length that was allowed to get this far is one bit) */
  23653. if (huff !== 0) {
  23654. //table.op[next + huff] = 64; /* invalid code marker */
  23655. //table.bits[next + huff] = len - drop;
  23656. //table.val[next + huff] = 0;
  23657. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23658. }
  23659. /* set return parameters */
  23660. //opts.table_index += used;
  23661. opts.bits = root;
  23662. return 0;
  23663. };
  23664. },{"../utils/common":72}],82:[function(require,module,exports){
  23665. 'use strict';
  23666. module.exports = {
  23667. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23668. '1': 'stream end', /* Z_STREAM_END 1 */
  23669. '0': '', /* Z_OK 0 */
  23670. '-1': 'file error', /* Z_ERRNO (-1) */
  23671. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23672. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23673. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23674. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23675. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23676. };
  23677. },{}],83:[function(require,module,exports){
  23678. 'use strict';
  23679. var utils = require('../utils/common');
  23680. /* Public constants ==========================================================*/
  23681. /* ===========================================================================*/
  23682. //var Z_FILTERED = 1;
  23683. //var Z_HUFFMAN_ONLY = 2;
  23684. //var Z_RLE = 3;
  23685. var Z_FIXED = 4;
  23686. //var Z_DEFAULT_STRATEGY = 0;
  23687. /* Possible values of the data_type field (though see inflate()) */
  23688. var Z_BINARY = 0;
  23689. var Z_TEXT = 1;
  23690. //var Z_ASCII = 1; // = Z_TEXT
  23691. var Z_UNKNOWN = 2;
  23692. /*============================================================================*/
  23693. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23694. // From zutil.h
  23695. var STORED_BLOCK = 0;
  23696. var STATIC_TREES = 1;
  23697. var DYN_TREES = 2;
  23698. /* The three kinds of block type */
  23699. var MIN_MATCH = 3;
  23700. var MAX_MATCH = 258;
  23701. /* The minimum and maximum match lengths */
  23702. // From deflate.h
  23703. /* ===========================================================================
  23704. * Internal compression state.
  23705. */
  23706. var LENGTH_CODES = 29;
  23707. /* number of length codes, not counting the special END_BLOCK code */
  23708. var LITERALS = 256;
  23709. /* number of literal bytes 0..255 */
  23710. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23711. /* number of Literal or Length codes, including the END_BLOCK code */
  23712. var D_CODES = 30;
  23713. /* number of distance codes */
  23714. var BL_CODES = 19;
  23715. /* number of codes used to transfer the bit lengths */
  23716. var HEAP_SIZE = 2*L_CODES + 1;
  23717. /* maximum heap size */
  23718. var MAX_BITS = 15;
  23719. /* All codes must not exceed MAX_BITS bits */
  23720. var Buf_size = 16;
  23721. /* size of bit buffer in bi_buf */
  23722. /* ===========================================================================
  23723. * Constants
  23724. */
  23725. var MAX_BL_BITS = 7;
  23726. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23727. var END_BLOCK = 256;
  23728. /* end of block literal code */
  23729. var REP_3_6 = 16;
  23730. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23731. var REPZ_3_10 = 17;
  23732. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23733. var REPZ_11_138 = 18;
  23734. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23735. var extra_lbits = /* extra bits for each length code */
  23736. [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];
  23737. var extra_dbits = /* extra bits for each distance code */
  23738. [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];
  23739. var extra_blbits = /* extra bits for each bit length code */
  23740. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23741. var bl_order =
  23742. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23743. /* The lengths of the bit length codes are sent in order of decreasing
  23744. * probability, to avoid transmitting the lengths for unused bit length codes.
  23745. */
  23746. /* ===========================================================================
  23747. * Local data. These are initialized only once.
  23748. */
  23749. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23750. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23751. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23752. var static_ltree = new Array((L_CODES+2) * 2);
  23753. zero(static_ltree);
  23754. /* The static literal tree. Since the bit lengths are imposed, there is no
  23755. * need for the L_CODES extra codes used during heap construction. However
  23756. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23757. * below).
  23758. */
  23759. var static_dtree = new Array(D_CODES * 2);
  23760. zero(static_dtree);
  23761. /* The static distance tree. (Actually a trivial tree since all codes use
  23762. * 5 bits.)
  23763. */
  23764. var _dist_code = new Array(DIST_CODE_LEN);
  23765. zero(_dist_code);
  23766. /* Distance codes. The first 256 values correspond to the distances
  23767. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23768. * the 15 bit distances.
  23769. */
  23770. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23771. zero(_length_code);
  23772. /* length code for each normalized match length (0 == MIN_MATCH) */
  23773. var base_length = new Array(LENGTH_CODES);
  23774. zero(base_length);
  23775. /* First normalized length for each code (0 = MIN_MATCH) */
  23776. var base_dist = new Array(D_CODES);
  23777. zero(base_dist);
  23778. /* First normalized distance for each code (0 = distance of 1) */
  23779. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23780. this.static_tree = static_tree; /* static tree or NULL */
  23781. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23782. this.extra_base = extra_base; /* base index for extra_bits */
  23783. this.elems = elems; /* max number of elements in the tree */
  23784. this.max_length = max_length; /* max bit length for the codes */
  23785. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23786. this.has_stree = static_tree && static_tree.length;
  23787. };
  23788. var static_l_desc;
  23789. var static_d_desc;
  23790. var static_bl_desc;
  23791. var TreeDesc = function(dyn_tree, stat_desc) {
  23792. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23793. this.max_code = 0; /* largest code with non zero frequency */
  23794. this.stat_desc = stat_desc; /* the corresponding static tree */
  23795. };
  23796. function d_code(dist) {
  23797. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23798. }
  23799. /* ===========================================================================
  23800. * Output a short LSB first on the stream.
  23801. * IN assertion: there is enough room in pendingBuf.
  23802. */
  23803. function put_short (s, w) {
  23804. // put_byte(s, (uch)((w) & 0xff));
  23805. // put_byte(s, (uch)((ush)(w) >> 8));
  23806. s.pending_buf[s.pending++] = (w) & 0xff;
  23807. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23808. }
  23809. /* ===========================================================================
  23810. * Send a value on a given number of bits.
  23811. * IN assertion: length <= 16 and value fits in length bits.
  23812. */
  23813. function send_bits(s, value, length) {
  23814. if (s.bi_valid > (Buf_size - length)) {
  23815. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23816. put_short(s, s.bi_buf);
  23817. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23818. s.bi_valid += length - Buf_size;
  23819. } else {
  23820. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23821. s.bi_valid += length;
  23822. }
  23823. }
  23824. function send_code(s, c, tree) {
  23825. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23826. }
  23827. /* ===========================================================================
  23828. * Reverse the first len bits of a code, using straightforward code (a faster
  23829. * method would use a table)
  23830. * IN assertion: 1 <= len <= 15
  23831. */
  23832. function bi_reverse(code, len) {
  23833. var res = 0;
  23834. do {
  23835. res |= code & 1;
  23836. code >>>= 1;
  23837. res <<= 1;
  23838. } while (--len > 0);
  23839. return res >>> 1;
  23840. }
  23841. /* ===========================================================================
  23842. * Flush the bit buffer, keeping at most 7 bits in it.
  23843. */
  23844. function bi_flush(s) {
  23845. if (s.bi_valid === 16) {
  23846. put_short(s, s.bi_buf);
  23847. s.bi_buf = 0;
  23848. s.bi_valid = 0;
  23849. } else if (s.bi_valid >= 8) {
  23850. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23851. s.bi_buf >>= 8;
  23852. s.bi_valid -= 8;
  23853. }
  23854. }
  23855. /* ===========================================================================
  23856. * Compute the optimal bit lengths for a tree and update the total bit length
  23857. * for the current block.
  23858. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23859. * above are the tree nodes sorted by increasing frequency.
  23860. * OUT assertions: the field len is set to the optimal bit length, the
  23861. * array bl_count contains the frequencies for each bit length.
  23862. * The length opt_len is updated; static_len is also updated if stree is
  23863. * not null.
  23864. */
  23865. function gen_bitlen(s, desc)
  23866. // deflate_state *s;
  23867. // tree_desc *desc; /* the tree descriptor */
  23868. {
  23869. var tree = desc.dyn_tree;
  23870. var max_code = desc.max_code;
  23871. var stree = desc.stat_desc.static_tree;
  23872. var has_stree = desc.stat_desc.has_stree;
  23873. var extra = desc.stat_desc.extra_bits;
  23874. var base = desc.stat_desc.extra_base;
  23875. var max_length = desc.stat_desc.max_length;
  23876. var h; /* heap index */
  23877. var n, m; /* iterate over the tree elements */
  23878. var bits; /* bit length */
  23879. var xbits; /* extra bits */
  23880. var f; /* frequency */
  23881. var overflow = 0; /* number of elements with bit length too large */
  23882. for (bits = 0; bits <= MAX_BITS; bits++) {
  23883. s.bl_count[bits] = 0;
  23884. }
  23885. /* In a first pass, compute the optimal bit lengths (which may
  23886. * overflow in the case of the bit length tree).
  23887. */
  23888. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  23889. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  23890. n = s.heap[h];
  23891. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  23892. if (bits > max_length) {
  23893. bits = max_length;
  23894. overflow++;
  23895. }
  23896. tree[n*2 + 1]/*.Len*/ = bits;
  23897. /* We overwrite tree[n].Dad which is no longer needed */
  23898. if (n > max_code) { continue; } /* not a leaf node */
  23899. s.bl_count[bits]++;
  23900. xbits = 0;
  23901. if (n >= base) {
  23902. xbits = extra[n-base];
  23903. }
  23904. f = tree[n * 2]/*.Freq*/;
  23905. s.opt_len += f * (bits + xbits);
  23906. if (has_stree) {
  23907. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  23908. }
  23909. }
  23910. if (overflow === 0) { return; }
  23911. // Trace((stderr,"\nbit length overflow\n"));
  23912. /* This happens for example on obj2 and pic of the Calgary corpus */
  23913. /* Find the first bit length which could increase: */
  23914. do {
  23915. bits = max_length-1;
  23916. while (s.bl_count[bits] === 0) { bits--; }
  23917. s.bl_count[bits]--; /* move one leaf down the tree */
  23918. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  23919. s.bl_count[max_length]--;
  23920. /* The brother of the overflow item also moves one step up,
  23921. * but this does not affect bl_count[max_length]
  23922. */
  23923. overflow -= 2;
  23924. } while (overflow > 0);
  23925. /* Now recompute all bit lengths, scanning in increasing frequency.
  23926. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  23927. * lengths instead of fixing only the wrong ones. This idea is taken
  23928. * from 'ar' written by Haruhiko Okumura.)
  23929. */
  23930. for (bits = max_length; bits !== 0; bits--) {
  23931. n = s.bl_count[bits];
  23932. while (n !== 0) {
  23933. m = s.heap[--h];
  23934. if (m > max_code) { continue; }
  23935. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  23936. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  23937. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  23938. tree[m*2 + 1]/*.Len*/ = bits;
  23939. }
  23940. n--;
  23941. }
  23942. }
  23943. }
  23944. /* ===========================================================================
  23945. * Generate the codes for a given tree and bit counts (which need not be
  23946. * optimal).
  23947. * IN assertion: the array bl_count contains the bit length statistics for
  23948. * the given tree and the field len is set for all tree elements.
  23949. * OUT assertion: the field code is set for all tree elements of non
  23950. * zero code length.
  23951. */
  23952. function gen_codes(tree, max_code, bl_count)
  23953. // ct_data *tree; /* the tree to decorate */
  23954. // int max_code; /* largest code with non zero frequency */
  23955. // ushf *bl_count; /* number of codes at each bit length */
  23956. {
  23957. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  23958. var code = 0; /* running code value */
  23959. var bits; /* bit index */
  23960. var n; /* code index */
  23961. /* The distribution counts are first used to generate the code values
  23962. * without bit reversal.
  23963. */
  23964. for (bits = 1; bits <= MAX_BITS; bits++) {
  23965. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  23966. }
  23967. /* Check that the bit counts in bl_count are consistent. The last code
  23968. * must be all ones.
  23969. */
  23970. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  23971. // "inconsistent bit counts");
  23972. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  23973. for (n = 0; n <= max_code; n++) {
  23974. var len = tree[n*2 + 1]/*.Len*/;
  23975. if (len === 0) { continue; }
  23976. /* Now reverse the bits */
  23977. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  23978. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  23979. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  23980. }
  23981. }
  23982. /* ===========================================================================
  23983. * Initialize the various 'constant' tables.
  23984. */
  23985. function tr_static_init() {
  23986. var n; /* iterates over tree elements */
  23987. var bits; /* bit counter */
  23988. var length; /* length value */
  23989. var code; /* code value */
  23990. var dist; /* distance index */
  23991. var bl_count = new Array(MAX_BITS+1);
  23992. /* number of codes at each bit length for an optimal tree */
  23993. // do check in _tr_init()
  23994. //if (static_init_done) return;
  23995. /* For some embedded targets, global variables are not initialized: */
  23996. /*#ifdef NO_INIT_GLOBAL_POINTERS
  23997. static_l_desc.static_tree = static_ltree;
  23998. static_l_desc.extra_bits = extra_lbits;
  23999. static_d_desc.static_tree = static_dtree;
  24000. static_d_desc.extra_bits = extra_dbits;
  24001. static_bl_desc.extra_bits = extra_blbits;
  24002. #endif*/
  24003. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24004. length = 0;
  24005. for (code = 0; code < LENGTH_CODES-1; code++) {
  24006. base_length[code] = length;
  24007. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24008. _length_code[length++] = code;
  24009. }
  24010. }
  24011. //Assert (length == 256, "tr_static_init: length != 256");
  24012. /* Note that the length 255 (match length 258) can be represented
  24013. * in two different ways: code 284 + 5 bits or code 285, so we
  24014. * overwrite length_code[255] to use the best encoding:
  24015. */
  24016. _length_code[length-1] = code;
  24017. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24018. dist = 0;
  24019. for (code = 0 ; code < 16; code++) {
  24020. base_dist[code] = dist;
  24021. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24022. _dist_code[dist++] = code;
  24023. }
  24024. }
  24025. //Assert (dist == 256, "tr_static_init: dist != 256");
  24026. dist >>= 7; /* from now on, all distances are divided by 128 */
  24027. for (; code < D_CODES; code++) {
  24028. base_dist[code] = dist << 7;
  24029. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24030. _dist_code[256 + dist++] = code;
  24031. }
  24032. }
  24033. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24034. /* Construct the codes of the static literal tree */
  24035. for (bits = 0; bits <= MAX_BITS; bits++) {
  24036. bl_count[bits] = 0;
  24037. }
  24038. n = 0;
  24039. while (n <= 143) {
  24040. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24041. n++;
  24042. bl_count[8]++;
  24043. }
  24044. while (n <= 255) {
  24045. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24046. n++;
  24047. bl_count[9]++;
  24048. }
  24049. while (n <= 279) {
  24050. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24051. n++;
  24052. bl_count[7]++;
  24053. }
  24054. while (n <= 287) {
  24055. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24056. n++;
  24057. bl_count[8]++;
  24058. }
  24059. /* Codes 286 and 287 do not exist, but we must include them in the
  24060. * tree construction to get a canonical Huffman tree (longest code
  24061. * all ones)
  24062. */
  24063. gen_codes(static_ltree, L_CODES+1, bl_count);
  24064. /* The static distance tree is trivial: */
  24065. for (n = 0; n < D_CODES; n++) {
  24066. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24067. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24068. }
  24069. // Now data ready and we can init static trees
  24070. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24071. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24072. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24073. //static_init_done = true;
  24074. }
  24075. /* ===========================================================================
  24076. * Initialize a new block.
  24077. */
  24078. function init_block(s) {
  24079. var n; /* iterates over tree elements */
  24080. /* Initialize the trees. */
  24081. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24082. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24083. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24084. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24085. s.opt_len = s.static_len = 0;
  24086. s.last_lit = s.matches = 0;
  24087. }
  24088. /* ===========================================================================
  24089. * Flush the bit buffer and align the output on a byte boundary
  24090. */
  24091. function bi_windup(s)
  24092. {
  24093. if (s.bi_valid > 8) {
  24094. put_short(s, s.bi_buf);
  24095. } else if (s.bi_valid > 0) {
  24096. //put_byte(s, (Byte)s->bi_buf);
  24097. s.pending_buf[s.pending++] = s.bi_buf;
  24098. }
  24099. s.bi_buf = 0;
  24100. s.bi_valid = 0;
  24101. }
  24102. /* ===========================================================================
  24103. * Copy a stored block, storing first the length and its
  24104. * one's complement if requested.
  24105. */
  24106. function copy_block(s, buf, len, header)
  24107. //DeflateState *s;
  24108. //charf *buf; /* the input data */
  24109. //unsigned len; /* its length */
  24110. //int header; /* true if block header must be written */
  24111. {
  24112. bi_windup(s); /* align on byte boundary */
  24113. if (header) {
  24114. put_short(s, len);
  24115. put_short(s, ~len);
  24116. }
  24117. // while (len--) {
  24118. // put_byte(s, *buf++);
  24119. // }
  24120. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24121. s.pending += len;
  24122. }
  24123. /* ===========================================================================
  24124. * Compares to subtrees, using the tree depth as tie breaker when
  24125. * the subtrees have equal frequency. This minimizes the worst case length.
  24126. */
  24127. function smaller(tree, n, m, depth) {
  24128. var _n2 = n*2;
  24129. var _m2 = m*2;
  24130. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24131. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24132. }
  24133. /* ===========================================================================
  24134. * Restore the heap property by moving down the tree starting at node k,
  24135. * exchanging a node with the smallest of its two sons if necessary, stopping
  24136. * when the heap property is re-established (each father smaller than its
  24137. * two sons).
  24138. */
  24139. function pqdownheap(s, tree, k)
  24140. // deflate_state *s;
  24141. // ct_data *tree; /* the tree to restore */
  24142. // int k; /* node to move down */
  24143. {
  24144. var v = s.heap[k];
  24145. var j = k << 1; /* left son of k */
  24146. while (j <= s.heap_len) {
  24147. /* Set j to the smallest of the two sons: */
  24148. if (j < s.heap_len &&
  24149. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24150. j++;
  24151. }
  24152. /* Exit if v is smaller than both sons */
  24153. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24154. /* Exchange v with the smallest son */
  24155. s.heap[k] = s.heap[j];
  24156. k = j;
  24157. /* And continue down the tree, setting j to the left son of k */
  24158. j <<= 1;
  24159. }
  24160. s.heap[k] = v;
  24161. }
  24162. // inlined manually
  24163. // var SMALLEST = 1;
  24164. /* ===========================================================================
  24165. * Send the block data compressed using the given Huffman trees
  24166. */
  24167. function compress_block(s, ltree, dtree)
  24168. // deflate_state *s;
  24169. // const ct_data *ltree; /* literal tree */
  24170. // const ct_data *dtree; /* distance tree */
  24171. {
  24172. var dist; /* distance of matched string */
  24173. var lc; /* match length or unmatched char (if dist == 0) */
  24174. var lx = 0; /* running index in l_buf */
  24175. var code; /* the code to send */
  24176. var extra; /* number of extra bits to send */
  24177. if (s.last_lit !== 0) {
  24178. do {
  24179. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24180. lc = s.pending_buf[s.l_buf + lx];
  24181. lx++;
  24182. if (dist === 0) {
  24183. send_code(s, lc, ltree); /* send a literal byte */
  24184. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24185. } else {
  24186. /* Here, lc is the match length - MIN_MATCH */
  24187. code = _length_code[lc];
  24188. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24189. extra = extra_lbits[code];
  24190. if (extra !== 0) {
  24191. lc -= base_length[code];
  24192. send_bits(s, lc, extra); /* send the extra length bits */
  24193. }
  24194. dist--; /* dist is now the match distance - 1 */
  24195. code = d_code(dist);
  24196. //Assert (code < D_CODES, "bad d_code");
  24197. send_code(s, code, dtree); /* send the distance code */
  24198. extra = extra_dbits[code];
  24199. if (extra !== 0) {
  24200. dist -= base_dist[code];
  24201. send_bits(s, dist, extra); /* send the extra distance bits */
  24202. }
  24203. } /* literal or match pair ? */
  24204. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24205. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24206. // "pendingBuf overflow");
  24207. } while (lx < s.last_lit);
  24208. }
  24209. send_code(s, END_BLOCK, ltree);
  24210. }
  24211. /* ===========================================================================
  24212. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24213. * Update the total bit length for the current block.
  24214. * IN assertion: the field freq is set for all tree elements.
  24215. * OUT assertions: the fields len and code are set to the optimal bit length
  24216. * and corresponding code. The length opt_len is updated; static_len is
  24217. * also updated if stree is not null. The field max_code is set.
  24218. */
  24219. function build_tree(s, desc)
  24220. // deflate_state *s;
  24221. // tree_desc *desc; /* the tree descriptor */
  24222. {
  24223. var tree = desc.dyn_tree;
  24224. var stree = desc.stat_desc.static_tree;
  24225. var has_stree = desc.stat_desc.has_stree;
  24226. var elems = desc.stat_desc.elems;
  24227. var n, m; /* iterate over heap elements */
  24228. var max_code = -1; /* largest code with non zero frequency */
  24229. var node; /* new node being created */
  24230. /* Construct the initial heap, with least frequent element in
  24231. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24232. * heap[0] is not used.
  24233. */
  24234. s.heap_len = 0;
  24235. s.heap_max = HEAP_SIZE;
  24236. for (n = 0; n < elems; n++) {
  24237. if (tree[n * 2]/*.Freq*/ !== 0) {
  24238. s.heap[++s.heap_len] = max_code = n;
  24239. s.depth[n] = 0;
  24240. } else {
  24241. tree[n*2 + 1]/*.Len*/ = 0;
  24242. }
  24243. }
  24244. /* The pkzip format requires that at least one distance code exists,
  24245. * and that at least one bit should be sent even if there is only one
  24246. * possible code. So to avoid special checks later on we force at least
  24247. * two codes of non zero frequency.
  24248. */
  24249. while (s.heap_len < 2) {
  24250. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24251. tree[node * 2]/*.Freq*/ = 1;
  24252. s.depth[node] = 0;
  24253. s.opt_len--;
  24254. if (has_stree) {
  24255. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24256. }
  24257. /* node is 0 or 1 so it does not have extra bits */
  24258. }
  24259. desc.max_code = max_code;
  24260. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24261. * establish sub-heaps of increasing lengths:
  24262. */
  24263. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24264. /* Construct the Huffman tree by repeatedly combining the least two
  24265. * frequent nodes.
  24266. */
  24267. node = elems; /* next internal node of the tree */
  24268. do {
  24269. //pqremove(s, tree, n); /* n = node of least frequency */
  24270. /*** pqremove ***/
  24271. n = s.heap[1/*SMALLEST*/];
  24272. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24273. pqdownheap(s, tree, 1/*SMALLEST*/);
  24274. /***/
  24275. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24276. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24277. s.heap[--s.heap_max] = m;
  24278. /* Create a new node father of n and m */
  24279. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24280. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24281. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24282. /* and insert the new node in the heap */
  24283. s.heap[1/*SMALLEST*/] = node++;
  24284. pqdownheap(s, tree, 1/*SMALLEST*/);
  24285. } while (s.heap_len >= 2);
  24286. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24287. /* At this point, the fields freq and dad are set. We can now
  24288. * generate the bit lengths.
  24289. */
  24290. gen_bitlen(s, desc);
  24291. /* The field len is now set, we can generate the bit codes */
  24292. gen_codes(tree, max_code, s.bl_count);
  24293. }
  24294. /* ===========================================================================
  24295. * Scan a literal or distance tree to determine the frequencies of the codes
  24296. * in the bit length tree.
  24297. */
  24298. function scan_tree(s, tree, max_code)
  24299. // deflate_state *s;
  24300. // ct_data *tree; /* the tree to be scanned */
  24301. // int max_code; /* and its largest code of non zero frequency */
  24302. {
  24303. var n; /* iterates over all tree elements */
  24304. var prevlen = -1; /* last emitted length */
  24305. var curlen; /* length of current code */
  24306. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24307. var count = 0; /* repeat count of the current code */
  24308. var max_count = 7; /* max repeat count */
  24309. var min_count = 4; /* min repeat count */
  24310. if (nextlen === 0) {
  24311. max_count = 138;
  24312. min_count = 3;
  24313. }
  24314. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24315. for (n = 0; n <= max_code; n++) {
  24316. curlen = nextlen;
  24317. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24318. if (++count < max_count && curlen === nextlen) {
  24319. continue;
  24320. } else if (count < min_count) {
  24321. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24322. } else if (curlen !== 0) {
  24323. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24324. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24325. } else if (count <= 10) {
  24326. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24327. } else {
  24328. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24329. }
  24330. count = 0;
  24331. prevlen = curlen;
  24332. if (nextlen === 0) {
  24333. max_count = 138;
  24334. min_count = 3;
  24335. } else if (curlen === nextlen) {
  24336. max_count = 6;
  24337. min_count = 3;
  24338. } else {
  24339. max_count = 7;
  24340. min_count = 4;
  24341. }
  24342. }
  24343. }
  24344. /* ===========================================================================
  24345. * Send a literal or distance tree in compressed form, using the codes in
  24346. * bl_tree.
  24347. */
  24348. function send_tree(s, tree, max_code)
  24349. // deflate_state *s;
  24350. // ct_data *tree; /* the tree to be scanned */
  24351. // int max_code; /* and its largest code of non zero frequency */
  24352. {
  24353. var n; /* iterates over all tree elements */
  24354. var prevlen = -1; /* last emitted length */
  24355. var curlen; /* length of current code */
  24356. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24357. var count = 0; /* repeat count of the current code */
  24358. var max_count = 7; /* max repeat count */
  24359. var min_count = 4; /* min repeat count */
  24360. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24361. if (nextlen === 0) {
  24362. max_count = 138;
  24363. min_count = 3;
  24364. }
  24365. for (n = 0; n <= max_code; n++) {
  24366. curlen = nextlen;
  24367. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24368. if (++count < max_count && curlen === nextlen) {
  24369. continue;
  24370. } else if (count < min_count) {
  24371. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24372. } else if (curlen !== 0) {
  24373. if (curlen !== prevlen) {
  24374. send_code(s, curlen, s.bl_tree);
  24375. count--;
  24376. }
  24377. //Assert(count >= 3 && count <= 6, " 3_6?");
  24378. send_code(s, REP_3_6, s.bl_tree);
  24379. send_bits(s, count-3, 2);
  24380. } else if (count <= 10) {
  24381. send_code(s, REPZ_3_10, s.bl_tree);
  24382. send_bits(s, count-3, 3);
  24383. } else {
  24384. send_code(s, REPZ_11_138, s.bl_tree);
  24385. send_bits(s, count-11, 7);
  24386. }
  24387. count = 0;
  24388. prevlen = curlen;
  24389. if (nextlen === 0) {
  24390. max_count = 138;
  24391. min_count = 3;
  24392. } else if (curlen === nextlen) {
  24393. max_count = 6;
  24394. min_count = 3;
  24395. } else {
  24396. max_count = 7;
  24397. min_count = 4;
  24398. }
  24399. }
  24400. }
  24401. /* ===========================================================================
  24402. * Construct the Huffman tree for the bit lengths and return the index in
  24403. * bl_order of the last bit length code to send.
  24404. */
  24405. function build_bl_tree(s) {
  24406. var max_blindex; /* index of last bit length code of non zero freq */
  24407. /* Determine the bit length frequencies for literal and distance trees */
  24408. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24409. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24410. /* Build the bit length tree: */
  24411. build_tree(s, s.bl_desc);
  24412. /* opt_len now includes the length of the tree representations, except
  24413. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24414. */
  24415. /* Determine the number of bit length codes to send. The pkzip format
  24416. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24417. * 3 but the actual value used is 4.)
  24418. */
  24419. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24420. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24421. break;
  24422. }
  24423. }
  24424. /* Update opt_len to include the bit length tree and counts */
  24425. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24426. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24427. // s->opt_len, s->static_len));
  24428. return max_blindex;
  24429. }
  24430. /* ===========================================================================
  24431. * Send the header for a block using dynamic Huffman trees: the counts, the
  24432. * lengths of the bit length codes, the literal tree and the distance tree.
  24433. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24434. */
  24435. function send_all_trees(s, lcodes, dcodes, blcodes)
  24436. // deflate_state *s;
  24437. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24438. {
  24439. var rank; /* index in bl_order */
  24440. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24441. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24442. // "too many codes");
  24443. //Tracev((stderr, "\nbl counts: "));
  24444. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24445. send_bits(s, dcodes-1, 5);
  24446. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24447. for (rank = 0; rank < blcodes; rank++) {
  24448. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24449. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24450. }
  24451. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24452. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24453. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24454. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24455. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24456. }
  24457. /* ===========================================================================
  24458. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24459. * - TEXT if the two conditions below are satisfied:
  24460. * a) There are no non-portable control characters belonging to the
  24461. * "black list" (0..6, 14..25, 28..31).
  24462. * b) There is at least one printable character belonging to the
  24463. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24464. * - BINARY otherwise.
  24465. * - The following partially-portable control characters form a
  24466. * "gray list" that is ignored in this detection algorithm:
  24467. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24468. * IN assertion: the fields Freq of dyn_ltree are set.
  24469. */
  24470. function detect_data_type(s) {
  24471. /* black_mask is the bit mask of black-listed bytes
  24472. * set bits 0..6, 14..25, and 28..31
  24473. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24474. */
  24475. var black_mask = 0xf3ffc07f;
  24476. var n;
  24477. /* Check for non-textual ("black-listed") bytes. */
  24478. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24479. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24480. return Z_BINARY;
  24481. }
  24482. }
  24483. /* Check for textual ("white-listed") bytes. */
  24484. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24485. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24486. return Z_TEXT;
  24487. }
  24488. for (n = 32; n < LITERALS; n++) {
  24489. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24490. return Z_TEXT;
  24491. }
  24492. }
  24493. /* There are no "black-listed" or "white-listed" bytes:
  24494. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24495. */
  24496. return Z_BINARY;
  24497. }
  24498. var static_init_done = false;
  24499. /* ===========================================================================
  24500. * Initialize the tree data structures for a new zlib stream.
  24501. */
  24502. function _tr_init(s)
  24503. {
  24504. if (!static_init_done) {
  24505. tr_static_init();
  24506. static_init_done = true;
  24507. }
  24508. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24509. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24510. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24511. s.bi_buf = 0;
  24512. s.bi_valid = 0;
  24513. /* Initialize the first block of the first file: */
  24514. init_block(s);
  24515. }
  24516. /* ===========================================================================
  24517. * Send a stored block
  24518. */
  24519. function _tr_stored_block(s, buf, stored_len, last)
  24520. //DeflateState *s;
  24521. //charf *buf; /* input block */
  24522. //ulg stored_len; /* length of input block */
  24523. //int last; /* one if this is the last block for a file */
  24524. {
  24525. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24526. copy_block(s, buf, stored_len, true); /* with header */
  24527. }
  24528. /* ===========================================================================
  24529. * Send one empty static block to give enough lookahead for inflate.
  24530. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24531. */
  24532. function _tr_align(s) {
  24533. send_bits(s, STATIC_TREES<<1, 3);
  24534. send_code(s, END_BLOCK, static_ltree);
  24535. bi_flush(s);
  24536. }
  24537. /* ===========================================================================
  24538. * Determine the best encoding for the current block: dynamic trees, static
  24539. * trees or store, and output the encoded block to the zip file.
  24540. */
  24541. function _tr_flush_block(s, buf, stored_len, last)
  24542. //DeflateState *s;
  24543. //charf *buf; /* input block, or NULL if too old */
  24544. //ulg stored_len; /* length of input block */
  24545. //int last; /* one if this is the last block for a file */
  24546. {
  24547. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24548. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24549. /* Build the Huffman trees unless a stored block is forced */
  24550. if (s.level > 0) {
  24551. /* Check if the file is binary or text */
  24552. if (s.strm.data_type === Z_UNKNOWN) {
  24553. s.strm.data_type = detect_data_type(s);
  24554. }
  24555. /* Construct the literal and distance trees */
  24556. build_tree(s, s.l_desc);
  24557. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24558. // s->static_len));
  24559. build_tree(s, s.d_desc);
  24560. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24561. // s->static_len));
  24562. /* At this point, opt_len and static_len are the total bit lengths of
  24563. * the compressed block data, excluding the tree representations.
  24564. */
  24565. /* Build the bit length tree for the above two trees, and get the index
  24566. * in bl_order of the last bit length code to send.
  24567. */
  24568. max_blindex = build_bl_tree(s);
  24569. /* Determine the best encoding. Compute the block lengths in bytes. */
  24570. opt_lenb = (s.opt_len+3+7) >>> 3;
  24571. static_lenb = (s.static_len+3+7) >>> 3;
  24572. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24573. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24574. // s->last_lit));
  24575. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24576. } else {
  24577. // Assert(buf != (char*)0, "lost buf");
  24578. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24579. }
  24580. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24581. /* 4: two words for the lengths */
  24582. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24583. * Otherwise we can't have processed more than WSIZE input bytes since
  24584. * the last block flush, because compression would have been
  24585. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24586. * transform a block into a stored block.
  24587. */
  24588. _tr_stored_block(s, buf, stored_len, last);
  24589. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24590. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24591. compress_block(s, static_ltree, static_dtree);
  24592. } else {
  24593. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24594. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24595. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24596. }
  24597. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24598. /* The above check is made mod 2^32, for files larger than 512 MB
  24599. * and uLong implemented on 32 bits.
  24600. */
  24601. init_block(s);
  24602. if (last) {
  24603. bi_windup(s);
  24604. }
  24605. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24606. // s->compressed_len-7*last));
  24607. }
  24608. /* ===========================================================================
  24609. * Save the match info and tally the frequency counts. Return true if
  24610. * the current block must be flushed.
  24611. */
  24612. function _tr_tally(s, dist, lc)
  24613. // deflate_state *s;
  24614. // unsigned dist; /* distance of matched string */
  24615. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24616. {
  24617. //var out_length, in_length, dcode;
  24618. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24619. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24620. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24621. s.last_lit++;
  24622. if (dist === 0) {
  24623. /* lc is the unmatched char */
  24624. s.dyn_ltree[lc*2]/*.Freq*/++;
  24625. } else {
  24626. s.matches++;
  24627. /* Here, lc is the match length - MIN_MATCH */
  24628. dist--; /* dist = match distance - 1 */
  24629. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24630. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24631. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24632. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24633. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24634. }
  24635. // (!) This block is disabled in zlib defailts,
  24636. // don't enable it for binary compatibility
  24637. //#ifdef TRUNCATE_BLOCK
  24638. // /* Try to guess if it is profitable to stop the current block here */
  24639. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24640. // /* Compute an upper bound for the compressed length */
  24641. // out_length = s.last_lit*8;
  24642. // in_length = s.strstart - s.block_start;
  24643. //
  24644. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24645. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24646. // }
  24647. // out_length >>>= 3;
  24648. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24649. // // s->last_lit, in_length, out_length,
  24650. // // 100L - out_length*100L/in_length));
  24651. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24652. // return true;
  24653. // }
  24654. // }
  24655. //#endif
  24656. return (s.last_lit === s.lit_bufsize-1);
  24657. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24658. * on 16 bit machines and because stored blocks are restricted to
  24659. * 64K-1 bytes.
  24660. */
  24661. }
  24662. exports._tr_init = _tr_init;
  24663. exports._tr_stored_block = _tr_stored_block;
  24664. exports._tr_flush_block = _tr_flush_block;
  24665. exports._tr_tally = _tr_tally;
  24666. exports._tr_align = _tr_align;
  24667. },{"../utils/common":72}],84:[function(require,module,exports){
  24668. 'use strict';
  24669. function ZStream() {
  24670. /* next input byte */
  24671. this.input = null; // JS specific, because we have no pointers
  24672. this.next_in = 0;
  24673. /* number of bytes available at input */
  24674. this.avail_in = 0;
  24675. /* total number of input bytes read so far */
  24676. this.total_in = 0;
  24677. /* next output byte should be put there */
  24678. this.output = null; // JS specific, because we have no pointers
  24679. this.next_out = 0;
  24680. /* remaining free space at output */
  24681. this.avail_out = 0;
  24682. /* total number of bytes output so far */
  24683. this.total_out = 0;
  24684. /* last error message, NULL if no error */
  24685. this.msg = ''/*Z_NULL*/;
  24686. /* not visible by applications */
  24687. this.state = null;
  24688. /* best guess about the data type: binary or text */
  24689. this.data_type = 2/*Z_UNKNOWN*/;
  24690. /* adler32 value of the uncompressed data */
  24691. this.adler = 0;
  24692. }
  24693. module.exports = ZStream;
  24694. },{}],85:[function(require,module,exports){
  24695. module.exports = require('./lib/retry');
  24696. },{"./lib/retry":86}],86:[function(require,module,exports){
  24697. var RetryOperation = require('./retry_operation');
  24698. exports.operation = function(options) {
  24699. var timeouts = exports.timeouts(options);
  24700. return new RetryOperation(timeouts);
  24701. };
  24702. exports.timeouts = function(options) {
  24703. if (options instanceof Array) {
  24704. return [].concat(options);
  24705. }
  24706. var opts = {
  24707. retries: 10,
  24708. factor: 2,
  24709. minTimeout: 1 * 1000,
  24710. maxTimeout: Infinity,
  24711. randomize: false
  24712. };
  24713. for (var key in options) {
  24714. opts[key] = options[key];
  24715. }
  24716. if (opts.minTimeout > opts.maxTimeout) {
  24717. throw new Error('minTimeout is greater than maxTimeout');
  24718. }
  24719. var timeouts = [];
  24720. for (var i = 0; i < opts.retries; i++) {
  24721. timeouts.push(this._createTimeout(i, opts));
  24722. }
  24723. // sort the array numerically ascending
  24724. timeouts.sort(function(a,b) {
  24725. return a - b;
  24726. });
  24727. return timeouts;
  24728. };
  24729. exports._createTimeout = function(attempt, opts) {
  24730. var random = (opts.randomize)
  24731. ? (Math.random() + 1)
  24732. : 1;
  24733. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  24734. timeout = Math.min(timeout, opts.maxTimeout);
  24735. return timeout;
  24736. };
  24737. },{"./retry_operation":87}],87:[function(require,module,exports){
  24738. function RetryOperation(timeouts) {
  24739. this._timeouts = timeouts;
  24740. this._fn = null;
  24741. this._errors = [];
  24742. this._attempts = 1;
  24743. this._operationTimeout = null;
  24744. this._operationTimeoutCb = null;
  24745. this._timeout = null;
  24746. }
  24747. module.exports = RetryOperation;
  24748. RetryOperation.prototype.retry = function(err) {
  24749. if (this._timeout) {
  24750. clearTimeout(this._timeout);
  24751. }
  24752. if (!err) {
  24753. return false;
  24754. }
  24755. this._errors.push(err);
  24756. var timeout = this._timeouts.shift();
  24757. if (timeout === undefined) {
  24758. return false;
  24759. }
  24760. this._attempts++;
  24761. var self = this;
  24762. setTimeout(function() {
  24763. self._fn(self._attempts);
  24764. if (self._operationTimeoutCb) {
  24765. self._timeout = setTimeout(function() {
  24766. self._operationTimeoutCb(self._attempts);
  24767. }, self._operationTimeout);
  24768. }
  24769. }, timeout);
  24770. return true;
  24771. };
  24772. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  24773. this._fn = fn;
  24774. if (timeoutOps) {
  24775. if (timeoutOps.timeout) {
  24776. this._operationTimeout = timeoutOps.timeout;
  24777. }
  24778. if (timeoutOps.cb) {
  24779. this._operationTimeoutCb = timeoutOps.cb;
  24780. }
  24781. }
  24782. this._fn(this._attempts);
  24783. var self = this;
  24784. if (this._operationTimeoutCb) {
  24785. this._timeout = setTimeout(function() {
  24786. self._operationTimeoutCb();
  24787. }, self._operationTimeout);
  24788. }
  24789. };
  24790. RetryOperation.prototype.try = function(fn) {
  24791. console.log('Using RetryOperation.try() is deprecated');
  24792. this.attempt(fn);
  24793. };
  24794. RetryOperation.prototype.start = function(fn) {
  24795. console.log('Using RetryOperation.start() is deprecated');
  24796. this.attempt(fn);
  24797. };
  24798. RetryOperation.prototype.start = RetryOperation.prototype.try;
  24799. RetryOperation.prototype.errors = function() {
  24800. return this._errors;
  24801. };
  24802. RetryOperation.prototype.attempts = function() {
  24803. return this._attempts;
  24804. };
  24805. RetryOperation.prototype.mainError = function() {
  24806. if (this._errors.length === 0) {
  24807. return null;
  24808. }
  24809. var counts = {};
  24810. var mainError = null;
  24811. var mainErrorCount = 0;
  24812. for (var i = 0; i < this._errors.length; i++) {
  24813. var error = this._errors[i];
  24814. var message = error.message;
  24815. var count = (counts[message] || 0) + 1;
  24816. counts[message] = count;
  24817. if (count >= mainErrorCount) {
  24818. mainError = error;
  24819. mainErrorCount = count;
  24820. }
  24821. }
  24822. return mainError;
  24823. };
  24824. },{}],88:[function(require,module,exports){
  24825. module.exports = function arrayEquals(array) {
  24826. // if the other array is a falsy value, return
  24827. if (!array)
  24828. return false;
  24829. // compare lengths - can save a lot of time
  24830. if (this.length != array.length)
  24831. return false;
  24832. for (var i = 0, l = this.length; i < l; i++) {
  24833. // Check if we have nested arrays
  24834. if (this[i] instanceof Array && array[i] instanceof Array) {
  24835. // recurse into the nested arrays
  24836. if (!arrayEquals.apply(this[i], [array[i]]))
  24837. return false;
  24838. } else if (this[i] != array[i]) {
  24839. // Warning - two different object instances will never be equal:
  24840. // {x:20} != {x:20}
  24841. return false;
  24842. }
  24843. }
  24844. return true;
  24845. }
  24846. },{}],89:[function(require,module,exports){
  24847. exports.Interop = require('./interop');
  24848. },{"./interop":90}],90:[function(require,module,exports){
  24849. "use strict";
  24850. var transform = require('./transform');
  24851. var arrayEquals = require('./array-equals');
  24852. function Interop() {
  24853. /**
  24854. * This map holds the most recent Unified Plan offer/answer SDP that was
  24855. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  24856. * the SDP string as values.
  24857. *
  24858. * @type {{}}
  24859. */
  24860. this.cache = {};
  24861. }
  24862. module.exports = Interop;
  24863. /**
  24864. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  24865. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  24866. * application.
  24867. *
  24868. * @param desc
  24869. * @returns {*}
  24870. */
  24871. Interop.prototype.toPlanB = function(desc) {
  24872. //#region Preliminary input validation.
  24873. if (typeof desc !== 'object' || desc === null ||
  24874. typeof desc.sdp !== 'string') {
  24875. console.warn('An empty description was passed as an argument.');
  24876. return desc;
  24877. }
  24878. // Objectify the SDP for easier manipulation.
  24879. var session = transform.parse(desc.sdp);
  24880. // If the SDP contains no media, there's nothing to transform.
  24881. if (typeof session.media === 'undefined' ||
  24882. !Array.isArray(session.media) || session.media.length === 0) {
  24883. console.warn('The description has no media.');
  24884. return desc;
  24885. }
  24886. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  24887. // SDP has a video, an audio and a data "channel" at most.
  24888. if (session.media.length <= 3 && session.media.every(function(m) {
  24889. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24890. })) {
  24891. console.warn('This description does not look like Unified Plan.');
  24892. return desc;
  24893. }
  24894. //#endregion
  24895. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  24896. // -> Unified Plan transformation.
  24897. this.cache[desc.type] = desc.sdp;
  24898. //#region Convert from Unified Plan to Plan B.
  24899. // We rebuild the session.media array.
  24900. var media = session.media;
  24901. session.media = [];
  24902. // Associative array that maps channel types to channel objects for fast
  24903. // access to channel objects by their type, e.g. type2bl['audio']->channel
  24904. // obj.
  24905. var type2bl = {};
  24906. // Used to build the group:BUNDLE value after the channels construction
  24907. // loop.
  24908. var types = [];
  24909. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  24910. media.forEach(function(unifiedLine) {
  24911. // rtcp-mux is required in the Plan B SDP.
  24912. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  24913. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  24914. unifiedLine.direction !== 'inactive') {
  24915. throw new Error('Cannot convert to Plan B because m-lines ' +
  24916. 'without the rtcp-mux attribute were found.');
  24917. }
  24918. if (unifiedLine.type === 'application') {
  24919. session.media.push(unifiedLine);
  24920. types.push(unifiedLine.mid);
  24921. return;
  24922. }
  24923. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  24924. // as the channel basis.
  24925. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  24926. type2bl[unifiedLine.type] = unifiedLine;
  24927. }
  24928. // Add sources to the channel and handle a=msid.
  24929. if (typeof unifiedLine.sources === 'object') {
  24930. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  24931. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  24932. type2bl[unifiedLine.type].sources = {};
  24933. // Assign the sources to the channel.
  24934. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  24935. if (typeof unifiedLine.msid !== 'undefined') {
  24936. // In Plan B the msid is an SSRC attribute. Also, we don't
  24937. // care about the obsolete label and mslabel attributes.
  24938. //
  24939. // Note that it is not guaranteed that the unifiedLine will have
  24940. // an msid. recvonly channels in particular don't have one.
  24941. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  24942. }
  24943. // NOTE ssrcs in ssrc groups will share msids, as
  24944. // draft-uberti-rtcweb-plan-00 mandates.
  24945. });
  24946. }
  24947. // Add ssrc groups to the channel.
  24948. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  24949. Array.isArray(unifiedLine.ssrcGroups)) {
  24950. // Create the ssrcGroups array, if it's not defined.
  24951. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  24952. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  24953. type2bl[unifiedLine.type].ssrcGroups = [];
  24954. }
  24955. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  24956. }
  24957. if (type2bl[unifiedLine.type] === unifiedLine) {
  24958. // Copy ICE related stuff from the principal media line.
  24959. unifiedLine.candidates = media[0].candidates;
  24960. unifiedLine.iceUfrag = media[0].iceUfrag;
  24961. unifiedLine.icePwd = media[0].icePwd;
  24962. unifiedLine.fingerprint = media[0].fingerprint;
  24963. // Plan B mids are in ['audio', 'video', 'data']
  24964. unifiedLine.mid = unifiedLine.type;
  24965. // Plan B doesn't support/need the bundle-only attribute.
  24966. delete unifiedLine.bundleOnly;
  24967. // In Plan B the msid is an SSRC attribute.
  24968. delete unifiedLine.msid;
  24969. // Used to build the group:BUNDLE value after this loop.
  24970. types.push(unifiedLine.type);
  24971. // Add the channel to the new media array.
  24972. session.media.push(unifiedLine);
  24973. }
  24974. });
  24975. // We regenerate the BUNDLE group with the new mids.
  24976. session.groups.some(function(group) {
  24977. if (group.type === 'BUNDLE') {
  24978. group.mids = types.join(' ');
  24979. return true;
  24980. }
  24981. });
  24982. // msid semantic
  24983. session.msidSemantic = {
  24984. semantic: 'WMS',
  24985. token: '*'
  24986. };
  24987. var resStr = transform.write(session);
  24988. return new RTCSessionDescription({
  24989. type: desc.type,
  24990. sdp: resStr
  24991. });
  24992. //#endregion
  24993. };
  24994. /**
  24995. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  24996. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  24997. * to FF.
  24998. *
  24999. * @param desc
  25000. * @returns {*}
  25001. */
  25002. Interop.prototype.toUnifiedPlan = function(desc) {
  25003. //#region Preliminary input validation.
  25004. if (typeof desc !== 'object' || desc === null ||
  25005. typeof desc.sdp !== 'string') {
  25006. console.warn('An empty description was passed as an argument.');
  25007. return desc;
  25008. }
  25009. var session = transform.parse(desc.sdp);
  25010. // If the SDP contains no media, there's nothing to transform.
  25011. if (typeof session.media === 'undefined' ||
  25012. !Array.isArray(session.media) || session.media.length === 0) {
  25013. console.warn('The description has no media.');
  25014. return desc;
  25015. }
  25016. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25017. // a video, an audio and a data "channel" at most.
  25018. if (session.media.length > 3 || !session.media.every(function(m) {
  25019. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25020. })) {
  25021. console.warn('This description does not look like Plan B.');
  25022. return desc;
  25023. }
  25024. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25025. var mids = [];
  25026. session.media.forEach(function(m) {
  25027. mids.push(m.mid);
  25028. });
  25029. var hasBundle = false;
  25030. if (typeof session.groups !== 'undefined' &&
  25031. Array.isArray(session.groups)) {
  25032. hasBundle = session.groups.every(function(g) {
  25033. return g.type !== 'BUNDLE' ||
  25034. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25035. });
  25036. }
  25037. if (!hasBundle) {
  25038. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25039. " are not bundled were found.");
  25040. }
  25041. //#endregion
  25042. //#region Convert from Plan B to Unified Plan.
  25043. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25044. // rebuild an equivalent Unified Plan offer/answer.
  25045. //
  25046. // For example, if this is a local answer (in Unified Plan style) that we
  25047. // convert to Plan B prior to handing it over to the application (the
  25048. // PeerConnection wrapper called us, for instance, after a successful
  25049. // createAnswer), we want to remember the m-line at which we've seen the
  25050. // (local) SSRC. That's because when the application wants to do call the
  25051. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25052. // Unified Plan), we need to know to which m-line to assign the (local)
  25053. // SSRC. We also need to know all the other m-lines that the original
  25054. // answer had and include them in the transformed answer as well.
  25055. //
  25056. // Another example is if this is a remote offer that we convert to Plan B
  25057. // prior to giving it to the application, we want to remember the mid at
  25058. // which we've seen the (remote) SSRC.
  25059. //
  25060. // In the iteration that follows, we use the cached Unified Plan (if it
  25061. // exists) to assign mids to ssrcs.
  25062. var cached;
  25063. if (typeof this.cache[desc.type] !== 'undefined') {
  25064. cached = transform.parse(this.cache[desc.type]);
  25065. }
  25066. // A helper map that sends mids to m-line objects. We use it later to
  25067. // rebuild the Unified Plan style session.media array.
  25068. var mid2ul = {};
  25069. session.media.forEach(function(bLine) {
  25070. if ((typeof bLine.rtcpMux !== 'string' ||
  25071. bLine.rtcpMux !== 'rtcp-mux') &&
  25072. bLine.direction !== 'inactive') {
  25073. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25074. "without the rtcp-mux attribute were found.");
  25075. }
  25076. if (bLine.type === 'application') {
  25077. mid2ul[bLine.mid] = bLine;
  25078. return;
  25079. }
  25080. // With rtcp-mux and bundle all the channels should have the same ICE
  25081. // stuff.
  25082. var sources = bLine.sources;
  25083. var ssrcGroups = bLine.ssrcGroups;
  25084. var candidates = bLine.candidates;
  25085. var iceUfrag = bLine.iceUfrag;
  25086. var icePwd = bLine.icePwd;
  25087. var fingerprint = bLine.fingerprint;
  25088. var port = bLine.port;
  25089. // We'll use the "bLine" object as a prototype for each new "mLine"
  25090. // that we create, but first we need to clean it up a bit.
  25091. delete bLine.sources;
  25092. delete bLine.ssrcGroups;
  25093. delete bLine.candidates;
  25094. delete bLine.iceUfrag;
  25095. delete bLine.icePwd;
  25096. delete bLine.fingerprint;
  25097. delete bLine.port;
  25098. delete bLine.mid;
  25099. // inverted ssrc group map
  25100. var ssrc2group = {};
  25101. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25102. ssrcGroups.forEach(function (ssrcGroup) {
  25103. // TODO(gp) find out how to receive simulcast with FF. For the
  25104. // time being, hide it.
  25105. if (ssrcGroup.semantics === 'SIM') {
  25106. return;
  25107. }
  25108. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25109. Array.isArray(ssrcGroup.ssrcs)) {
  25110. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25111. if (typeof ssrc2group[ssrc] === 'undefined') {
  25112. ssrc2group[ssrc] = [];
  25113. }
  25114. ssrc2group[ssrc].push(ssrcGroup);
  25115. });
  25116. }
  25117. });
  25118. }
  25119. // ssrc to m-line index.
  25120. var ssrc2ml = {};
  25121. if (typeof sources === 'object') {
  25122. // Explode the Plan B channel sources with one m-line per source.
  25123. Object.keys(sources).forEach(function(ssrc) {
  25124. // The (unified) m-line for this SSRC. We either create it from
  25125. // scratch or, if it's a grouped SSRC, we re-use a related
  25126. // mline. In other words, if the source is grouped with another
  25127. // source, put the two together in the same m-line.
  25128. var unifiedLine;
  25129. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25130. Array.isArray(ssrc2group[ssrc])) {
  25131. ssrc2group[ssrc].some(function (ssrcGroup) {
  25132. // ssrcGroup.ssrcs *is* an Array, no need to check
  25133. // again here.
  25134. return ssrcGroup.ssrcs.some(function (related) {
  25135. if (typeof ssrc2ml[related] === 'object') {
  25136. unifiedLine = ssrc2ml[related];
  25137. return true;
  25138. }
  25139. });
  25140. });
  25141. }
  25142. if (typeof unifiedLine === 'object') {
  25143. // the m-line already exists. Just add the source.
  25144. unifiedLine.sources[ssrc] = sources[ssrc];
  25145. delete sources[ssrc].msid;
  25146. } else {
  25147. // Use the "bLine" as a prototype for the "unifiedLine".
  25148. unifiedLine = Object.create(bLine);
  25149. ssrc2ml[ssrc] = unifiedLine;
  25150. if (typeof sources[ssrc].msid !== 'undefined') {
  25151. // Assign the msid of the source to the m-line. Note
  25152. // that it is not guaranteed that the source will have
  25153. // msid. In particular "recvonly" sources don't have an
  25154. // msid. Note that "recvonly" is a term only defined
  25155. // for m-lines.
  25156. unifiedLine.msid = sources[ssrc].msid;
  25157. delete sources[ssrc].msid;
  25158. }
  25159. // We assign one SSRC per media line.
  25160. unifiedLine.sources = {};
  25161. unifiedLine.sources[ssrc] = sources[ssrc];
  25162. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25163. // Use the cached Unified Plan SDP (if it exists) to assign
  25164. // SSRCs to mids.
  25165. if (typeof cached !== 'undefined' &&
  25166. typeof cached.media !== 'undefined' &&
  25167. Array.isArray(cached.media)) {
  25168. cached.media.forEach(function (m) {
  25169. if (typeof m.sources === 'object') {
  25170. Object.keys(m.sources).forEach(function (s) {
  25171. if (s === ssrc) {
  25172. unifiedLine.mid = m.mid;
  25173. }
  25174. });
  25175. }
  25176. });
  25177. }
  25178. if (typeof unifiedLine.mid === 'undefined') {
  25179. // If this is an SSRC that we see for the first time
  25180. // assign it a new mid. This is typically the case when
  25181. // this method is called to transform a remote
  25182. // description for the first time or when there is a
  25183. // new SSRC in the remote description because a new
  25184. // peer has joined the conference. Local SSRCs should
  25185. // have already been added to the map in the toPlanB
  25186. // method.
  25187. //
  25188. // Because FF generates answers in Unified Plan style,
  25189. // we MUST already have a cached answer with all the
  25190. // local SSRCs mapped to some m-line/mid.
  25191. if (desc.type === 'answer') {
  25192. throw new Error("An unmapped SSRC was found.");
  25193. }
  25194. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25195. }
  25196. // Include the candidates in the 1st media line.
  25197. unifiedLine.candidates = candidates;
  25198. unifiedLine.iceUfrag = iceUfrag;
  25199. unifiedLine.icePwd = icePwd;
  25200. unifiedLine.fingerprint = fingerprint;
  25201. unifiedLine.port = port;
  25202. mid2ul[unifiedLine.mid] = unifiedLine;
  25203. }
  25204. });
  25205. }
  25206. });
  25207. // Rebuild the media array in the right order and add the missing mLines
  25208. // (missing from the Plan B SDP).
  25209. session.media = [];
  25210. mids = []; // reuse
  25211. if (desc.type === 'answer') {
  25212. // The media lines in the answer must match the media lines in the
  25213. // offer. The order is important too. Here we assume that Firefox is the
  25214. // answerer, so we merely have to use the reconstructed (unified) answer
  25215. // to update the cached (unified) answer accordingly.
  25216. //
  25217. // In the general case, one would have to use the cached (unified) offer
  25218. // to find the m-lines that are missing from the reconstructed answer,
  25219. // potentially grabbing them from the cached (unified) answer. One has
  25220. // to be carefull with this approach because inactive m-lines do not
  25221. // always have an mid, making it tricky (impossible?) to find where
  25222. // exactly and which m-lines are missing from the reconstructed answer.
  25223. for (var i = 0; i < cached.media.length; i++) {
  25224. var unifiedLine = cached.media[i];
  25225. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25226. // The mid isn't in the reconstructed (unified) answer.
  25227. // This is either a (unified) m-line containing a remote
  25228. // track only, or a (unified) m-line containing a remote
  25229. // track and a local track that has been removed.
  25230. // In either case, it MUST exist in the cached
  25231. // (unified) answer.
  25232. //
  25233. // In case this is a removed local track, clean-up
  25234. // the (unified) m-line and make sure it's 'recvonly' or
  25235. // 'inactive'.
  25236. delete unifiedLine.msid;
  25237. delete unifiedLine.sources;
  25238. delete unifiedLine.ssrcGroups;
  25239. if (!unifiedLine.direction
  25240. || unifiedLine.direction === 'sendrecv')
  25241. unifiedLine.direction = 'recvonly';
  25242. if (!unifiedLine.direction
  25243. || unifiedLine.direction === 'sendonly')
  25244. unifiedLine.direction = 'inactive';
  25245. } else {
  25246. // This is an (unified) m-line/channel that contains a local
  25247. // track (sendrecv or sendonly channel) or it's a unified
  25248. // recvonly m-line/channel. In either case, since we're
  25249. // going from PlanB -> Unified Plan this m-line MUST
  25250. // exist in the cached answer.
  25251. }
  25252. session.media.push(unifiedLine);
  25253. if (typeof unifiedLine.mid === 'string') {
  25254. // inactive lines don't/may not have an mid.
  25255. mids.push(unifiedLine.mid);
  25256. }
  25257. }
  25258. } else {
  25259. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25260. // under any circumstances. If we are no longer interested in sending a
  25261. // track, we just remove the msid and ssrc attributes and set it to
  25262. // either a=recvonly (as the reofferer, we must use recvonly if the
  25263. // other side was previously sending on the m-section, but we can also
  25264. // leave the possibility open if it wasn't previously in use), or
  25265. // a=inacive.
  25266. if (typeof cached !== 'undefined' &&
  25267. typeof cached.media !== 'undefined' &&
  25268. Array.isArray(cached.media)) {
  25269. cached.media.forEach(function(unifiedLine) {
  25270. mids.push(unifiedLine.mid);
  25271. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25272. session.media.push(mid2ul[unifiedLine.mid]);
  25273. } else {
  25274. delete unifiedLine.msid;
  25275. delete unifiedLine.sources;
  25276. delete unifiedLine.ssrcGroups;
  25277. if (!unifiedLine.direction
  25278. || unifiedLine.direction === 'sendrecv')
  25279. unifiedLine.direction = 'recvonly';
  25280. if (!unifiedLine.direction
  25281. || unifiedLine.direction === 'sendonly')
  25282. unifiedLine.direction = 'inactive';
  25283. session.media.push(unifiedLine);
  25284. }
  25285. });
  25286. }
  25287. // Add all the remaining (new) m-lines of the transformed SDP.
  25288. Object.keys(mid2ul).forEach(function(mid) {
  25289. if (mids.indexOf(mid) === -1) {
  25290. mids.push(mid);
  25291. if (typeof mid2ul[mid].direction === 'recvonly') {
  25292. // This is a remote recvonly channel. Add its SSRC to the
  25293. // appropriate sendrecv or sendonly channel.
  25294. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25295. session.media.some(function (unifiedLine) {
  25296. if ((unifiedLine.direction === 'sendrecv' ||
  25297. unifiedLine.direction === 'sendonly') &&
  25298. unifiedLine.type === mid2ul[mid].type) {
  25299. // mid2ul[mid] shouldn't have any ssrc-groups
  25300. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25301. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25302. });
  25303. return true;
  25304. }
  25305. });
  25306. } else {
  25307. session.media.push(mid2ul[mid]);
  25308. }
  25309. }
  25310. });
  25311. }
  25312. // We regenerate the BUNDLE group (since we regenerated the mids)
  25313. session.groups.some(function(group) {
  25314. if (group.type === 'BUNDLE') {
  25315. group.mids = mids.join(' ');
  25316. return true;
  25317. }
  25318. });
  25319. // msid semantic
  25320. session.msidSemantic = {
  25321. semantic: 'WMS',
  25322. token: '*'
  25323. };
  25324. var resStr = transform.write(session);
  25325. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25326. // function.
  25327. this.cache[desc.type] = resStr;
  25328. return new RTCSessionDescription({
  25329. type: desc.type,
  25330. sdp: resStr
  25331. });
  25332. //#endregion
  25333. };
  25334. },{"./array-equals":88,"./transform":91}],91:[function(require,module,exports){
  25335. var transform = require('sdp-transform');
  25336. exports.write = function(session, opts) {
  25337. if (typeof session !== 'undefined' &&
  25338. typeof session.media !== 'undefined' &&
  25339. Array.isArray(session.media)) {
  25340. session.media.forEach(function (mLine) {
  25341. // expand sources to ssrcs
  25342. if (typeof mLine.sources !== 'undefined' &&
  25343. Object.keys(mLine.sources).length !== 0) {
  25344. mLine.ssrcs = [];
  25345. Object.keys(mLine.sources).forEach(function (ssrc) {
  25346. var source = mLine.sources[ssrc];
  25347. Object.keys(source).forEach(function (attribute) {
  25348. mLine.ssrcs.push({
  25349. id: ssrc,
  25350. attribute: attribute,
  25351. value: source[attribute]
  25352. });
  25353. });
  25354. });
  25355. delete mLine.sources;
  25356. }
  25357. // join ssrcs in ssrc groups
  25358. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25359. Array.isArray(mLine.ssrcGroups)) {
  25360. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25361. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25362. Array.isArray(ssrcGroup.ssrcs)) {
  25363. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25364. }
  25365. });
  25366. }
  25367. });
  25368. }
  25369. // join group mids
  25370. if (typeof session !== 'undefined' &&
  25371. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25372. session.groups.forEach(function (g) {
  25373. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25374. g.mids = g.mids.join(' ');
  25375. }
  25376. });
  25377. }
  25378. return transform.write(session, opts);
  25379. };
  25380. exports.parse = function(sdp) {
  25381. var session = transform.parse(sdp);
  25382. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25383. Array.isArray(session.media)) {
  25384. session.media.forEach(function (mLine) {
  25385. // group sources attributes by ssrc
  25386. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25387. mLine.sources = {};
  25388. mLine.ssrcs.forEach(function (ssrc) {
  25389. if (!mLine.sources[ssrc.id])
  25390. mLine.sources[ssrc.id] = {};
  25391. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25392. });
  25393. delete mLine.ssrcs;
  25394. }
  25395. // split ssrcs in ssrc groups
  25396. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25397. Array.isArray(mLine.ssrcGroups)) {
  25398. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25399. if (typeof ssrcGroup.ssrcs === 'string') {
  25400. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25401. }
  25402. });
  25403. }
  25404. });
  25405. }
  25406. // split group mids
  25407. if (typeof session !== 'undefined' &&
  25408. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25409. session.groups.forEach(function (g) {
  25410. if (typeof g.mids === 'string') {
  25411. g.mids = g.mids.split(' ');
  25412. }
  25413. });
  25414. }
  25415. return session;
  25416. };
  25417. },{"sdp-transform":95}],92:[function(require,module,exports){
  25418. var transform = require('sdp-transform');
  25419. var transformUtils = require('./transform-utils');
  25420. var parseSsrcs = transformUtils.parseSsrcs;
  25421. var writeSsrcs = transformUtils.writeSsrcs;
  25422. //region Constants
  25423. var DEFAULT_NUM_OF_LAYERS = 3;
  25424. //endregion
  25425. //region Ctor
  25426. function Simulcast(options) {
  25427. this.options = options ? options : {};
  25428. if (!this.options.numOfLayers) {
  25429. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  25430. }
  25431. this.layers = [];
  25432. }
  25433. //endregion
  25434. //region Stateless private utility functions
  25435. /**
  25436. * Returns a random integer between min (included) and max (excluded)
  25437. * Using Math.round() gives a non-uniform distribution!
  25438. * @returns {number}
  25439. */
  25440. function generateSSRC() {
  25441. var min = 0, max = 0xffffffff;
  25442. return Math.floor(Math.random() * (max - min)) + min;
  25443. };
  25444. function processVideo(session, action) {
  25445. if (session == null || !Array.isArray(session.media)) {
  25446. return;
  25447. }
  25448. session.media.forEach(function (mLine) {
  25449. if (mLine.type === 'video') {
  25450. action(mLine);
  25451. }
  25452. });
  25453. }
  25454. function validateDescription(desc)
  25455. {
  25456. return desc && desc != null
  25457. && desc.type && desc.type != ''
  25458. && desc.sdp && desc.sdp != '';
  25459. }
  25460. function explodeRemoteSimulcast(mLine) {
  25461. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25462. return;
  25463. }
  25464. var sources = parseSsrcs(mLine);
  25465. var order = [];
  25466. // Find the SIM group and explode its sources.
  25467. var j = mLine.ssrcGroups.length;
  25468. while (j--) {
  25469. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  25470. continue;
  25471. }
  25472. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  25473. for (var i = 0; i < simulcastSsrcs.length; i++) {
  25474. var ssrc = simulcastSsrcs[i];
  25475. order.push(ssrc);
  25476. var parts = sources[ssrc].msid.split(' ');
  25477. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  25478. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  25479. // Remove all the groups that this SSRC participates in.
  25480. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25481. if (relatedGroup.semantics === 'SIM') {
  25482. return;
  25483. }
  25484. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25485. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25486. return;
  25487. }
  25488. // Nuke all the related SSRCs.
  25489. relatedSsrcs.forEach(function (relatedSSRC) {
  25490. sources[relatedSSRC].msid = sources[ssrc].msid;
  25491. sources[relatedSSRC].cname = sources[ssrc].cname;
  25492. if (relatedSSRC !== ssrc) {
  25493. order.push(relatedSSRC);
  25494. }
  25495. });
  25496. // Schedule the related group for nuking.
  25497. })
  25498. }
  25499. mLine.ssrcs = writeSsrcs(sources, order);
  25500. mLine.ssrcGroups.splice(j, 1);
  25501. };
  25502. }
  25503. function squeezeRemoteSimulcast(mLine) {
  25504. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25505. return;
  25506. }
  25507. var sources = parseSsrcs(mLine);
  25508. // Find the SIM group and nuke it.
  25509. mLine.ssrcGroups.some(function (simulcastGroup) {
  25510. if (simulcastGroup.semantics !== 'SIM') {
  25511. return false;
  25512. }
  25513. // Schedule the SIM group for nuking.
  25514. simulcastGroup.nuke = true;
  25515. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  25516. // Nuke all the higher layer SSRCs.
  25517. for (var i = 1; i < simulcastSsrcs.length; i++) {
  25518. var ssrc = simulcastSsrcs[i];
  25519. delete sources[ssrc];
  25520. // Remove all the groups that this SSRC participates in.
  25521. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25522. if (relatedGroup.semantics === 'SIM') {
  25523. return;
  25524. }
  25525. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25526. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25527. return;
  25528. }
  25529. // Nuke all the related SSRCs.
  25530. relatedSsrcs.forEach(function (relatedSSRC) {
  25531. delete sources[relatedSSRC];
  25532. });
  25533. // Schedule the related group for nuking.
  25534. relatedGroup.nuke = true;
  25535. })
  25536. }
  25537. return true;
  25538. });
  25539. mLine.ssrcs = writeSsrcs(sources);
  25540. // Nuke all the scheduled groups.
  25541. var i = mLine.ssrcGroups.length;
  25542. while (i--) {
  25543. if (mLine.ssrcGroups[i].nuke) {
  25544. mLine.ssrcGroups.splice(i, 1);
  25545. }
  25546. }
  25547. }
  25548. function removeGoogConference(mLine) {
  25549. if (!mLine || !Array.isArray(mLine.invalid)) {
  25550. return;
  25551. }
  25552. var i = mLine.invalid.length;
  25553. while (i--) {
  25554. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  25555. mLine.invalid.splice(i, 1);
  25556. }
  25557. }
  25558. }
  25559. function assertGoogConference(mLine) {
  25560. if (!mLine) {
  25561. return;
  25562. }
  25563. if (!Array.isArray(mLine.invalid)) {
  25564. mLine.invalid = [];
  25565. }
  25566. if (!mLine.invalid.some(
  25567. function (i) { return i.value === 'x-google-flag:conference' })) {
  25568. mLine.invalid.push({'value': 'x-google-flag:conference'});
  25569. }
  25570. }
  25571. //endregion
  25572. //region "Private" functions
  25573. /**
  25574. *
  25575. * @param mLine
  25576. * @private
  25577. */
  25578. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  25579. if (!mLine || mLine.type !== 'video') {
  25580. return;
  25581. }
  25582. var sources = parseSsrcs(mLine);
  25583. if (Object.keys(sources).length === 0) {
  25584. // no sources, disable simulcast.
  25585. if (this.layers.length !== 0) {
  25586. this.layers = [];
  25587. }
  25588. return;
  25589. }
  25590. // find the base layer (we'll reuse its msid and cname).
  25591. var baseLayerSSRC = Object.keys(sources)[0];
  25592. var baseLayer = sources[baseLayerSSRC];
  25593. // todo(gp) handle screen sharing.
  25594. // check if base CNAME has changed and reinitialise layers.
  25595. if (this.layers.length > 0
  25596. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  25597. this.layers = [];
  25598. }
  25599. // (re)initialise layers
  25600. if (this.layers.length < 1) {
  25601. // first push the base layer.
  25602. this.layers.push({
  25603. ssrc: baseLayerSSRC,
  25604. msid: baseLayer.msid,
  25605. cname: baseLayer.cname
  25606. });
  25607. var rtx = false; // RFC 4588
  25608. if (Array.isArray(mLine.rtp)) {
  25609. rtx = mLine.rtp.some(
  25610. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  25611. }
  25612. if (rtx) {
  25613. this.layers[0].rtx = generateSSRC();
  25614. }
  25615. // now push additional layers.
  25616. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  25617. var layer = { ssrc: generateSSRC() };
  25618. if (rtx) {
  25619. layer.rtx = generateSSRC();
  25620. }
  25621. this.layers.push(layer);
  25622. }
  25623. }
  25624. };
  25625. /**
  25626. *
  25627. * @param mLine
  25628. * @private
  25629. */
  25630. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  25631. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  25632. var sources = {};
  25633. var msid = this.layers[0].msid;
  25634. var cname = this.layers[0].cname;
  25635. var simulcastSsrcs = [];
  25636. var ssrcGroups = [];
  25637. for (var i = 0; i < this.layers.length; i++) {
  25638. var layer = this.layers[i];
  25639. sources[layer.ssrc] = { msid: msid, cname: cname };
  25640. simulcastSsrcs.push(layer.ssrc);
  25641. if (layer.rtx) {
  25642. sources[layer.rtx] = {
  25643. msid: msid,
  25644. cname: cname
  25645. }
  25646. ssrcGroups.push({
  25647. semantics: 'FID',
  25648. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  25649. });
  25650. }
  25651. }
  25652. ssrcGroups.push({
  25653. semantics: 'SIM',
  25654. ssrcs: simulcastSsrcs.join(' ')
  25655. });
  25656. mLine.ssrcGroups = ssrcGroups;
  25657. mLine.ssrcs = writeSsrcs(sources);
  25658. }
  25659. }
  25660. //endregion
  25661. //region "Public" functions
  25662. Simulcast.prototype.isSupported = function () {
  25663. return window.chrome;
  25664. // TODO this needs improvements. For example I doubt that Chrome in Android
  25665. // has simulcast support. Also, only recent versions of Chromium have native
  25666. // simulcast support.
  25667. }
  25668. /**
  25669. *
  25670. * @param desc
  25671. * @returns {RTCSessionDescription}
  25672. */
  25673. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  25674. if (!validateDescription(desc)) {
  25675. return desc;
  25676. }
  25677. var session = transform.parse(desc.sdp);
  25678. var self = this;
  25679. processVideo(session, function (mLine) {
  25680. // Handle simulcast reception.
  25681. if (self.options.explodeRemoteSimulcast) {
  25682. explodeRemoteSimulcast(mLine);
  25683. } else {
  25684. squeezeRemoteSimulcast(mLine);
  25685. }
  25686. // If native simulcast is enabled, we must append the x-goog-conference
  25687. // attribute to the SDP.
  25688. if (self.layers.length < 1) {
  25689. removeGoogConference(mLine);
  25690. } else {
  25691. assertGoogConference(mLine);
  25692. }
  25693. });
  25694. return new RTCSessionDescription({
  25695. type: desc.type,
  25696. sdp: transform.write(session)
  25697. });
  25698. };
  25699. /**
  25700. *
  25701. * @param desc
  25702. * @returns {RTCSessionDescription}
  25703. */
  25704. Simulcast.prototype.mungeLocalDescription = function (desc) {
  25705. if (!validateDescription(desc) || !this.isSupported()) {
  25706. return desc;
  25707. }
  25708. var session = transform.parse(desc.sdp);
  25709. var self = this;
  25710. processVideo(session, function (mLine) {
  25711. // Initialize native simulcast layers, if not already done.
  25712. self._maybeInitializeLayers(mLine);
  25713. // Update the SDP with the simulcast layers.
  25714. self._restoreSimulcastView(mLine);
  25715. });
  25716. return new RTCSessionDescription({
  25717. type: desc.type,
  25718. sdp: transform.write(session)
  25719. });
  25720. };
  25721. //endregion
  25722. module.exports = Simulcast;
  25723. },{"./transform-utils":93,"sdp-transform":95}],93:[function(require,module,exports){
  25724. exports.writeSsrcs = function(sources, order) {
  25725. var ssrcs = [];
  25726. // expand sources to ssrcs
  25727. if (typeof sources !== 'undefined' &&
  25728. Object.keys(sources).length !== 0) {
  25729. if (Array.isArray(order)) {
  25730. for (var i = 0; i < order.length; i++) {
  25731. var ssrc = order[i];
  25732. var source = sources[ssrc];
  25733. Object.keys(source).forEach(function (attribute) {
  25734. ssrcs.push({
  25735. id: ssrc,
  25736. attribute: attribute,
  25737. value: source[attribute]
  25738. });
  25739. });
  25740. }
  25741. } else {
  25742. Object.keys(sources).forEach(function (ssrc) {
  25743. var source = sources[ssrc];
  25744. Object.keys(source).forEach(function (attribute) {
  25745. ssrcs.push({
  25746. id: ssrc,
  25747. attribute: attribute,
  25748. value: source[attribute]
  25749. });
  25750. });
  25751. });
  25752. }
  25753. }
  25754. return ssrcs;
  25755. };
  25756. exports.parseSsrcs = function (mLine) {
  25757. var sources = {};
  25758. // group sources attributes by ssrc.
  25759. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25760. mLine.ssrcs.forEach(function (ssrc) {
  25761. if (!sources[ssrc.id])
  25762. sources[ssrc.id] = {};
  25763. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25764. });
  25765. }
  25766. return sources;
  25767. };
  25768. },{}],94:[function(require,module,exports){
  25769. var grammar = module.exports = {
  25770. v: [{
  25771. name: 'version',
  25772. reg: /^(\d*)$/
  25773. }],
  25774. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25775. // NB: sessionId will be a String in most cases because it is huge
  25776. name: 'origin',
  25777. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25778. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25779. format: "%s %s %d %s IP%d %s"
  25780. }],
  25781. // default parsing of these only (though some of these feel outdated)
  25782. s: [{ name: 'name' }],
  25783. i: [{ name: 'description' }],
  25784. u: [{ name: 'uri' }],
  25785. e: [{ name: 'email' }],
  25786. p: [{ name: 'phone' }],
  25787. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25788. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25789. //k: [{}], // outdated thing ignored
  25790. t: [{ //t=0 0
  25791. name: 'timing',
  25792. reg: /^(\d*) (\d*)/,
  25793. names: ['start', 'stop'],
  25794. format: "%d %d"
  25795. }],
  25796. c: [{ //c=IN IP4 10.47.197.26
  25797. name: 'connection',
  25798. reg: /^IN IP(\d) (\S*)/,
  25799. names: ['version', 'ip'],
  25800. format: "IN IP%d %s"
  25801. }],
  25802. b: [{ //b=AS:4000
  25803. push: 'bandwidth',
  25804. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25805. names: ['type', 'limit'],
  25806. format: "%s:%s"
  25807. }],
  25808. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25809. // NB: special - pushes to session
  25810. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25811. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25812. names: ['type', 'port', 'protocol', 'payloads'],
  25813. format: "%s %d %s %s"
  25814. }],
  25815. a: [
  25816. { //a=rtpmap:110 opus/48000/2
  25817. push: 'rtp',
  25818. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25819. names: ['payload', 'codec', 'rate', 'encoding'],
  25820. format: function (o) {
  25821. return (o.encoding) ?
  25822. "rtpmap:%d %s/%s/%s":
  25823. "rtpmap:%d %s/%s";
  25824. }
  25825. },
  25826. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25827. push: 'fmtp',
  25828. reg: /^fmtp:(\d*) (\S*)/,
  25829. names: ['payload', 'config'],
  25830. format: "fmtp:%d %s"
  25831. },
  25832. { //a=control:streamid=0
  25833. name: 'control',
  25834. reg: /^control:(.*)/,
  25835. format: "control:%s"
  25836. },
  25837. { //a=rtcp:65179 IN IP4 193.84.77.194
  25838. name: 'rtcp',
  25839. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25840. names: ['port', 'netType', 'ipVer', 'address'],
  25841. format: function (o) {
  25842. return (o.address != null) ?
  25843. "rtcp:%d %s IP%d %s":
  25844. "rtcp:%d";
  25845. }
  25846. },
  25847. { //a=rtcp-fb:98 trr-int 100
  25848. push: 'rtcpFbTrrInt',
  25849. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25850. names: ['payload', 'value'],
  25851. format: "rtcp-fb:%d trr-int %d"
  25852. },
  25853. { //a=rtcp-fb:98 nack rpsi
  25854. push: 'rtcpFb',
  25855. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25856. names: ['payload', 'type', 'subtype'],
  25857. format: function (o) {
  25858. return (o.subtype != null) ?
  25859. "rtcp-fb:%s %s %s":
  25860. "rtcp-fb:%s %s";
  25861. }
  25862. },
  25863. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25864. //a=extmap:1/recvonly URI-gps-string
  25865. push: 'ext',
  25866. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25867. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25868. format: function (o) {
  25869. return (o.config != null) ?
  25870. "extmap:%s %s %s":
  25871. "extmap:%s %s";
  25872. }
  25873. },
  25874. {
  25875. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25876. push: 'crypto',
  25877. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25878. names: ['id', 'suite', 'config', 'sessionConfig'],
  25879. format: function (o) {
  25880. return (o.sessionConfig != null) ?
  25881. "crypto:%d %s %s %s":
  25882. "crypto:%d %s %s";
  25883. }
  25884. },
  25885. { //a=setup:actpass
  25886. name: 'setup',
  25887. reg: /^setup:(\w*)/,
  25888. format: "setup:%s"
  25889. },
  25890. { //a=mid:1
  25891. name: 'mid',
  25892. reg: /^mid:([^\s]*)/,
  25893. format: "mid:%s"
  25894. },
  25895. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25896. name: 'msid',
  25897. reg: /^msid:(.*)/,
  25898. format: "msid:%s"
  25899. },
  25900. { //a=ptime:20
  25901. name: 'ptime',
  25902. reg: /^ptime:(\d*)/,
  25903. format: "ptime:%d"
  25904. },
  25905. { //a=maxptime:60
  25906. name: 'maxptime',
  25907. reg: /^maxptime:(\d*)/,
  25908. format: "maxptime:%d"
  25909. },
  25910. { //a=sendrecv
  25911. name: 'direction',
  25912. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25913. },
  25914. { //a=ice-lite
  25915. name: 'icelite',
  25916. reg: /^(ice-lite)/
  25917. },
  25918. { //a=ice-ufrag:F7gI
  25919. name: 'iceUfrag',
  25920. reg: /^ice-ufrag:(\S*)/,
  25921. format: "ice-ufrag:%s"
  25922. },
  25923. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25924. name: 'icePwd',
  25925. reg: /^ice-pwd:(\S*)/,
  25926. format: "ice-pwd:%s"
  25927. },
  25928. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25929. name: 'fingerprint',
  25930. reg: /^fingerprint:(\S*) (\S*)/,
  25931. names: ['type', 'hash'],
  25932. format: "fingerprint:%s %s"
  25933. },
  25934. {
  25935. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25936. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25937. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25938. push:'candidates',
  25939. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  25940. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  25941. format: function (o) {
  25942. var str = "candidate:%s %d %s %d %s %d typ %s";
  25943. // NB: candidate has two optional chunks, so %void middle one if it's missing
  25944. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25945. if (o.generation != null) {
  25946. str += " generation %d";
  25947. }
  25948. return str;
  25949. }
  25950. },
  25951. { //a=end-of-candidates (keep after the candidates line for readability)
  25952. name: 'endOfCandidates',
  25953. reg: /^(end-of-candidates)/
  25954. },
  25955. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25956. name: 'remoteCandidates',
  25957. reg: /^remote-candidates:(.*)/,
  25958. format: "remote-candidates:%s"
  25959. },
  25960. { //a=ice-options:google-ice
  25961. name: 'iceOptions',
  25962. reg: /^ice-options:(\S*)/,
  25963. format: "ice-options:%s"
  25964. },
  25965. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25966. push: "ssrcs",
  25967. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25968. names: ['id', 'attribute', 'value'],
  25969. format: "ssrc:%d %s:%s"
  25970. },
  25971. { //a=ssrc-group:FEC 1 2
  25972. push: "ssrcGroups",
  25973. reg: /^ssrc-group:(\w*) (.*)/,
  25974. names: ['semantics', 'ssrcs'],
  25975. format: "ssrc-group:%s %s"
  25976. },
  25977. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25978. name: "msidSemantic",
  25979. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25980. names: ['semantic', 'token'],
  25981. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25982. },
  25983. { //a=group:BUNDLE audio video
  25984. push: 'groups',
  25985. reg: /^group:(\w*) (.*)/,
  25986. names: ['type', 'mids'],
  25987. format: "group:%s %s"
  25988. },
  25989. { //a=rtcp-mux
  25990. name: 'rtcpMux',
  25991. reg: /^(rtcp-mux)/
  25992. },
  25993. { //a=rtcp-rsize
  25994. name: 'rtcpRsize',
  25995. reg: /^(rtcp-rsize)/
  25996. },
  25997. { // any a= that we don't understand is kepts verbatim on media.invalid
  25998. push: 'invalid',
  25999. names: ["value"]
  26000. }
  26001. ]
  26002. };
  26003. // set sensible defaults to avoid polluting the grammar with boring details
  26004. Object.keys(grammar).forEach(function (key) {
  26005. var objs = grammar[key];
  26006. objs.forEach(function (obj) {
  26007. if (!obj.reg) {
  26008. obj.reg = /(.*)/;
  26009. }
  26010. if (!obj.format) {
  26011. obj.format = "%s";
  26012. }
  26013. });
  26014. });
  26015. },{}],95:[function(require,module,exports){
  26016. var parser = require('./parser');
  26017. var writer = require('./writer');
  26018. exports.write = writer;
  26019. exports.parse = parser.parse;
  26020. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26021. exports.parsePayloads = parser.parsePayloads;
  26022. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26023. },{"./parser":96,"./writer":97}],96:[function(require,module,exports){
  26024. var toIntIfInt = function (v) {
  26025. return String(Number(v)) === v ? Number(v) : v;
  26026. };
  26027. var attachProperties = function (match, location, names, rawName) {
  26028. if (rawName && !names) {
  26029. location[rawName] = toIntIfInt(match[1]);
  26030. }
  26031. else {
  26032. for (var i = 0; i < names.length; i += 1) {
  26033. if (match[i+1] != null) {
  26034. location[names[i]] = toIntIfInt(match[i+1]);
  26035. }
  26036. }
  26037. }
  26038. };
  26039. var parseReg = function (obj, location, content) {
  26040. var needsBlank = obj.name && obj.names;
  26041. if (obj.push && !location[obj.push]) {
  26042. location[obj.push] = [];
  26043. }
  26044. else if (needsBlank && !location[obj.name]) {
  26045. location[obj.name] = {};
  26046. }
  26047. var keyLocation = obj.push ?
  26048. {} : // blank object that will be pushed
  26049. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26050. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26051. if (obj.push) {
  26052. location[obj.push].push(keyLocation);
  26053. }
  26054. };
  26055. var grammar = require('./grammar');
  26056. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26057. exports.parse = function (sdp) {
  26058. var session = {}
  26059. , media = []
  26060. , location = session; // points at where properties go under (one of the above)
  26061. // parse lines we understand
  26062. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26063. var type = l[0];
  26064. var content = l.slice(2);
  26065. if (type === 'm') {
  26066. media.push({rtp: [], fmtp: []});
  26067. location = media[media.length-1]; // point at latest media line
  26068. }
  26069. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26070. var obj = grammar[type][j];
  26071. if (obj.reg.test(content)) {
  26072. return parseReg(obj, location, content);
  26073. }
  26074. }
  26075. });
  26076. session.media = media; // link it up
  26077. return session;
  26078. };
  26079. var fmtpReducer = function (acc, expr) {
  26080. var s = expr.split('=');
  26081. if (s.length === 2) {
  26082. acc[s[0]] = toIntIfInt(s[1]);
  26083. }
  26084. return acc;
  26085. };
  26086. exports.parseFmtpConfig = function (str) {
  26087. return str.split(';').reduce(fmtpReducer, {});
  26088. };
  26089. exports.parsePayloads = function (str) {
  26090. return str.split(' ').map(Number);
  26091. };
  26092. exports.parseRemoteCandidates = function (str) {
  26093. var candidates = [];
  26094. var parts = str.split(' ').map(toIntIfInt);
  26095. for (var i = 0; i < parts.length; i += 3) {
  26096. candidates.push({
  26097. component: parts[i],
  26098. ip: parts[i + 1],
  26099. port: parts[i + 2]
  26100. });
  26101. }
  26102. return candidates;
  26103. };
  26104. },{"./grammar":94}],97:[function(require,module,exports){
  26105. var grammar = require('./grammar');
  26106. // customized util.format - discards excess arguments and can void middle ones
  26107. var formatRegExp = /%[sdv%]/g;
  26108. var format = function (formatStr) {
  26109. var i = 1;
  26110. var args = arguments;
  26111. var len = args.length;
  26112. return formatStr.replace(formatRegExp, function (x) {
  26113. if (i >= len) {
  26114. return x; // missing argument
  26115. }
  26116. var arg = args[i];
  26117. i += 1;
  26118. switch (x) {
  26119. case '%%':
  26120. return '%';
  26121. case '%s':
  26122. return String(arg);
  26123. case '%d':
  26124. return Number(arg);
  26125. case '%v':
  26126. return '';
  26127. }
  26128. });
  26129. // NB: we discard excess arguments - they are typically undefined from makeLine
  26130. };
  26131. var makeLine = function (type, obj, location) {
  26132. var str = obj.format instanceof Function ?
  26133. (obj.format(obj.push ? location : location[obj.name])) :
  26134. obj.format;
  26135. var args = [type + '=' + str];
  26136. if (obj.names) {
  26137. for (var i = 0; i < obj.names.length; i += 1) {
  26138. var n = obj.names[i];
  26139. if (obj.name) {
  26140. args.push(location[obj.name][n]);
  26141. }
  26142. else { // for mLine and push attributes
  26143. args.push(location[obj.names[i]]);
  26144. }
  26145. }
  26146. }
  26147. else {
  26148. args.push(location[obj.name]);
  26149. }
  26150. return format.apply(null, args);
  26151. };
  26152. // RFC specified order
  26153. // TODO: extend this with all the rest
  26154. var defaultOuterOrder = [
  26155. 'v', 'o', 's', 'i',
  26156. 'u', 'e', 'p', 'c',
  26157. 'b', 't', 'r', 'z', 'a'
  26158. ];
  26159. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26160. module.exports = function (session, opts) {
  26161. opts = opts || {};
  26162. // ensure certain properties exist
  26163. if (session.version == null) {
  26164. session.version = 0; // "v=0" must be there (only defined version atm)
  26165. }
  26166. if (session.name == null) {
  26167. session.name = " "; // "s= " must be there if no meaningful name set
  26168. }
  26169. session.media.forEach(function (mLine) {
  26170. if (mLine.payloads == null) {
  26171. mLine.payloads = "";
  26172. }
  26173. });
  26174. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26175. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26176. var sdp = [];
  26177. // loop through outerOrder for matching properties on session
  26178. outerOrder.forEach(function (type) {
  26179. grammar[type].forEach(function (obj) {
  26180. if (obj.name in session && session[obj.name] != null) {
  26181. sdp.push(makeLine(type, obj, session));
  26182. }
  26183. else if (obj.push in session && session[obj.push] != null) {
  26184. session[obj.push].forEach(function (el) {
  26185. sdp.push(makeLine(type, obj, el));
  26186. });
  26187. }
  26188. });
  26189. });
  26190. // then for each media line, follow the innerOrder
  26191. session.media.forEach(function (mLine) {
  26192. sdp.push(makeLine('m', grammar.m[0], mLine));
  26193. innerOrder.forEach(function (type) {
  26194. grammar[type].forEach(function (obj) {
  26195. if (obj.name in mLine && mLine[obj.name] != null) {
  26196. sdp.push(makeLine(type, obj, mLine));
  26197. }
  26198. else if (obj.push in mLine && mLine[obj.push] != null) {
  26199. mLine[obj.push].forEach(function (el) {
  26200. sdp.push(makeLine(type, obj, el));
  26201. });
  26202. }
  26203. });
  26204. });
  26205. });
  26206. return sdp.join('\r\n') + '\r\n';
  26207. };
  26208. },{"./grammar":94}],98:[function(require,module,exports){
  26209. var MediaStreamType = {
  26210. VIDEO_TYPE: "Video",
  26211. AUDIO_TYPE: "Audio"
  26212. };
  26213. module.exports = MediaStreamType;
  26214. },{}],99:[function(require,module,exports){
  26215. var RTCEvents = {
  26216. RTC_READY: "rtc.ready",
  26217. LASTN_CHANGED: "rtc.lastn_changed",
  26218. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26219. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26220. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26221. AUDIO_MUTE: "rtc.audio_mute",
  26222. VIDEO_MUTE: "rtc.video_mute"
  26223. };
  26224. module.exports = RTCEvents;
  26225. },{}],100:[function(require,module,exports){
  26226. var Resolutions = {
  26227. "1080": {
  26228. width: 1920,
  26229. height: 1080,
  26230. order: 7
  26231. },
  26232. "fullhd": {
  26233. width: 1920,
  26234. height: 1080,
  26235. order: 7
  26236. },
  26237. "720": {
  26238. width: 1280,
  26239. height: 720,
  26240. order: 6
  26241. },
  26242. "hd": {
  26243. width: 1280,
  26244. height: 720,
  26245. order: 6
  26246. },
  26247. "960": {
  26248. width: 960,
  26249. height: 720,
  26250. order: 5
  26251. },
  26252. "640": {
  26253. width: 640,
  26254. height: 480,
  26255. order: 4
  26256. },
  26257. "vga": {
  26258. width: 640,
  26259. height: 480,
  26260. order: 4
  26261. },
  26262. "360": {
  26263. width: 640,
  26264. height: 360,
  26265. order: 3
  26266. },
  26267. "320": {
  26268. width: 320,
  26269. height: 240,
  26270. order: 2
  26271. },
  26272. "180": {
  26273. width: 320,
  26274. height: 180,
  26275. order: 1
  26276. }
  26277. };
  26278. module.exports = Resolutions;
  26279. },{}],101:[function(require,module,exports){
  26280. var StreamEventTypes = {
  26281. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26282. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26283. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26284. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26285. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  26286. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  26287. };
  26288. module.exports = StreamEventTypes;
  26289. },{}],102:[function(require,module,exports){
  26290. var UIEvents = {
  26291. NICKNAME_CHANGED: "UI.nickname_changed",
  26292. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26293. PINNED_ENDPOINT: "UI.pinned_endpoint"
  26294. };
  26295. module.exports = UIEvents;
  26296. },{}],103:[function(require,module,exports){
  26297. var AuthenticationEvents = {
  26298. /**
  26299. * Event callback arguments:
  26300. * function(authenticationEnabled, userIdentity)
  26301. * authenticationEnabled - indicates whether authentication has been enabled
  26302. * in this session
  26303. * userIdentity - if user has been logged in then it contains user name. If
  26304. * contains 'null' or 'undefined' then user is not logged in.
  26305. */
  26306. IDENTITY_UPDATED: "authentication.identity_updated"
  26307. };
  26308. module.exports = AuthenticationEvents;
  26309. },{}],104:[function(require,module,exports){
  26310. var CQEvents = {
  26311. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26312. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26313. STOP: "cq.stop"
  26314. };
  26315. module.exports = CQEvents;
  26316. },{}],105:[function(require,module,exports){
  26317. var DesktopSharingEventTypes = {
  26318. INIT: "ds.init",
  26319. SWITCHING_DONE: "ds.switching_done",
  26320. NEW_STREAM_CREATED: "ds.new_stream_created"
  26321. };
  26322. module.exports = DesktopSharingEventTypes;
  26323. },{}],106:[function(require,module,exports){
  26324. var Events = {
  26325. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26326. };
  26327. module.exports = Events;
  26328. },{}],107:[function(require,module,exports){
  26329. module.exports = {
  26330. getLanguages : function () {
  26331. var languages = [];
  26332. for(var lang in this)
  26333. {
  26334. if(typeof this[lang] === "string")
  26335. languages.push(this[lang]);
  26336. }
  26337. return languages;
  26338. },
  26339. EN: "en",
  26340. BG: "bg",
  26341. DE: "de",
  26342. TR: "tr",
  26343. FR: "fr"
  26344. }
  26345. },{}],108:[function(require,module,exports){
  26346. var XMPPEvents = {
  26347. CONNECTION_FAILED: "xmpp.connection.failed",
  26348. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26349. CALL_INCOMING: "xmpp.callincoming.jingle",
  26350. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26351. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26352. KICKED: "xmpp.kicked",
  26353. BRIDGE_DOWN: "xmpp.bridge_down",
  26354. USER_ID_CHANGED: "xmpp.user_id_changed",
  26355. // We joined the MUC
  26356. MUC_JOINED: "xmpp.muc_joined",
  26357. // A member joined the MUC
  26358. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26359. // A member left the MUC
  26360. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26361. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26362. MUC_DESTROYED: "xmpp.muc_destroyed",
  26363. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26364. REMOTE_STATS: "xmpp.remote_stats",
  26365. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26366. PRESENCE_STATUS: "xmpp.presence_status",
  26367. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26368. SUBJECT_CHANGED: "xmpp.subject_changed",
  26369. MESSAGE_RECEIVED: "xmpp.message_received",
  26370. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26371. PASSWORD_REQUIRED: "xmpp.password_required",
  26372. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26373. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26374. ETHERPAD: "xmpp.etherpad",
  26375. DEVICE_AVAILABLE: "xmpp.device_available",
  26376. START_MUTED: "xmpp.start_muted",
  26377. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  26378. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  26379. AUDIO_MUTED: "xmpp.audio_muted",
  26380. VIDEO_MUTED: "xmpp.video_muted"
  26381. };
  26382. module.exports = XMPPEvents;
  26383. },{}],109:[function(require,module,exports){
  26384. // Copyright Joyent, Inc. and other Node contributors.
  26385. //
  26386. // Permission is hereby granted, free of charge, to any person obtaining a
  26387. // copy of this software and associated documentation files (the
  26388. // "Software"), to deal in the Software without restriction, including
  26389. // without limitation the rights to use, copy, modify, merge, publish,
  26390. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26391. // persons to whom the Software is furnished to do so, subject to the
  26392. // following conditions:
  26393. //
  26394. // The above copyright notice and this permission notice shall be included
  26395. // in all copies or substantial portions of the Software.
  26396. //
  26397. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26398. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26399. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26400. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26401. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26402. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26403. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26404. function EventEmitter() {
  26405. this._events = this._events || {};
  26406. this._maxListeners = this._maxListeners || undefined;
  26407. }
  26408. module.exports = EventEmitter;
  26409. // Backwards-compat with node 0.10.x
  26410. EventEmitter.EventEmitter = EventEmitter;
  26411. EventEmitter.prototype._events = undefined;
  26412. EventEmitter.prototype._maxListeners = undefined;
  26413. // By default EventEmitters will print a warning if more than 10 listeners are
  26414. // added to it. This is a useful default which helps finding memory leaks.
  26415. EventEmitter.defaultMaxListeners = 10;
  26416. // Obviously not all Emitters should be limited to 10. This function allows
  26417. // that to be increased. Set to zero for unlimited.
  26418. EventEmitter.prototype.setMaxListeners = function(n) {
  26419. if (!isNumber(n) || n < 0 || isNaN(n))
  26420. throw TypeError('n must be a positive number');
  26421. this._maxListeners = n;
  26422. return this;
  26423. };
  26424. EventEmitter.prototype.emit = function(type) {
  26425. var er, handler, len, args, i, listeners;
  26426. if (!this._events)
  26427. this._events = {};
  26428. // If there is no 'error' event listener then throw.
  26429. if (type === 'error') {
  26430. if (!this._events.error ||
  26431. (isObject(this._events.error) && !this._events.error.length)) {
  26432. er = arguments[1];
  26433. if (er instanceof Error) {
  26434. throw er; // Unhandled 'error' event
  26435. }
  26436. throw TypeError('Uncaught, unspecified "error" event.');
  26437. }
  26438. }
  26439. handler = this._events[type];
  26440. if (isUndefined(handler))
  26441. return false;
  26442. if (isFunction(handler)) {
  26443. switch (arguments.length) {
  26444. // fast cases
  26445. case 1:
  26446. handler.call(this);
  26447. break;
  26448. case 2:
  26449. handler.call(this, arguments[1]);
  26450. break;
  26451. case 3:
  26452. handler.call(this, arguments[1], arguments[2]);
  26453. break;
  26454. // slower
  26455. default:
  26456. len = arguments.length;
  26457. args = new Array(len - 1);
  26458. for (i = 1; i < len; i++)
  26459. args[i - 1] = arguments[i];
  26460. handler.apply(this, args);
  26461. }
  26462. } else if (isObject(handler)) {
  26463. len = arguments.length;
  26464. args = new Array(len - 1);
  26465. for (i = 1; i < len; i++)
  26466. args[i - 1] = arguments[i];
  26467. listeners = handler.slice();
  26468. len = listeners.length;
  26469. for (i = 0; i < len; i++)
  26470. listeners[i].apply(this, args);
  26471. }
  26472. return true;
  26473. };
  26474. EventEmitter.prototype.addListener = function(type, listener) {
  26475. var m;
  26476. if (!isFunction(listener))
  26477. throw TypeError('listener must be a function');
  26478. if (!this._events)
  26479. this._events = {};
  26480. // To avoid recursion in the case that type === "newListener"! Before
  26481. // adding it to the listeners, first emit "newListener".
  26482. if (this._events.newListener)
  26483. this.emit('newListener', type,
  26484. isFunction(listener.listener) ?
  26485. listener.listener : listener);
  26486. if (!this._events[type])
  26487. // Optimize the case of one listener. Don't need the extra array object.
  26488. this._events[type] = listener;
  26489. else if (isObject(this._events[type]))
  26490. // If we've already got an array, just append.
  26491. this._events[type].push(listener);
  26492. else
  26493. // Adding the second element, need to change to array.
  26494. this._events[type] = [this._events[type], listener];
  26495. // Check for listener leak
  26496. if (isObject(this._events[type]) && !this._events[type].warned) {
  26497. var m;
  26498. if (!isUndefined(this._maxListeners)) {
  26499. m = this._maxListeners;
  26500. } else {
  26501. m = EventEmitter.defaultMaxListeners;
  26502. }
  26503. if (m && m > 0 && this._events[type].length > m) {
  26504. this._events[type].warned = true;
  26505. console.error('(node) warning: possible EventEmitter memory ' +
  26506. 'leak detected. %d listeners added. ' +
  26507. 'Use emitter.setMaxListeners() to increase limit.',
  26508. this._events[type].length);
  26509. if (typeof console.trace === 'function') {
  26510. // not supported in IE 10
  26511. console.trace();
  26512. }
  26513. }
  26514. }
  26515. return this;
  26516. };
  26517. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  26518. EventEmitter.prototype.once = function(type, listener) {
  26519. if (!isFunction(listener))
  26520. throw TypeError('listener must be a function');
  26521. var fired = false;
  26522. function g() {
  26523. this.removeListener(type, g);
  26524. if (!fired) {
  26525. fired = true;
  26526. listener.apply(this, arguments);
  26527. }
  26528. }
  26529. g.listener = listener;
  26530. this.on(type, g);
  26531. return this;
  26532. };
  26533. // emits a 'removeListener' event iff the listener was removed
  26534. EventEmitter.prototype.removeListener = function(type, listener) {
  26535. var list, position, length, i;
  26536. if (!isFunction(listener))
  26537. throw TypeError('listener must be a function');
  26538. if (!this._events || !this._events[type])
  26539. return this;
  26540. list = this._events[type];
  26541. length = list.length;
  26542. position = -1;
  26543. if (list === listener ||
  26544. (isFunction(list.listener) && list.listener === listener)) {
  26545. delete this._events[type];
  26546. if (this._events.removeListener)
  26547. this.emit('removeListener', type, listener);
  26548. } else if (isObject(list)) {
  26549. for (i = length; i-- > 0;) {
  26550. if (list[i] === listener ||
  26551. (list[i].listener && list[i].listener === listener)) {
  26552. position = i;
  26553. break;
  26554. }
  26555. }
  26556. if (position < 0)
  26557. return this;
  26558. if (list.length === 1) {
  26559. list.length = 0;
  26560. delete this._events[type];
  26561. } else {
  26562. list.splice(position, 1);
  26563. }
  26564. if (this._events.removeListener)
  26565. this.emit('removeListener', type, listener);
  26566. }
  26567. return this;
  26568. };
  26569. EventEmitter.prototype.removeAllListeners = function(type) {
  26570. var key, listeners;
  26571. if (!this._events)
  26572. return this;
  26573. // not listening for removeListener, no need to emit
  26574. if (!this._events.removeListener) {
  26575. if (arguments.length === 0)
  26576. this._events = {};
  26577. else if (this._events[type])
  26578. delete this._events[type];
  26579. return this;
  26580. }
  26581. // emit removeListener for all listeners on all events
  26582. if (arguments.length === 0) {
  26583. for (key in this._events) {
  26584. if (key === 'removeListener') continue;
  26585. this.removeAllListeners(key);
  26586. }
  26587. this.removeAllListeners('removeListener');
  26588. this._events = {};
  26589. return this;
  26590. }
  26591. listeners = this._events[type];
  26592. if (isFunction(listeners)) {
  26593. this.removeListener(type, listeners);
  26594. } else {
  26595. // LIFO order
  26596. while (listeners.length)
  26597. this.removeListener(type, listeners[listeners.length - 1]);
  26598. }
  26599. delete this._events[type];
  26600. return this;
  26601. };
  26602. EventEmitter.prototype.listeners = function(type) {
  26603. var ret;
  26604. if (!this._events || !this._events[type])
  26605. ret = [];
  26606. else if (isFunction(this._events[type]))
  26607. ret = [this._events[type]];
  26608. else
  26609. ret = this._events[type].slice();
  26610. return ret;
  26611. };
  26612. EventEmitter.listenerCount = function(emitter, type) {
  26613. var ret;
  26614. if (!emitter._events || !emitter._events[type])
  26615. ret = 0;
  26616. else if (isFunction(emitter._events[type]))
  26617. ret = 1;
  26618. else
  26619. ret = emitter._events[type].length;
  26620. return ret;
  26621. };
  26622. function isFunction(arg) {
  26623. return typeof arg === 'function';
  26624. }
  26625. function isNumber(arg) {
  26626. return typeof arg === 'number';
  26627. }
  26628. function isObject(arg) {
  26629. return typeof arg === 'object' && arg !== null;
  26630. }
  26631. function isUndefined(arg) {
  26632. return arg === void 0;
  26633. }
  26634. },{}],110:[function(require,module,exports){
  26635. // shim for using process in browser
  26636. var process = module.exports = {};
  26637. var queue = [];
  26638. var draining = false;
  26639. function drainQueue() {
  26640. if (draining) {
  26641. return;
  26642. }
  26643. draining = true;
  26644. var currentQueue;
  26645. var len = queue.length;
  26646. while(len) {
  26647. currentQueue = queue;
  26648. queue = [];
  26649. var i = -1;
  26650. while (++i < len) {
  26651. currentQueue[i]();
  26652. }
  26653. len = queue.length;
  26654. }
  26655. draining = false;
  26656. }
  26657. process.nextTick = function (fun) {
  26658. queue.push(fun);
  26659. if (!draining) {
  26660. setTimeout(drainQueue, 0);
  26661. }
  26662. };
  26663. process.title = 'browser';
  26664. process.browser = true;
  26665. process.env = {};
  26666. process.argv = [];
  26667. process.version = ''; // empty string to avoid regexp issues
  26668. function noop() {}
  26669. process.on = noop;
  26670. process.addListener = noop;
  26671. process.once = noop;
  26672. process.off = noop;
  26673. process.removeListener = noop;
  26674. process.removeAllListeners = noop;
  26675. process.emit = noop;
  26676. process.binding = function (name) {
  26677. throw new Error('process.binding is not supported');
  26678. };
  26679. // TODO(shtylman)
  26680. process.cwd = function () { return '/' };
  26681. process.chdir = function (dir) {
  26682. throw new Error('process.chdir is not supported');
  26683. };
  26684. process.umask = function() { return 0; };
  26685. },{}]},{},[1])(1)
  26686. });