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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  13. this.xmpp = require("./modules/xmpp/xmpp");
  14. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  15. this.translation = require("./modules/translation/translation");
  16. this.settings = require("./modules/settings/Settings");
  17. this.DTMF = require("./modules/DTMF/DTMF");
  18. this.members = require("./modules/members/MemberList");
  19. }
  20. };
  21. function init() {
  22. APP.desktopsharing.init();
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. APP.keyboardshortcut.init();
  28. APP.members.start();
  29. }
  30. $(document).ready(function () {
  31. var URLPRocessor = require("./modules/URLProcessor/URLProcessor");
  32. URLPRocessor.setConfigParametersFromUrl();
  33. APP.init();
  34. APP.translation.init();
  35. if(APP.API.isEnabled())
  36. APP.API.init();
  37. APP.UI.start(init);
  38. });
  39. $(window).bind('beforeunload', function () {
  40. if(APP.API.isEnabled())
  41. APP.API.dispose();
  42. });
  43. module.exports = APP;
  44. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":11,"./modules/URLProcessor/URLProcessor":42,"./modules/connectionquality/connectionquality":43,"./modules/desktopsharing/desktopsharing":44,"./modules/keyboardshortcut/keyboardshortcut":45,"./modules/members/MemberList":46,"./modules/settings/Settings":47,"./modules/statistics/statistics":51,"./modules/translation/translation":52,"./modules/xmpp/xmpp":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. {
  62. displayName: APP.UI.inputDisplayNameHandler,
  63. muteAudio: APP.UI.toggleAudio,
  64. muteVideo: APP.UI.toggleVideo,
  65. toggleFilmStrip: APP.UI.toggleFilmStrip,
  66. toggleChat: APP.UI.toggleChat,
  67. toggleContactList: APP.UI.toggleContactList
  68. };
  69. /**
  70. * Maps the supported events and their status
  71. * (true it the event is enabled and false if it is disabled)
  72. * @type {{
  73. * incomingMessage: boolean,
  74. * outgoingMessage: boolean,
  75. * displayNameChange: boolean,
  76. * participantJoined: boolean,
  77. * participantLeft: boolean
  78. * }}
  79. */
  80. var events =
  81. {
  82. incomingMessage: false,
  83. outgoingMessage:false,
  84. displayNameChange: false,
  85. participantJoined: false,
  86. participantLeft: false
  87. };
  88. var displayName = {};
  89. /**
  90. * Processes commands from external applicaiton.
  91. * @param message the object with the command
  92. */
  93. function processCommand(message)
  94. {
  95. if(message.action != "execute")
  96. {
  97. console.error("Unknown action of the message");
  98. return;
  99. }
  100. for(var key in message)
  101. {
  102. if(commands[key])
  103. commands[key].apply(null, message[key]);
  104. }
  105. }
  106. /**
  107. * Processes events objects from external applications
  108. * @param event the event
  109. */
  110. function processEvent(event) {
  111. if(!event.action)
  112. {
  113. console.error("Event with no action is received.");
  114. return;
  115. }
  116. var i = 0;
  117. switch(event.action)
  118. {
  119. case "add":
  120. for(; i < event.events.length; i++)
  121. {
  122. events[event.events[i]] = true;
  123. }
  124. break;
  125. case "remove":
  126. for(; i < event.events.length; i++)
  127. {
  128. events[event.events[i]] = false;
  129. }
  130. break;
  131. default:
  132. console.error("Unknown action for event.");
  133. }
  134. }
  135. /**
  136. * Sends message to the external application.
  137. * @param object
  138. */
  139. function sendMessage(object) {
  140. window.parent.postMessage(JSON.stringify(object), "*");
  141. }
  142. /**
  143. * Processes a message event from the external application
  144. * @param event the message event
  145. */
  146. function processMessage(event)
  147. {
  148. var message;
  149. try {
  150. message = JSON.parse(event.data);
  151. } catch (e) {}
  152. if(!message.type)
  153. return;
  154. switch (message.type)
  155. {
  156. case "command":
  157. processCommand(message);
  158. break;
  159. case "event":
  160. processEvent(message);
  161. break;
  162. default:
  163. console.error("Unknown type of the message");
  164. return;
  165. }
  166. }
  167. function setupListeners() {
  168. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  169. API.triggerEvent("participantJoined", {jid: from});
  170. });
  171. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  172. if (from != myjid)
  173. API.triggerEvent("incomingMessage",
  174. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  175. });
  176. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  177. API.triggerEvent("participantLeft", {jid: jid});
  178. });
  179. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  180. name = displayName[jid];
  181. if(!name || name != newDisplayName) {
  182. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  183. displayName[jid] = newDisplayName;
  184. }
  185. });
  186. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  187. APP.API.triggerEvent("outgoingMessage", {"message": body});
  188. });
  189. }
  190. var API = {
  191. /**
  192. * Check whether the API should be enabled or not.
  193. * @returns {boolean}
  194. */
  195. isEnabled: function () {
  196. var hash = location.hash;
  197. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  198. return true;
  199. return false;
  200. },
  201. /**
  202. * Initializes the APIConnector. Setups message event listeners that will
  203. * receive information from external applications that embed Jitsi Meet.
  204. * It also sends a message to the external application that APIConnector
  205. * is initialized.
  206. */
  207. init: function () {
  208. if (window.addEventListener)
  209. {
  210. window.addEventListener('message',
  211. processMessage, false);
  212. }
  213. else
  214. {
  215. window.attachEvent('onmessage', processMessage);
  216. }
  217. sendMessage({type: "system", loaded: true});
  218. setupListeners();
  219. },
  220. /**
  221. * Checks whether the event is enabled ot not.
  222. * @param name the name of the event.
  223. * @returns {*}
  224. */
  225. isEventEnabled: function (name) {
  226. return events[name];
  227. },
  228. /**
  229. * Sends event object to the external application that has been subscribed
  230. * for that event.
  231. * @param name the name event
  232. * @param object data associated with the event
  233. */
  234. triggerEvent: function (name, object) {
  235. if(this.isEnabled() && this.isEventEnabled(name))
  236. sendMessage({
  237. type: "event", action: "result", event: name, result: object});
  238. },
  239. /**
  240. * Removes the listeners.
  241. */
  242. dispose: function () {
  243. if(window.removeEventListener)
  244. {
  245. window.removeEventListener("message",
  246. processMessage, false);
  247. }
  248. else
  249. {
  250. window.detachEvent('onmessage', processMessage);
  251. }
  252. }
  253. };
  254. module.exports = API;
  255. },{"../../service/xmpp/XMPPEvents":112}],3:[function(require,module,exports){
  256. /* global APP */
  257. /**
  258. * A module for sending DTMF tones.
  259. */
  260. var DTMFSender;
  261. var initDtmfSender = function() {
  262. // TODO: This needs to reset this if the peerconnection changes
  263. // (e.g. the call is re-made)
  264. if (DTMFSender)
  265. return;
  266. var localAudio = APP.RTC.localAudio;
  267. if (localAudio && localAudio.getTracks().length > 0)
  268. {
  269. var peerconnection
  270. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  271. if (peerconnection) {
  272. DTMFSender =
  273. peerconnection.peerconnection
  274. .createDTMFSender(localAudio.getTracks()[0]);
  275. console.log("Initialized DTMFSender");
  276. }
  277. else {
  278. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  279. }
  280. }
  281. else {
  282. console.log("Failed to initialize DTMFSender: no audio track.");
  283. }
  284. };
  285. var DTMF = {
  286. sendTones: function (tones, duration, pause) {
  287. if (!DTMFSender)
  288. initDtmfSender();
  289. if (DTMFSender){
  290. DTMFSender.insertDTMF(tones,
  291. (duration || 200),
  292. (pause || 200));
  293. }
  294. }
  295. };
  296. module.exports = DTMF;
  297. },{}],4:[function(require,module,exports){
  298. /* global Strophe, focusedVideoSrc*/
  299. // cache datachannels to avoid garbage collection
  300. // https://code.google.com/p/chromium/issues/detail?id=405545
  301. var RTCEvents = require("../../service/RTC/RTCEvents");
  302. var _dataChannels = [];
  303. var eventEmitter = null;
  304. var DataChannels =
  305. {
  306. /**
  307. * Callback triggered by PeerConnection when new data channel is opened
  308. * on the bridge.
  309. * @param event the event info object.
  310. */
  311. onDataChannel: function (event)
  312. {
  313. var dataChannel = event.channel;
  314. dataChannel.onopen = function () {
  315. console.info("Data channel opened by the Videobridge!", dataChannel);
  316. // Code sample for sending string and/or binary data
  317. // Sends String message to the bridge
  318. //dataChannel.send("Hello bridge!");
  319. // Sends 12 bytes binary message to the bridge
  320. //dataChannel.send(new ArrayBuffer(12));
  321. // when the data channel becomes available, tell the bridge about video
  322. // selections so that it can do adaptive simulcast,
  323. // we want the notification to trigger even if userJid is undefined,
  324. // or null.
  325. var userJid = APP.UI.getLargeVideoJid();
  326. // we want the notification to trigger even if userJid is undefined,
  327. // or null.
  328. onSelectedEndpointChanged(userJid);
  329. };
  330. dataChannel.onerror = function (error) {
  331. console.error("Data Channel Error:", error, dataChannel);
  332. };
  333. dataChannel.onmessage = function (event) {
  334. var data = event.data;
  335. // JSON
  336. var obj;
  337. try {
  338. obj = JSON.parse(data);
  339. }
  340. catch (e) {
  341. console.error(
  342. "Failed to parse data channel message as JSON: ",
  343. data,
  344. dataChannel);
  345. }
  346. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  347. var colibriClass = obj.colibriClass;
  348. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  349. // Endpoint ID from the Videobridge.
  350. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  351. console.info(
  352. "Data channel new dominant speaker event: ",
  353. dominantSpeakerEndpoint);
  354. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  355. }
  356. else if ("InLastNChangeEvent" === colibriClass)
  357. {
  358. var oldValue = obj.oldValue;
  359. var newValue = obj.newValue;
  360. // Make sure that oldValue and newValue are of type boolean.
  361. var type;
  362. if ((type = typeof oldValue) !== 'boolean') {
  363. if (type === 'string') {
  364. oldValue = (oldValue == "true");
  365. } else {
  366. oldValue = new Boolean(oldValue).valueOf();
  367. }
  368. }
  369. if ((type = typeof newValue) !== 'boolean') {
  370. if (type === 'string') {
  371. newValue = (newValue == "true");
  372. } else {
  373. newValue = new Boolean(newValue).valueOf();
  374. }
  375. }
  376. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  377. }
  378. else if ("LastNEndpointsChangeEvent" === colibriClass)
  379. {
  380. // The new/latest list of last-n endpoint IDs.
  381. var lastNEndpoints = obj.lastNEndpoints;
  382. // The list of endpoint IDs which are entering the list of
  383. // last-n at this time i.e. were not in the old list of last-n
  384. // endpoint IDs.
  385. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  386. var stream = obj.stream;
  387. console.log(
  388. "Data channel new last-n event: ",
  389. lastNEndpoints, endpointsEnteringLastN, obj);
  390. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  391. lastNEndpoints, endpointsEnteringLastN, obj);
  392. }
  393. else
  394. {
  395. console.debug("Data channel JSON-formatted message: ", obj);
  396. }
  397. }
  398. };
  399. dataChannel.onclose = function ()
  400. {
  401. console.info("The Data Channel closed", dataChannel);
  402. var idx = _dataChannels.indexOf(dataChannel);
  403. if (idx > -1)
  404. _dataChannels = _dataChannels.splice(idx, 1);
  405. };
  406. _dataChannels.push(dataChannel);
  407. },
  408. /**
  409. * Binds "ondatachannel" event listener to given PeerConnection instance.
  410. * @param peerConnection WebRTC peer connection instance.
  411. */
  412. init: function (peerConnection, emitter) {
  413. if(!config.openSctp)
  414. return;
  415. peerConnection.ondatachannel = this.onDataChannel;
  416. eventEmitter = emitter;
  417. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  418. // Although it's not a requirement to open separate channels from both bridge
  419. // and peer as single channel can be used for sending and receiving data.
  420. // So either channel opened by the bridge or the one opened here is enough
  421. // for communication with the bridge.
  422. /*var dataChannelOptions =
  423. {
  424. reliable: true
  425. };
  426. var dataChannel
  427. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  428. // Can be used only when is in open state
  429. dataChannel.onopen = function ()
  430. {
  431. dataChannel.send("My channel !!!");
  432. };
  433. dataChannel.onmessage = function (event)
  434. {
  435. var msgData = event.data;
  436. console.info("Got My Data Channel Message:", msgData, dataChannel);
  437. };*/
  438. },
  439. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  440. handlePinnedEndpointEvent: onPinnedEndpointChanged
  441. };
  442. function onSelectedEndpointChanged(userResource)
  443. {
  444. console.log('selected endpoint changed: ', userResource);
  445. if (_dataChannels && _dataChannels.length != 0)
  446. {
  447. _dataChannels.some(function (dataChannel) {
  448. if (dataChannel.readyState == 'open')
  449. {
  450. console.log('sending selected endpoint changed '
  451. + 'notification to the bridge: ', userResource);
  452. dataChannel.send(JSON.stringify({
  453. 'colibriClass': 'SelectedEndpointChangedEvent',
  454. 'selectedEndpoint':
  455. (!userResource || userResource === null)?
  456. null : userResource
  457. }));
  458. return true;
  459. }
  460. });
  461. }
  462. }
  463. function onPinnedEndpointChanged(userResource)
  464. {
  465. console.log('pinned endpoint changed: ', userResource);
  466. if (_dataChannels && _dataChannels.length != 0)
  467. {
  468. _dataChannels.some(function (dataChannel) {
  469. if (dataChannel.readyState == 'open')
  470. {
  471. dataChannel.send(JSON.stringify({
  472. 'colibriClass': 'PinnedEndpointChangedEvent',
  473. 'pinnedEndpoint':
  474. (!userResource || userResource == null)?
  475. null : userResource
  476. }));
  477. return true;
  478. }
  479. });
  480. }
  481. }
  482. module.exports = DataChannels;
  483. },{"../../service/RTC/RTCEvents":103}],5:[function(require,module,exports){
  484. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  485. var RTCEvents = require("../../service/RTC/RTCEvents");
  486. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  487. {
  488. this.stream = stream;
  489. this.eventEmitter = eventEmitter;
  490. this.type = type;
  491. this.videoType = videoType;
  492. this.isGUMStream = true;
  493. if(isGUMStream === false)
  494. this.isGUMStream = isGUMStream;
  495. var self = this;
  496. if(type == "audio")
  497. {
  498. this.getTracks = function () {
  499. return self.stream.getAudioTracks();
  500. };
  501. }
  502. else
  503. {
  504. this.getTracks = function () {
  505. return self.stream.getVideoTracks();
  506. };
  507. }
  508. this.stream.onended = function()
  509. {
  510. self.streamEnded();
  511. };
  512. }
  513. LocalStream.prototype.streamEnded = function () {
  514. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  515. }
  516. LocalStream.prototype.getOriginalStream = function()
  517. {
  518. return this.stream;
  519. }
  520. LocalStream.prototype.isAudioStream = function () {
  521. return this.type === "audio";
  522. };
  523. LocalStream.prototype.setMute = function(mute)
  524. {
  525. if((window.location.protocol != "https:" && this.isGUMStream) ||
  526. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  527. {
  528. var tracks = this.getTracks();
  529. for (var idx = 0; idx < tracks.length; idx++) {
  530. tracks[idx].enabled = mute;
  531. }
  532. this.eventEmitter.emit(
  533. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  534. !mute);
  535. }
  536. else
  537. {
  538. if(mute === false) {
  539. APP.xmpp.removeStream(this.stream);
  540. this.stream.stop();
  541. this.eventEmitter.emit(
  542. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  543. true);
  544. }
  545. else
  546. {
  547. var self = this;
  548. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  549. (this.isAudioStream() ? ["audio"] : ["video"]),
  550. function (stream) {
  551. if(self.isAudioStream())
  552. {
  553. APP.RTC.changeLocalAudio(stream,
  554. function () {
  555. self.eventEmitter.emit(
  556. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  557. true);
  558. });
  559. }
  560. else
  561. {
  562. APP.RTC.changeLocalVideo(stream, false,
  563. function () {
  564. self.eventEmitter.emit(
  565. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  566. true);
  567. });
  568. }
  569. });
  570. }
  571. }
  572. };
  573. LocalStream.prototype.isMuted = function () {
  574. var tracks = [];
  575. if(this.type == "audio")
  576. {
  577. tracks = this.stream.getAudioTracks();
  578. }
  579. else
  580. {
  581. if(this.stream.ended)
  582. return true;
  583. tracks = this.stream.getVideoTracks();
  584. }
  585. for (var idx = 0; idx < tracks.length; idx++) {
  586. if(tracks[idx].enabled)
  587. return false;
  588. }
  589. return true;
  590. }
  591. LocalStream.prototype.getId = function () {
  592. return this.stream.getTracks()[0].id;
  593. }
  594. module.exports = LocalStream;
  595. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes.js":105}],6:[function(require,module,exports){
  596. ////These lines should be uncommented when require works in app.js
  597. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  598. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  599. /**
  600. * Creates a MediaStream object for the given data, session id and ssrc.
  601. * It is a wrapper class for the MediaStream.
  602. *
  603. * @param data the data object from which we obtain the stream,
  604. * the peerjid, etc.
  605. * @param sid the session id
  606. * @param ssrc the ssrc corresponding to this MediaStream
  607. *
  608. * @constructor
  609. */
  610. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  611. // XXX(gp) to minimize headaches in the future, we should build our
  612. // abstractions around tracks and not streams. ORTC is track based API.
  613. // Mozilla expects m-lines to represent media tracks.
  614. //
  615. // Practically, what I'm saying is that we should have a MediaTrack class
  616. // and not a MediaStream class.
  617. //
  618. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  619. // a track might have an associated RTX and FEC sources.
  620. this.sid = sid;
  621. this.stream = data.stream;
  622. this.peerjid = data.peerjid;
  623. this.videoType = data.videoType;
  624. this.ssrc = ssrc;
  625. this.type = (this.stream.getVideoTracks().length > 0)?
  626. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  627. this.muted = false;
  628. this.eventEmitter = eventEmitter;
  629. }
  630. MediaStream.prototype.getOriginalStream = function()
  631. {
  632. return this.stream;
  633. };
  634. MediaStream.prototype.setMute = function (value)
  635. {
  636. this.stream.muted = value;
  637. this.muted = value;
  638. };
  639. module.exports = MediaStream;
  640. },{"../../service/RTC/MediaStreamTypes":102,"../../service/RTC/StreamEventTypes":105}],7:[function(require,module,exports){
  641. var EventEmitter = require("events");
  642. var RTCBrowserType = require("./RTCBrowserType");
  643. var RTCUtils = require("./RTCUtils.js");
  644. var LocalStream = require("./LocalStream.js");
  645. var DataChannels = require("./DataChannels");
  646. var MediaStream = require("./MediaStream.js");
  647. var DesktopSharingEventTypes
  648. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  649. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  650. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  651. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  652. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  653. var UIEvents = require("../../service/UI/UIEvents");
  654. var eventEmitter = new EventEmitter();
  655. function getMediaStreamUsage()
  656. {
  657. var result = {
  658. audio: true,
  659. video: true
  660. };
  661. /** There are some issues with the desktop sharing
  662. * when this property is enabled.
  663. * WARNING: We must change the implementation to start video/audio if we
  664. * receive from the focus that the peer is not muted.
  665. var isSecureConnection = window.location.protocol == "https:";
  666. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  667. {
  668. result = {
  669. audio: false,
  670. video: false
  671. };
  672. }
  673. **/
  674. return result;
  675. }
  676. var RTC = {
  677. rtcUtils: null,
  678. devices: {
  679. audio: true,
  680. video: true
  681. },
  682. localStreams: [],
  683. remoteStreams: {},
  684. localAudio: null,
  685. localVideo: null,
  686. addStreamListener: function (listener, eventType) {
  687. eventEmitter.on(eventType, listener);
  688. },
  689. addListener: function (type, listener) {
  690. eventEmitter.on(type, listener);
  691. },
  692. removeStreamListener: function (listener, eventType) {
  693. if(!(eventType instanceof StreamEventTypes))
  694. throw "Illegal argument";
  695. eventEmitter.removeListener(eventType, listener);
  696. },
  697. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  698. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  699. //in firefox we have only one stream object
  700. if(this.localStreams.length == 0 ||
  701. this.localStreams[0].getOriginalStream() != stream)
  702. this.localStreams.push(localStream);
  703. if(isMuted === true)
  704. localStream.setMute(false);
  705. if(type == "audio")
  706. {
  707. this.localAudio = localStream;
  708. }
  709. else
  710. {
  711. this.localVideo = localStream;
  712. }
  713. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  714. if(change)
  715. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  716. eventEmitter.emit(eventType, localStream, isMuted);
  717. return localStream;
  718. },
  719. removeLocalStream: function (stream) {
  720. for(var i = 0; i < this.localStreams.length; i++)
  721. {
  722. if(this.localStreams[i].getOriginalStream() === stream) {
  723. delete this.localStreams[i];
  724. return;
  725. }
  726. }
  727. },
  728. createRemoteStream: function (data, sid, thessrc) {
  729. var remoteStream = new MediaStream(data, sid, thessrc,
  730. RTCBrowserType.getBrowserType(), eventEmitter);
  731. var jid = data.peerjid || APP.xmpp.myJid();
  732. if(!this.remoteStreams[jid]) {
  733. this.remoteStreams[jid] = {};
  734. }
  735. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  736. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  737. return remoteStream;
  738. },
  739. getPCConstraints: function () {
  740. return this.rtcUtils.pc_constraints;
  741. },
  742. getUserMediaWithConstraints:function(um, success_callback,
  743. failure_callback, resolution,
  744. bandwidth, fps, desktopStream)
  745. {
  746. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  747. failure_callback, resolution, bandwidth, fps, desktopStream);
  748. },
  749. attachMediaStream: function (elSelector, stream) {
  750. this.rtcUtils.attachMediaStream(elSelector, stream);
  751. },
  752. getStreamID: function (stream) {
  753. return this.rtcUtils.getStreamID(stream);
  754. },
  755. getVideoSrc: function (element) {
  756. return this.rtcUtils.getVideoSrc(element);
  757. },
  758. setVideoSrc: function (element, src) {
  759. this.rtcUtils.setVideoSrc(element, src);
  760. },
  761. getVideoElementName: function () {
  762. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  763. },
  764. dispose: function() {
  765. if (this.rtcUtils) {
  766. this.rtcUtils = null;
  767. }
  768. },
  769. stop: function () {
  770. this.dispose();
  771. },
  772. start: function () {
  773. var self = this;
  774. APP.desktopsharing.addListener(
  775. function (stream, isUsingScreenStream, callback) {
  776. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  777. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  778. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  779. DataChannels.init(event.peerconnection, eventEmitter);
  780. });
  781. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  782. DataChannels.handleSelectedEndpointEvent);
  783. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  784. DataChannels.handlePinnedEndpointEvent);
  785. // In case of IE we continue from 'onReady' callback
  786. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  787. // once it is initialized.
  788. var onReady = function () {
  789. eventEmitter.emit(RTCEvents.RTC_READY, true);
  790. self.rtcUtils.obtainAudioAndVideoPermissions(
  791. null, null, getMediaStreamUsage());
  792. };
  793. this.rtcUtils = new RTCUtils(this, onReady);
  794. // Call onReady() if Temasys plugin is not used
  795. if (!RTCBrowserType.isTemasysPluginUsed()) {
  796. onReady();
  797. }
  798. },
  799. muteRemoteVideoStream: function (jid, value) {
  800. var stream;
  801. if(this.remoteStreams[jid] &&
  802. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  803. {
  804. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  805. }
  806. if(!stream)
  807. return true;
  808. if (value != stream.muted) {
  809. stream.setMute(value);
  810. return true;
  811. }
  812. return false;
  813. },
  814. switchVideoStreams: function (new_stream) {
  815. this.localVideo.stream = new_stream;
  816. this.localStreams = [];
  817. //in firefox we have only one stream object
  818. if (this.localAudio.getOriginalStream() != new_stream)
  819. this.localStreams.push(this.localAudio);
  820. this.localStreams.push(this.localVideo);
  821. },
  822. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  823. var oldStream = this.localVideo.getOriginalStream();
  824. var type = (isUsingScreenStream? "screen" : "video");
  825. var localCallback = callback;
  826. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  827. {
  828. localCallback = function() {
  829. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  830. callback();
  831. };
  832. }
  833. // FIXME: Workaround for FF/IE/Safari
  834. if (stream && stream.videoStream) {
  835. stream = stream.videoStream;
  836. }
  837. var videoStream = this.rtcUtils.createStream(stream, true);
  838. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  839. // Stop the stream to trigger onended event for old stream
  840. oldStream.stop();
  841. this.switchVideoStreams(videoStream, oldStream);
  842. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  843. },
  844. changeLocalAudio: function (stream, callback) {
  845. var oldStream = this.localAudio.getOriginalStream();
  846. var newStream = this.rtcUtils.createStream(stream);
  847. this.localAudio = this.createLocalStream(newStream, "audio", true);
  848. // Stop the stream to trigger onended event for old stream
  849. oldStream.stop();
  850. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  851. },
  852. isVideoMuted: function (jid) {
  853. if (jid === APP.xmpp.myJid()) {
  854. var localVideo = APP.RTC.localVideo;
  855. return (!localVideo || localVideo.isMuted());
  856. }
  857. else
  858. {
  859. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  860. return null;
  861. }
  862. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  863. }
  864. },
  865. /**
  866. * Checks if video identified by given src is desktop stream.
  867. * @param videoSrc eg.
  868. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  869. * @returns {boolean}
  870. */
  871. isVideoSrcDesktop: function (jid) {
  872. if(!jid)
  873. return false;
  874. var isDesktop = false;
  875. var stream = null;
  876. if (APP.xmpp.myJid() === jid) {
  877. // local video
  878. stream = this.localVideo;
  879. } else {
  880. var peerStreams = this.remoteStreams[jid];
  881. if(!peerStreams)
  882. return false;
  883. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  884. }
  885. if(stream)
  886. isDesktop = (stream.videoType === "screen");
  887. return isDesktop;
  888. },
  889. setVideoMute: function(mute, callback, options) {
  890. if(!this.localVideo)
  891. return;
  892. if (mute == APP.RTC.localVideo.isMuted())
  893. {
  894. APP.xmpp.sendVideoInfoPresence(mute);
  895. if(callback)
  896. callback(mute);
  897. }
  898. else
  899. {
  900. APP.RTC.localVideo.setMute(!mute);
  901. APP.xmpp.setVideoMute(
  902. mute,
  903. callback,
  904. options);
  905. }
  906. },
  907. setDeviceAvailability: function (devices) {
  908. if(!devices)
  909. return;
  910. if(devices.audio === true || devices.audio === false)
  911. this.devices.audio = devices.audio;
  912. if(devices.video === true || devices.video === false)
  913. this.devices.video = devices.video;
  914. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  915. }
  916. };
  917. module.exports = RTC;
  918. },{"../../service/RTC/MediaStreamTypes":102,"../../service/RTC/RTCEvents.js":103,"../../service/RTC/StreamEventTypes.js":105,"../../service/UI/UIEvents":106,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../../service/xmpp/XMPPEvents":112,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":113}],8:[function(require,module,exports){
  919. var currentBrowser;
  920. var browserVersion;
  921. var RTCBrowserType = {
  922. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  923. RTC_BROWSER_OPERA: "rtc_browser.opera",
  924. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  925. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  926. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  927. getBrowserType: function () {
  928. return currentBrowser;
  929. },
  930. isChrome: function () {
  931. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  932. },
  933. isOpera: function () {
  934. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  935. },
  936. isFirefox: function () {
  937. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  938. },
  939. isIExplorer: function () {
  940. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  941. },
  942. isSafari: function () {
  943. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  944. },
  945. isTemasysPluginUsed: function () {
  946. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  947. },
  948. getFirefoxVersion: function () {
  949. return RTCBrowserType.isFirefox() ? browserVersion : null;
  950. },
  951. getChromeVersion: function () {
  952. return RTCBrowserType.isChrome() ? browserVersion : null;
  953. }
  954. // Add version getters for other browsers when needed
  955. };
  956. // detectOpera() must be called before detectChrome() !!!
  957. // otherwise Opera wil be detected as Chrome
  958. function detectChrome() {
  959. if (navigator.webkitGetUserMedia) {
  960. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  961. var userAgent = navigator.userAgent.toLowerCase();
  962. // We can assume that user agent is chrome, because it's
  963. // enforced when 'ext' streaming method is set
  964. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  965. console.log("This appears to be Chrome, ver: " + ver);
  966. return ver;
  967. }
  968. return null;
  969. }
  970. function detectOpera() {
  971. var userAgent = navigator.userAgent;
  972. if (userAgent.match(/Opera|OPR/)) {
  973. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  974. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  975. console.info("This appears to be Opera, ver: " + version);
  976. return version;
  977. }
  978. return null;
  979. }
  980. function detectFirefox() {
  981. if (navigator.mozGetUserMedia) {
  982. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  983. var version = parseInt(
  984. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  985. console.log('This appears to be Firefox, ver: ' + version);
  986. return version;
  987. }
  988. return null;
  989. }
  990. function detectSafari() {
  991. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  992. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  993. console.info("This appears to be Safari");
  994. // FIXME detect Safari version when needed
  995. return 1;
  996. }
  997. return null;
  998. }
  999. function detectIE() {
  1000. var version;
  1001. var ua = window.navigator.userAgent;
  1002. var msie = ua.indexOf('MSIE ');
  1003. if (msie > 0) {
  1004. // IE 10 or older => return version number
  1005. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1006. }
  1007. var trident = ua.indexOf('Trident/');
  1008. if (!version && trident > 0) {
  1009. // IE 11 => return version number
  1010. var rv = ua.indexOf('rv:');
  1011. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1012. }
  1013. var edge = ua.indexOf('Edge/');
  1014. if (!version && edge > 0) {
  1015. // IE 12 => return version number
  1016. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1017. }
  1018. if (version) {
  1019. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1020. console.info("This appears to be IExplorer, ver: " + version);
  1021. }
  1022. return version;
  1023. }
  1024. function detectBrowser() {
  1025. var version;
  1026. var detectors = [
  1027. detectOpera,
  1028. detectChrome,
  1029. detectFirefox,
  1030. detectIE,
  1031. detectSafari
  1032. ];
  1033. // Try all browser detectors
  1034. for (var i = 0; i < detectors.length; i++) {
  1035. version = detectors[i]();
  1036. if (version)
  1037. return version;
  1038. }
  1039. console.error("Failed to detect browser type");
  1040. return undefined;
  1041. }
  1042. browserVersion = detectBrowser();
  1043. module.exports = RTCBrowserType;
  1044. },{}],9:[function(require,module,exports){
  1045. var RTCBrowserType = require("./RTCBrowserType");
  1046. var Resolutions = require("../../service/RTC/Resolutions");
  1047. var AdapterJS = require("./adapter.screenshare");
  1048. var SDPUtil = require("../xmpp/SDPUtil");
  1049. var currentResolution = null;
  1050. function getPreviousResolution(resolution) {
  1051. if(!Resolutions[resolution])
  1052. return null;
  1053. var order = Resolutions[resolution].order;
  1054. var res = null;
  1055. var resName = null;
  1056. for(var i in Resolutions)
  1057. {
  1058. var tmp = Resolutions[i];
  1059. if(res == null || (res.order < tmp.order && tmp.order < order))
  1060. {
  1061. resName = i;
  1062. res = tmp;
  1063. }
  1064. }
  1065. return resName;
  1066. }
  1067. function setResolutionConstraints(constraints, resolution, isAndroid)
  1068. {
  1069. if (resolution && !constraints.video || isAndroid) {
  1070. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1071. }
  1072. if(Resolutions[resolution])
  1073. {
  1074. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1075. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1076. }
  1077. else
  1078. {
  1079. if (isAndroid) {
  1080. constraints.video.mandatory.minWidth = 320;
  1081. constraints.video.mandatory.minHeight = 240;
  1082. constraints.video.mandatory.maxFrameRate = 15;
  1083. }
  1084. }
  1085. if (constraints.video.mandatory.minWidth)
  1086. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1087. if (constraints.video.mandatory.minHeight)
  1088. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1089. }
  1090. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1091. {
  1092. var constraints = {audio: false, video: false};
  1093. if (um.indexOf('video') >= 0) {
  1094. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1095. }
  1096. if (um.indexOf('audio') >= 0) {
  1097. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1098. }
  1099. if (um.indexOf('screen') >= 0) {
  1100. if (RTCBrowserType.isChrome()) {
  1101. constraints.video = {
  1102. mandatory: {
  1103. chromeMediaSource: "screen",
  1104. googLeakyBucket: true,
  1105. maxWidth: window.screen.width,
  1106. maxHeight: window.screen.height,
  1107. maxFrameRate: 3
  1108. },
  1109. optional: []
  1110. };
  1111. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1112. constraints.video = {
  1113. optional: [
  1114. {
  1115. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1116. }
  1117. ]
  1118. };
  1119. } else {
  1120. console.error(
  1121. "'screen' WebRTC media source is supported only in Chrome" +
  1122. " and with Temasys plugin");
  1123. }
  1124. }
  1125. if (um.indexOf('desktop') >= 0) {
  1126. constraints.video = {
  1127. mandatory: {
  1128. chromeMediaSource: "desktop",
  1129. chromeMediaSourceId: desktopStream,
  1130. googLeakyBucket: true,
  1131. maxWidth: window.screen.width,
  1132. maxHeight: window.screen.height,
  1133. maxFrameRate: 3
  1134. },
  1135. optional: []
  1136. };
  1137. }
  1138. if (constraints.audio) {
  1139. // if it is good enough for hangouts...
  1140. constraints.audio.optional.push(
  1141. {googEchoCancellation: true},
  1142. {googAutoGainControl: true},
  1143. {googNoiseSupression: true},
  1144. {googHighpassFilter: true},
  1145. {googNoisesuppression2: true},
  1146. {googEchoCancellation2: true},
  1147. {googAutoGainControl2: true}
  1148. );
  1149. }
  1150. if (constraints.video) {
  1151. constraints.video.optional.push(
  1152. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1153. );
  1154. if (um.indexOf('video') >= 0) {
  1155. constraints.video.optional.push(
  1156. {googLeakyBucket: true}
  1157. );
  1158. }
  1159. }
  1160. if (um.indexOf('video') >= 0) {
  1161. setResolutionConstraints(constraints, resolution, isAndroid);
  1162. }
  1163. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1164. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1165. constraints.video.optional.push({bandwidth: bandwidth});
  1166. }
  1167. if (fps) { // for some cameras it might be necessary to request 30fps
  1168. // so they choose 30fps mjpg over 10fps yuy2
  1169. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1170. constraints.video.mandatory.minFrameRate = fps;
  1171. }
  1172. return constraints;
  1173. }
  1174. function RTCUtils(RTCService, onTemasysPluginReady)
  1175. {
  1176. var self = this;
  1177. this.service = RTCService;
  1178. if (RTCBrowserType.isFirefox()) {
  1179. var FFversion = RTCBrowserType.getFirefoxVersion();
  1180. if (FFversion >= 40 && config.useBundle && config.useRtcpMux) {
  1181. this.peerconnection = mozRTCPeerConnection;
  1182. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1183. this.pc_constraints = {};
  1184. this.attachMediaStream = function (element, stream) {
  1185. // srcObject is being standardized and FF will eventually
  1186. // support that unprefixed. FF also supports the
  1187. // "element.src = URL.createObjectURL(...)" combo, but that
  1188. // will be deprecated in favour of srcObject.
  1189. //
  1190. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1191. // https://github.com/webrtc/samples/issues/302
  1192. if(!element[0])
  1193. return;
  1194. element[0].mozSrcObject = stream;
  1195. element[0].play();
  1196. };
  1197. this.getStreamID = function (stream) {
  1198. var tracks = stream.getVideoTracks();
  1199. if(!tracks || tracks.length == 0)
  1200. {
  1201. tracks = stream.getAudioTracks();
  1202. }
  1203. return SDPUtil.filter_special_chars(tracks[0].id);
  1204. };
  1205. this.getVideoSrc = function (element) {
  1206. if(!element)
  1207. return null;
  1208. return element.mozSrcObject;
  1209. };
  1210. this.setVideoSrc = function (element, src) {
  1211. if(element)
  1212. element.mozSrcObject = src;
  1213. };
  1214. RTCSessionDescription = mozRTCSessionDescription;
  1215. RTCIceCandidate = mozRTCIceCandidate;
  1216. } else {
  1217. console.error(
  1218. "Firefox requirements not met, ver: " + FFversion +
  1219. ", bundle: " + config.useBundle +
  1220. ", rtcp-mux: " + config.useRtcpMux);
  1221. window.location.href = 'unsupported_browser.html';
  1222. return;
  1223. }
  1224. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1225. this.peerconnection = webkitRTCPeerConnection;
  1226. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1227. this.attachMediaStream = function (element, stream) {
  1228. element.attr('src', webkitURL.createObjectURL(stream));
  1229. };
  1230. this.getStreamID = function (stream) {
  1231. // streams from FF endpoints have the characters '{' and '}'
  1232. // that make jQuery choke.
  1233. return SDPUtil.filter_special_chars(stream.id);
  1234. };
  1235. this.getVideoSrc = function (element) {
  1236. if(!element)
  1237. return null;
  1238. return element.getAttribute("src");
  1239. };
  1240. this.setVideoSrc = function (element, src) {
  1241. if(element)
  1242. element.setAttribute("src", src);
  1243. };
  1244. // DTLS should now be enabled by default but..
  1245. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1246. if (navigator.userAgent.indexOf('Android') != -1) {
  1247. this.pc_constraints = {}; // disable DTLS on Android
  1248. }
  1249. if (!webkitMediaStream.prototype.getVideoTracks) {
  1250. webkitMediaStream.prototype.getVideoTracks = function () {
  1251. return this.videoTracks;
  1252. };
  1253. }
  1254. if (!webkitMediaStream.prototype.getAudioTracks) {
  1255. webkitMediaStream.prototype.getAudioTracks = function () {
  1256. return this.audioTracks;
  1257. };
  1258. }
  1259. }
  1260. // Detect IE/Safari
  1261. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1262. AdapterJS.WebRTCPlugin.setLogLevel(
  1263. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1264. AdapterJS.webRTCReady(function (isPlugin) {
  1265. self.peerconnection = RTCPeerConnection;
  1266. self.getUserMedia = getUserMedia;
  1267. self.attachMediaStream = function (elSel, stream) {
  1268. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1269. return;
  1270. }
  1271. attachMediaStream(elSel[0], stream);
  1272. };
  1273. self.getStreamID = function (stream) {
  1274. var id = SDPUtil.filter_special_chars(stream.label);
  1275. return id;
  1276. };
  1277. self.getVideoSrc = function (element) {
  1278. if (!element) {
  1279. console.warn("Attempt to get video SRC of null element");
  1280. return null;
  1281. }
  1282. var src = null;
  1283. var children = element.children;
  1284. for (var i = 0; i !== children.length; ++i) {
  1285. if (children[i].name === 'streamId') {
  1286. return children[i].value;
  1287. }
  1288. }
  1289. //console.info(element.id + " SRC: " + src);
  1290. return null;
  1291. };
  1292. self.setVideoSrc = function (element, src) {
  1293. //console.info("Set video src: ", element, src);
  1294. if (!src) {
  1295. console.warn("Not attaching video stream, 'src' is null");
  1296. return;
  1297. }
  1298. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1299. var stream = AdapterJS.WebRTCPlugin.plugin
  1300. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1301. attachMediaStream(element, stream);
  1302. };
  1303. onTemasysPluginReady(isPlugin);
  1304. });
  1305. } else {
  1306. try {
  1307. console.log('Browser does not appear to be WebRTC-capable');
  1308. } catch (e) { }
  1309. window.location.href = 'unsupported_browser.html';
  1310. }
  1311. }
  1312. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1313. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1314. desktopStream)
  1315. {
  1316. currentResolution = resolution;
  1317. // Check if we are running on Android device
  1318. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1319. var constraints = getConstraints(
  1320. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1321. console.info("Get media constraints", constraints);
  1322. var self = this;
  1323. try {
  1324. this.getUserMedia(constraints,
  1325. function (stream) {
  1326. console.log('onUserMediaSuccess');
  1327. self.setAvailableDevices(um, true);
  1328. success_callback(stream);
  1329. },
  1330. function (error) {
  1331. self.setAvailableDevices(um, false);
  1332. console.warn('Failed to get access to local media. Error ',
  1333. error, constraints);
  1334. if (failure_callback) {
  1335. failure_callback(error);
  1336. }
  1337. });
  1338. } catch (e) {
  1339. console.error('GUM failed: ', e);
  1340. if(failure_callback) {
  1341. failure_callback(e);
  1342. }
  1343. }
  1344. };
  1345. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1346. var devices = {};
  1347. if(um.indexOf("video") != -1)
  1348. {
  1349. devices.video = available;
  1350. }
  1351. if(um.indexOf("audio") != -1)
  1352. {
  1353. devices.audio = available;
  1354. }
  1355. this.service.setDeviceAvailability(devices);
  1356. }
  1357. /**
  1358. * We ask for audio and video combined stream in order to get permissions and
  1359. * not to ask twice.
  1360. */
  1361. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1362. function(devices, callback, usageOptions)
  1363. {
  1364. var self = this;
  1365. // Get AV
  1366. var successCallback = function (stream) {
  1367. if(callback)
  1368. callback(stream, usageOptions);
  1369. else
  1370. self.successCallback(stream, usageOptions);
  1371. };
  1372. if(!devices)
  1373. devices = ['audio', 'video'];
  1374. var newDevices = [];
  1375. if(usageOptions)
  1376. for(var i = 0; i < devices.length; i++)
  1377. {
  1378. var device = devices[i];
  1379. if(usageOptions[device] === true)
  1380. newDevices.push(device);
  1381. }
  1382. else
  1383. newDevices = devices;
  1384. if(newDevices.length === 0)
  1385. {
  1386. successCallback();
  1387. return;
  1388. }
  1389. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1390. // With FF/IE we can't split the stream into audio and video because FF
  1391. // doesn't support media stream constructors. So, we need to get the
  1392. // audio stream separately from the video stream using two distinct GUM
  1393. // calls. Not very user friendly :-( but we don't have many other
  1394. // options neither.
  1395. //
  1396. // Note that we pack those 2 streams in a single object and pass it to
  1397. // the successCallback method.
  1398. var obtainVideo = function (audioStream) {
  1399. self.getUserMediaWithConstraints(
  1400. ['video'],
  1401. function (videoStream) {
  1402. return successCallback({
  1403. audioStream: audioStream,
  1404. videoStream: videoStream
  1405. });
  1406. },
  1407. function (error) {
  1408. console.error(
  1409. 'failed to obtain video stream - stop', error);
  1410. self.errorCallback(error);
  1411. },
  1412. config.resolution || '360');
  1413. };
  1414. var obtainAudio = function () {
  1415. self.getUserMediaWithConstraints(
  1416. ['audio'],
  1417. function (audioStream) {
  1418. if (newDevices.indexOf('video') !== -1)
  1419. obtainVideo(audioStream);
  1420. },
  1421. function (error) {
  1422. console.error(
  1423. 'failed to obtain audio stream - stop', error);
  1424. self.errorCallback(error);
  1425. }
  1426. );
  1427. };
  1428. if (newDevices.indexOf('audio') !== -1) {
  1429. obtainAudio();
  1430. } else {
  1431. obtainVideo(null);
  1432. }
  1433. } else {
  1434. this.getUserMediaWithConstraints(
  1435. newDevices,
  1436. function (stream) {
  1437. successCallback(stream);
  1438. },
  1439. function (error) {
  1440. self.errorCallback(error);
  1441. },
  1442. config.resolution || '360');
  1443. }
  1444. };
  1445. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1446. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1447. // it's an object with two properties: audioStream, videoStream.
  1448. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1449. console.log('got', stream, stream.getAudioTracks().length,
  1450. stream.getVideoTracks().length);
  1451. this.handleLocalStream(stream, usageOptions);
  1452. };
  1453. RTCUtils.prototype.errorCallback = function (error) {
  1454. var self = this;
  1455. console.error('failed to obtain audio/video stream - trying audio only', error);
  1456. var resolution = getPreviousResolution(currentResolution);
  1457. if(typeof error == "object" && error.constraintName && error.name
  1458. && (error.name == "ConstraintNotSatisfiedError" ||
  1459. error.name == "OverconstrainedError") &&
  1460. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1461. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1462. && resolution != null)
  1463. {
  1464. self.getUserMediaWithConstraints(['audio', 'video'],
  1465. function (stream) {
  1466. return self.successCallback(stream);
  1467. }, function (error) {
  1468. return self.errorCallback(error);
  1469. }, resolution);
  1470. }
  1471. else
  1472. {
  1473. self.getUserMediaWithConstraints(
  1474. ['audio'],
  1475. function (stream) {
  1476. return self.successCallback(stream);
  1477. },
  1478. function (error) {
  1479. console.error('failed to obtain audio/video stream - stop',
  1480. error);
  1481. return self.successCallback(null);
  1482. }
  1483. );
  1484. }
  1485. }
  1486. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1487. {
  1488. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1489. // an object with two properties: audioStream, videoStream.
  1490. var audioStream, videoStream;
  1491. if(window.webkitMediaStream)
  1492. {
  1493. audioStream = new webkitMediaStream();
  1494. videoStream = new webkitMediaStream();
  1495. if(stream) {
  1496. var audioTracks = stream.getAudioTracks();
  1497. for (var i = 0; i < audioTracks.length; i++) {
  1498. audioStream.addTrack(audioTracks[i]);
  1499. }
  1500. var videoTracks = stream.getVideoTracks();
  1501. for (i = 0; i < videoTracks.length; i++) {
  1502. videoStream.addTrack(videoTracks[i]);
  1503. }
  1504. }
  1505. }
  1506. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1507. { // Firefox and Temasys plugin
  1508. if (stream && stream.audioStream)
  1509. audioStream = stream.audioStream;
  1510. else
  1511. audioStream = new DummyMediaStream("dummyAudio");
  1512. if (stream && stream.videoStream)
  1513. videoStream = stream.videoStream;
  1514. else
  1515. videoStream = new DummyMediaStream("dummyVideo");
  1516. }
  1517. var audioMuted = (usageOptions && usageOptions.audio === false),
  1518. videoMuted = (usageOptions && usageOptions.video === false);
  1519. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1520. videoGUM = (!usageOptions || usageOptions.video !== false);
  1521. this.service.createLocalStream(audioStream, "audio", null, null,
  1522. audioMuted, audioGUM);
  1523. this.service.createLocalStream(videoStream, "video", null, null,
  1524. videoMuted, videoGUM);
  1525. };
  1526. function DummyMediaStream(id) {
  1527. this.id = id;
  1528. this.label = id;
  1529. this.stop = function() { };
  1530. this.getAudioTracks = function() { return []; }
  1531. this.getVideoTracks = function() { return []; }
  1532. }
  1533. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1534. var newStream = null;
  1535. if (window.webkitMediaStream) {
  1536. newStream = new webkitMediaStream();
  1537. if (newStream) {
  1538. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1539. for (i = 0; i < tracks.length; i++) {
  1540. newStream.addTrack(tracks[i]);
  1541. }
  1542. }
  1543. }
  1544. else {
  1545. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1546. if (stream) {
  1547. newStream = stream;
  1548. } else {
  1549. newStream = new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1550. }
  1551. }
  1552. return newStream;
  1553. };
  1554. module.exports = RTCUtils;
  1555. },{"../../service/RTC/Resolutions":104,"../xmpp/SDPUtil":56,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1556. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1557. // Adapter's interface.
  1558. var AdapterJS = AdapterJS || {};
  1559. // Browserify compatibility
  1560. if(typeof exports !== 'undefined') {
  1561. module.exports = AdapterJS;
  1562. }
  1563. AdapterJS.options = AdapterJS.options || {};
  1564. // uncomment to get virtual webcams
  1565. // AdapterJS.options.getAllCams = true;
  1566. // uncomment to prevent the install prompt when the plugin in not yet installed
  1567. // AdapterJS.options.hidePluginInstallPrompt = true;
  1568. // AdapterJS version
  1569. AdapterJS.VERSION = '0.11.0';
  1570. // This function will be called when the WebRTC API is ready to be used
  1571. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1572. // the plugin
  1573. // You may Override this function to synchronise the start of your application
  1574. // with the WebRTC API being ready.
  1575. // If you decide not to override use this synchronisation, it may result in
  1576. // an extensive CPU usage on the plugin start (once per tab loaded)
  1577. // Params:
  1578. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1579. //
  1580. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1581. // The WebRTC API is ready.
  1582. // Override me and do whatever you want here
  1583. };
  1584. // Sets a callback function to be called when the WebRTC interface is ready.
  1585. // The first argument is the function to callback.\
  1586. // Throws an error if the first argument is not a function
  1587. AdapterJS.webRTCReady = function (callback) {
  1588. if (typeof callback !== 'function') {
  1589. throw new Error('Callback provided is not a function');
  1590. }
  1591. if (true === AdapterJS.onwebrtcreadyDone) {
  1592. // All WebRTC interfaces are ready, just call the callback
  1593. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1594. } else {
  1595. // will be triggered automatically when your browser/plugin is ready.
  1596. AdapterJS.onwebrtcready = callback;
  1597. }
  1598. };
  1599. // Plugin namespace
  1600. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1601. // The object to store plugin information
  1602. AdapterJS.WebRTCPlugin.pluginInfo = {
  1603. prefix : 'Tem',
  1604. plugName : 'TemWebRTCPlugin',
  1605. pluginId : 'plugin0',
  1606. type : 'application/x-temwebrtcplugin',
  1607. onload : '__TemWebRTCReady0',
  1608. portalLink : 'http://skylink.io/plugin/',
  1609. downloadLink : null, //set below
  1610. companyName: 'Temasys'
  1611. };
  1612. if(!!navigator.platform.match(/^Mac/i)) {
  1613. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1614. }
  1615. else if(!!navigator.platform.match(/^Win/i)) {
  1616. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1617. }
  1618. // Unique identifier of each opened page
  1619. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1620. // Use this whenever you want to call the plugin.
  1621. AdapterJS.WebRTCPlugin.plugin = null;
  1622. // Set log level for the plugin once it is ready.
  1623. // The different values are
  1624. // This is an asynchronous function that will run when the plugin is ready
  1625. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1626. // Defines webrtc's JS interface according to the plugin's implementation.
  1627. // Define plugin Browsers as WebRTC Interface.
  1628. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1629. // This function detects whether or not a plugin is installed.
  1630. // Checks if Not IE (firefox, for example), else if it's IE,
  1631. // we're running IE and do something. If not it is not supported.
  1632. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1633. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1634. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1635. // Inject the HTML DOM object element into the page.
  1636. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1637. // States of readiness that the plugin goes through when
  1638. // being injected and stated
  1639. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1640. NONE : 0, // no plugin use
  1641. INITIALIZING : 1, // Detected need for plugin
  1642. INJECTING : 2, // Injecting plugin
  1643. INJECTED: 3, // Plugin element injected but not usable yet
  1644. READY: 4 // Plugin ready to be used
  1645. };
  1646. // Current state of the plugin. You cannot use the plugin before this is
  1647. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1648. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1649. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1650. // Used to make sure AdapterJS.onwebrtcready is only called once
  1651. AdapterJS.onwebrtcreadyDone = false;
  1652. // Log levels for the plugin.
  1653. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1654. /*
  1655. Log outputs are prefixed in some cases.
  1656. INFO: Information reported by the plugin.
  1657. ERROR: Errors originating from within the plugin.
  1658. WEBRTC: Error originating from within the libWebRTC library
  1659. */
  1660. // From the least verbose to the most verbose
  1661. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1662. NONE : 'NONE',
  1663. ERROR : 'ERROR',
  1664. WARNING : 'WARNING',
  1665. INFO: 'INFO',
  1666. VERBOSE: 'VERBOSE',
  1667. SENSITIVE: 'SENSITIVE'
  1668. };
  1669. // Does a waiting check before proceeding to load the plugin.
  1670. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1671. // This methid will use an interval to wait for the plugin to be ready.
  1672. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1673. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1674. // This function will be called when plugin is ready. It sends necessary
  1675. // details to the plugin.
  1676. // The function will wait for the document to be ready and the set the
  1677. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1678. // indicating that it can start being requested.
  1679. // This function is not in the IE/Safari condition brackets so that
  1680. // TemPluginLoaded function might be called on Chrome/Firefox.
  1681. // This function is the only private function that is not encapsulated to
  1682. // allow the plugin method to be called.
  1683. __TemWebRTCReady0 = function () {
  1684. if (document.readyState === 'complete') {
  1685. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1686. AdapterJS.maybeThroughWebRTCReady();
  1687. } else {
  1688. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1689. if (document.readyState === 'complete') {
  1690. // TODO: update comments, we wait for the document to be ready
  1691. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1692. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1693. AdapterJS.maybeThroughWebRTCReady();
  1694. }
  1695. }, 100);
  1696. }
  1697. };
  1698. AdapterJS.maybeThroughWebRTCReady = function() {
  1699. if (!AdapterJS.onwebrtcreadyDone) {
  1700. AdapterJS.onwebrtcreadyDone = true;
  1701. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1702. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1703. }
  1704. }
  1705. };
  1706. // Text namespace
  1707. AdapterJS.TEXT = {
  1708. PLUGIN: {
  1709. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1710. 'to work on this browser.',
  1711. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1712. BUTTON: 'Install Now'
  1713. },
  1714. REFRESH: {
  1715. REQUIRE_REFRESH: 'Please refresh page',
  1716. BUTTON: 'Refresh Page'
  1717. }
  1718. };
  1719. // The result of ice connection states.
  1720. // - starting: Ice connection is starting.
  1721. // - checking: Ice connection is checking.
  1722. // - connected Ice connection is connected.
  1723. // - completed Ice connection is connected.
  1724. // - done Ice connection has been completed.
  1725. // - disconnected Ice connection has been disconnected.
  1726. // - failed Ice connection has failed.
  1727. // - closed Ice connection is closed.
  1728. AdapterJS._iceConnectionStates = {
  1729. starting : 'starting',
  1730. checking : 'checking',
  1731. connected : 'connected',
  1732. completed : 'connected',
  1733. done : 'completed',
  1734. disconnected : 'disconnected',
  1735. failed : 'failed',
  1736. closed : 'closed'
  1737. };
  1738. //The IceConnection states that has been fired for each peer.
  1739. AdapterJS._iceConnectionFiredStates = [];
  1740. // Check if WebRTC Interface is defined.
  1741. AdapterJS.isDefined = null;
  1742. // This function helps to retrieve the webrtc detected browser information.
  1743. // This sets:
  1744. // - webrtcDetectedBrowser: The browser agent name.
  1745. // - webrtcDetectedVersion: The browser version.
  1746. // - webrtcDetectedType: The types of webRTC support.
  1747. // - 'moz': Mozilla implementation of webRTC.
  1748. // - 'webkit': WebKit implementation of webRTC.
  1749. // - 'plugin': Using the plugin implementation.
  1750. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1751. var hasMatch, checkMatch = navigator.userAgent.match(
  1752. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1753. if (/trident/i.test(checkMatch[1])) {
  1754. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1755. webrtcDetectedBrowser = 'IE';
  1756. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1757. } else if (checkMatch[1] === 'Chrome') {
  1758. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1759. if (hasMatch !== null) {
  1760. webrtcDetectedBrowser = 'opera';
  1761. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1762. }
  1763. }
  1764. if (navigator.userAgent.indexOf('Safari')) {
  1765. if (typeof InstallTrigger !== 'undefined') {
  1766. webrtcDetectedBrowser = 'firefox';
  1767. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1768. webrtcDetectedBrowser = 'IE';
  1769. } else if (
  1770. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1771. webrtcDetectedBrowser = 'safari';
  1772. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1773. webrtcDetectedBrowser = 'opera';
  1774. } else if (!!window.chrome) {
  1775. webrtcDetectedBrowser = 'chrome';
  1776. }
  1777. }
  1778. if (!webrtcDetectedBrowser) {
  1779. webrtcDetectedVersion = checkMatch[1];
  1780. }
  1781. if (!webrtcDetectedVersion) {
  1782. try {
  1783. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1784. [navigator.appName, navigator.appVersion, '-?'];
  1785. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1786. checkMatch.splice(1, 1, hasMatch[1]);
  1787. }
  1788. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1789. } catch (error) { }
  1790. }
  1791. };
  1792. // To fix configuration as some browsers does not support
  1793. // the 'urls' attribute.
  1794. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1795. if (pcConfig === null) {
  1796. return;
  1797. }
  1798. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1799. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1800. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1801. delete pcConfig.iceServers[i].urls;
  1802. }
  1803. }
  1804. };
  1805. AdapterJS.addEvent = function(elem, evnt, func) {
  1806. if (elem.addEventListener) { // W3C DOM
  1807. elem.addEventListener(evnt, func, false);
  1808. } else if (elem.attachEvent) {// OLD IE DOM
  1809. elem.attachEvent('on'+evnt, func);
  1810. } else { // No much to do
  1811. elem[evnt] = func;
  1812. }
  1813. };
  1814. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1815. // only inject once the page is ready
  1816. if (document.readyState !== 'complete') {
  1817. return;
  1818. }
  1819. var w = window;
  1820. var i = document.createElement('iframe');
  1821. i.style.position = 'fixed';
  1822. i.style.top = '-41px';
  1823. i.style.left = 0;
  1824. i.style.right = 0;
  1825. i.style.width = '100%';
  1826. i.style.height = '40px';
  1827. i.style.backgroundColor = '#ffffe1';
  1828. i.style.border = 'none';
  1829. i.style.borderBottom = '1px solid #888888';
  1830. i.style.zIndex = '9999999';
  1831. if(typeof i.style.webkitTransition === 'string') {
  1832. i.style.webkitTransition = 'all .5s ease-out';
  1833. } else if(typeof i.style.transition === 'string') {
  1834. i.style.transition = 'all .5s ease-out';
  1835. }
  1836. document.body.appendChild(i);
  1837. c = (i.contentWindow) ? i.contentWindow :
  1838. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1839. c.document.open();
  1840. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1841. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1842. 'middle; cursor: default;">' + text + '</span>');
  1843. if(buttonText && buttonLink) {
  1844. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1845. c.document.close();
  1846. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1847. if (!!displayRefreshBar) {
  1848. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1849. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1850. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1851. }
  1852. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1853. e.preventDefault();
  1854. try {
  1855. event.cancelBubble = true;
  1856. } catch(error) { }
  1857. });
  1858. }
  1859. else {
  1860. c.document.close();
  1861. }
  1862. AdapterJS.addEvent(c.document, 'click', function() {
  1863. w.document.body.removeChild(i);
  1864. });
  1865. setTimeout(function() {
  1866. if(typeof i.style.webkitTransform === 'string') {
  1867. i.style.webkitTransform = 'translateY(40px)';
  1868. } else if(typeof i.style.transform === 'string') {
  1869. i.style.transform = 'translateY(40px)';
  1870. } else {
  1871. i.style.top = '0px';
  1872. }
  1873. }, 300);
  1874. };
  1875. // -----------------------------------------------------------
  1876. // Detected webrtc implementation. Types are:
  1877. // - 'moz': Mozilla implementation of webRTC.
  1878. // - 'webkit': WebKit implementation of webRTC.
  1879. // - 'plugin': Using the plugin implementation.
  1880. webrtcDetectedType = null;
  1881. // Detected webrtc datachannel support. Types are:
  1882. // - 'SCTP': SCTP datachannel support.
  1883. // - 'RTP': RTP datachannel support.
  1884. webrtcDetectedDCSupport = null;
  1885. // Set the settings for creating DataChannels, MediaStream for
  1886. // Cross-browser compability.
  1887. // - This is only for SCTP based support browsers.
  1888. // the 'urls' attribute.
  1889. checkMediaDataChannelSettings =
  1890. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1891. if (typeof callback !== 'function') {
  1892. return;
  1893. }
  1894. var beOfferer = true;
  1895. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1896. // Nightly version does not require MozDontOfferDataChannel for interop
  1897. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1898. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1899. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1900. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1901. // Resends an updated version of constraints for MozDataChannel to work
  1902. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1903. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1904. try {
  1905. delete constraints.mandatory.MozDontOfferDataChannel;
  1906. } catch (error) {
  1907. console.error('Failed deleting MozDontOfferDataChannel');
  1908. console.error(error);
  1909. }
  1910. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1911. constraints.mandatory.MozDontOfferDataChannel = true;
  1912. }
  1913. if (!isLocalFirefox) {
  1914. // temporary measure to remove Moz* constraints in non Firefox browsers
  1915. for (var prop in constraints.mandatory) {
  1916. if (constraints.mandatory.hasOwnProperty(prop)) {
  1917. if (prop.indexOf('Moz') !== -1) {
  1918. delete constraints.mandatory[prop];
  1919. }
  1920. }
  1921. }
  1922. }
  1923. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1924. // interopability of the media stream
  1925. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1926. beOfferer = false;
  1927. }
  1928. callback(beOfferer, constraints);
  1929. };
  1930. // Handles the differences for all browsers ice connection state output.
  1931. // - Tested outcomes are:
  1932. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1933. // - Chrome (answerer) : 'checking' > 'connected'
  1934. // - Firefox (offerer) : 'checking' > 'connected'
  1935. // - Firefox (answerer): 'checking' > 'connected'
  1936. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1937. if (typeof callback !== 'function') {
  1938. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1939. return;
  1940. }
  1941. peerId = (peerId) ? peerId : 'peer';
  1942. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1943. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1944. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1945. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1946. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1947. }
  1948. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1949. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1950. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1951. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1952. setTimeout(function () {
  1953. AdapterJS._iceConnectionFiredStates[peerId]
  1954. .push(AdapterJS._iceConnectionStates.done);
  1955. callback(AdapterJS._iceConnectionStates.done);
  1956. }, 1000);
  1957. }
  1958. callback(iceConnectionState);
  1959. }
  1960. return;
  1961. };
  1962. // Firefox:
  1963. // - Creates iceServer from the url for Firefox.
  1964. // - Create iceServer with stun url.
  1965. // - Create iceServer with turn url.
  1966. // - Ignore the transport parameter from TURN url for FF version <=27.
  1967. // - Return null for createIceServer if transport=tcp.
  1968. // - FF 27 and above supports transport parameters in TURN url,
  1969. // - So passing in the full url to create iceServer.
  1970. // Chrome:
  1971. // - Creates iceServer from the url for Chrome M33 and earlier.
  1972. // - Create iceServer with stun url.
  1973. // - Chrome M28 & above uses below TURN format.
  1974. // Plugin:
  1975. // - Creates Ice Server for Plugin Browsers
  1976. // - If Stun - Create iceServer with stun url.
  1977. // - Else - Create iceServer with turn url
  1978. // - This is a WebRTC Function
  1979. createIceServer = null;
  1980. // Firefox:
  1981. // - Creates IceServers for Firefox
  1982. // - Use .url for FireFox.
  1983. // - Multiple Urls support
  1984. // Chrome:
  1985. // - Creates iceServers from the urls for Chrome M34 and above.
  1986. // - .urls is supported since Chrome M34.
  1987. // - Multiple Urls support
  1988. // Plugin:
  1989. // - Creates Ice Servers for Plugin Browsers
  1990. // - Multiple Urls support
  1991. // - This is a WebRTC Function
  1992. createIceServers = null;
  1993. //------------------------------------------------------------
  1994. //The RTCPeerConnection object.
  1995. RTCPeerConnection = null;
  1996. // Creates RTCSessionDescription object for Plugin Browsers
  1997. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  1998. RTCSessionDescription : null;
  1999. // Creates RTCIceCandidate object for Plugin Browsers
  2000. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2001. RTCIceCandidate : null;
  2002. // Get UserMedia (only difference is the prefix).
  2003. // Code from Adam Barth.
  2004. getUserMedia = null;
  2005. // Attach a media stream to an element.
  2006. attachMediaStream = null;
  2007. // Re-attach a media stream to an element.
  2008. reattachMediaStream = null;
  2009. // Detected browser agent name. Types are:
  2010. // - 'firefox': Firefox browser.
  2011. // - 'chrome': Chrome browser.
  2012. // - 'opera': Opera browser.
  2013. // - 'safari': Safari browser.
  2014. // - 'IE' - Internet Explorer browser.
  2015. webrtcDetectedBrowser = null;
  2016. // Detected browser version.
  2017. webrtcDetectedVersion = null;
  2018. // Check for browser types and react accordingly
  2019. if (navigator.mozGetUserMedia) {
  2020. webrtcDetectedBrowser = 'firefox';
  2021. webrtcDetectedVersion = parseInt(navigator
  2022. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2023. webrtcDetectedType = 'moz';
  2024. webrtcDetectedDCSupport = 'SCTP';
  2025. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2026. AdapterJS.maybeFixConfiguration(pcConfig);
  2027. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2028. };
  2029. // The RTCSessionDescription object.
  2030. RTCSessionDescription = mozRTCSessionDescription;
  2031. window.RTCSessionDescription = RTCSessionDescription;
  2032. // The RTCIceCandidate object.
  2033. RTCIceCandidate = mozRTCIceCandidate;
  2034. window.RTCIceCandidate = RTCIceCandidate;
  2035. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2036. navigator.getUserMedia = window.getUserMedia;
  2037. // Shim for MediaStreamTrack.getSources.
  2038. MediaStreamTrack.getSources = function(successCb) {
  2039. setTimeout(function() {
  2040. var infos = [
  2041. { kind: 'audio', id: 'default', label:'', facing:'' },
  2042. { kind: 'video', id: 'default', label:'', facing:'' }
  2043. ];
  2044. successCb(infos);
  2045. }, 0);
  2046. };
  2047. createIceServer = function (url, username, password) {
  2048. var iceServer = null;
  2049. var url_parts = url.split(':');
  2050. if (url_parts[0].indexOf('stun') === 0) {
  2051. iceServer = { url : url };
  2052. } else if (url_parts[0].indexOf('turn') === 0) {
  2053. if (webrtcDetectedVersion < 27) {
  2054. var turn_url_parts = url.split('?');
  2055. if (turn_url_parts.length === 1 ||
  2056. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2057. iceServer = {
  2058. url : turn_url_parts[0],
  2059. credential : password,
  2060. username : username
  2061. };
  2062. }
  2063. } else {
  2064. iceServer = {
  2065. url : url,
  2066. credential : password,
  2067. username : username
  2068. };
  2069. }
  2070. }
  2071. return iceServer;
  2072. };
  2073. createIceServers = function (urls, username, password) {
  2074. var iceServers = [];
  2075. for (i = 0; i < urls.length; i++) {
  2076. var iceServer = createIceServer(urls[i], username, password);
  2077. if (iceServer !== null) {
  2078. iceServers.push(iceServer);
  2079. }
  2080. }
  2081. return iceServers;
  2082. };
  2083. attachMediaStream = function (element, stream) {
  2084. element.mozSrcObject = stream;
  2085. if (stream !== null)
  2086. element.play();
  2087. return element;
  2088. };
  2089. reattachMediaStream = function (to, from) {
  2090. to.mozSrcObject = from.mozSrcObject;
  2091. to.play();
  2092. return to;
  2093. };
  2094. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2095. if (!callback) {
  2096. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2097. ': 1 argument required, but only 0 present.');
  2098. }
  2099. return callback([]);
  2100. };
  2101. // Fake get{Video,Audio}Tracks
  2102. if (!MediaStream.prototype.getVideoTracks) {
  2103. MediaStream.prototype.getVideoTracks = function () {
  2104. return [];
  2105. };
  2106. }
  2107. if (!MediaStream.prototype.getAudioTracks) {
  2108. MediaStream.prototype.getAudioTracks = function () {
  2109. return [];
  2110. };
  2111. }
  2112. AdapterJS.maybeThroughWebRTCReady();
  2113. } else if (navigator.webkitGetUserMedia) {
  2114. webrtcDetectedBrowser = 'chrome';
  2115. webrtcDetectedType = 'webkit';
  2116. webrtcDetectedVersion = parseInt(navigator
  2117. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2118. // check if browser is opera 20+
  2119. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2120. if (checkIfOpera !== null) {
  2121. webrtcDetectedBrowser = 'opera';
  2122. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2123. }
  2124. // check browser datachannel support
  2125. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2126. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2127. webrtcDetectedDCSupport = 'SCTP';
  2128. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2129. webrtcDetectedVersion > 24) {
  2130. webrtcDetectedDCSupport = 'RTP';
  2131. } else {
  2132. webrtcDetectedDCSupport = '';
  2133. }
  2134. createIceServer = function (url, username, password) {
  2135. var iceServer = null;
  2136. var url_parts = url.split(':');
  2137. if (url_parts[0].indexOf('stun') === 0) {
  2138. iceServer = { 'url' : url };
  2139. } else if (url_parts[0].indexOf('turn') === 0) {
  2140. iceServer = {
  2141. 'url' : url,
  2142. 'credential' : password,
  2143. 'username' : username
  2144. };
  2145. }
  2146. return iceServer;
  2147. };
  2148. createIceServers = function (urls, username, password) {
  2149. var iceServers = [];
  2150. if (webrtcDetectedVersion >= 34) {
  2151. iceServers = {
  2152. 'urls' : urls,
  2153. 'credential' : password,
  2154. 'username' : username
  2155. };
  2156. } else {
  2157. for (i = 0; i < urls.length; i++) {
  2158. var iceServer = createIceServer(urls[i], username, password);
  2159. if (iceServer !== null) {
  2160. iceServers.push(iceServer);
  2161. }
  2162. }
  2163. }
  2164. return iceServers;
  2165. };
  2166. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2167. if (webrtcDetectedVersion < 34) {
  2168. AdapterJS.maybeFixConfiguration(pcConfig);
  2169. }
  2170. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2171. };
  2172. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2173. navigator.getUserMedia = window.getUserMedia;
  2174. attachMediaStream = function (element, stream) {
  2175. if (typeof element.srcObject !== 'undefined') {
  2176. element.srcObject = stream;
  2177. } else if (typeof element.mozSrcObject !== 'undefined') {
  2178. element.mozSrcObject = stream;
  2179. } else if (typeof element.src !== 'undefined') {
  2180. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2181. } else {
  2182. console.log('Error attaching stream to element.');
  2183. }
  2184. return element;
  2185. };
  2186. reattachMediaStream = function (to, from) {
  2187. to.src = from.src;
  2188. return to;
  2189. };
  2190. AdapterJS.maybeThroughWebRTCReady();
  2191. } else { // TRY TO USE PLUGIN
  2192. // IE 9 is not offering an implementation of console.log until you open a console
  2193. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2194. /* jshint -W020 */
  2195. console = {} || console;
  2196. // Implemented based on console specs from MDN
  2197. // You may override these functions
  2198. console.log = function (arg) {};
  2199. console.info = function (arg) {};
  2200. console.error = function (arg) {};
  2201. console.dir = function (arg) {};
  2202. console.exception = function (arg) {};
  2203. console.trace = function (arg) {};
  2204. console.warn = function (arg) {};
  2205. console.count = function (arg) {};
  2206. console.debug = function (arg) {};
  2207. console.count = function (arg) {};
  2208. console.time = function (arg) {};
  2209. console.timeEnd = function (arg) {};
  2210. console.group = function (arg) {};
  2211. console.groupCollapsed = function (arg) {};
  2212. console.groupEnd = function (arg) {};
  2213. /* jshint +W020 */
  2214. }
  2215. webrtcDetectedType = 'plugin';
  2216. webrtcDetectedDCSupport = 'plugin';
  2217. AdapterJS.parseWebrtcDetectedBrowser();
  2218. isIE = webrtcDetectedBrowser === 'IE';
  2219. /* jshint -W035 */
  2220. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2221. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2222. /* empty because it needs to prevent the function from running. */
  2223. }
  2224. };
  2225. /* jshint +W035 */
  2226. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2227. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2228. // Call immediately if possible
  2229. // Once the plugin is set, the code will always take this path
  2230. callback();
  2231. } else {
  2232. // otherwise start a 100ms interval
  2233. var checkPluginReadyState = setInterval(function () {
  2234. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2235. clearInterval(checkPluginReadyState);
  2236. callback();
  2237. }
  2238. }, 100);
  2239. }
  2240. };
  2241. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2242. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2243. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2244. });
  2245. };
  2246. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2247. // only inject once the page is ready
  2248. if (document.readyState !== 'complete') {
  2249. return;
  2250. }
  2251. // Prevent multiple injections
  2252. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2253. return;
  2254. }
  2255. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2256. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2257. var frag = document.createDocumentFragment();
  2258. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2259. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2260. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2261. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2262. '<param name="pluginId" value="' +
  2263. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2264. '<param name="windowless" value="false" /> ' +
  2265. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2266. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2267. '" />' +
  2268. // uncomment to be able to use virtual cams
  2269. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2270. '</object>';
  2271. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2272. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2273. }
  2274. document.body.appendChild(frag);
  2275. // Need to re-fetch the plugin
  2276. AdapterJS.WebRTCPlugin.plugin =
  2277. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2278. } else {
  2279. // Load Plugin
  2280. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2281. AdapterJS.WebRTCPlugin.plugin.id =
  2282. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2283. // IE will only start the plugin if it's ACTUALLY visible
  2284. if (isIE) {
  2285. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2286. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2287. } else { // The size of the plugin on Safari should be 0x0px
  2288. // so that the autorisation prompt is at the top
  2289. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2290. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2291. }
  2292. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2293. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2294. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2295. '<param name="pluginId" value="' +
  2296. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2297. '<param name="windowless" value="false" /> ' +
  2298. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2299. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2300. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2301. }
  2302. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2303. };
  2304. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2305. function (comName, plugName, installedCb, notInstalledCb) {
  2306. if (!isIE) {
  2307. var pluginArray = navigator.plugins;
  2308. for (var i = 0; i < pluginArray.length; i++) {
  2309. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2310. installedCb();
  2311. return;
  2312. }
  2313. }
  2314. notInstalledCb();
  2315. } else {
  2316. try {
  2317. var axo = new ActiveXObject(comName + '.' + plugName);
  2318. } catch (e) {
  2319. notInstalledCb();
  2320. return;
  2321. }
  2322. installedCb();
  2323. }
  2324. };
  2325. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2326. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2327. AdapterJS.isDefined = function (variable) {
  2328. return variable !== null && variable !== undefined;
  2329. };
  2330. createIceServer = function (url, username, password) {
  2331. var iceServer = null;
  2332. var url_parts = url.split(':');
  2333. if (url_parts[0].indexOf('stun') === 0) {
  2334. iceServer = {
  2335. 'url' : url,
  2336. 'hasCredentials' : false
  2337. };
  2338. } else if (url_parts[0].indexOf('turn') === 0) {
  2339. iceServer = {
  2340. 'url' : url,
  2341. 'hasCredentials' : true,
  2342. 'credential' : password,
  2343. 'username' : username
  2344. };
  2345. }
  2346. return iceServer;
  2347. };
  2348. createIceServers = function (urls, username, password) {
  2349. var iceServers = [];
  2350. for (var i = 0; i < urls.length; ++i) {
  2351. iceServers.push(createIceServer(urls[i], username, password));
  2352. }
  2353. return iceServers;
  2354. };
  2355. RTCSessionDescription = function (info) {
  2356. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2357. return AdapterJS.WebRTCPlugin.plugin.
  2358. ConstructSessionDescription(info.type, info.sdp);
  2359. };
  2360. RTCPeerConnection = function (servers, constraints) {
  2361. var iceServers = null;
  2362. if (servers) {
  2363. iceServers = servers.iceServers;
  2364. for (var i = 0; i < iceServers.length; i++) {
  2365. if (iceServers[i].urls && !iceServers[i].url) {
  2366. iceServers[i].url = iceServers[i].urls;
  2367. }
  2368. iceServers[i].hasCredentials = AdapterJS.
  2369. isDefined(iceServers[i].username) &&
  2370. AdapterJS.isDefined(iceServers[i].credential);
  2371. }
  2372. }
  2373. var mandatory = (constraints && constraints.mandatory) ?
  2374. constraints.mandatory : null;
  2375. var optional = (constraints && constraints.optional) ?
  2376. constraints.optional : null;
  2377. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2378. return AdapterJS.WebRTCPlugin.plugin.
  2379. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2380. iceServers, mandatory, optional);
  2381. };
  2382. MediaStreamTrack = {};
  2383. MediaStreamTrack.getSources = function (callback) {
  2384. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2385. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2386. });
  2387. };
  2388. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2389. constraints.audio = constraints.audio || false;
  2390. constraints.video = constraints.video || false;
  2391. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2392. AdapterJS.WebRTCPlugin.plugin.
  2393. getUserMedia(constraints, successCallback, failureCallback);
  2394. });
  2395. };
  2396. window.navigator.getUserMedia = window.getUserMedia;
  2397. attachMediaStream = function (element, stream) {
  2398. if (!element || !element.parentNode) {
  2399. return;
  2400. }
  2401. var streamId
  2402. if (stream === null) {
  2403. streamId = '';
  2404. }
  2405. else {
  2406. stream.enableSoundTracks(true);
  2407. streamId = stream.id;
  2408. }
  2409. if (element.nodeName.toLowerCase() !== 'audio') {
  2410. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2411. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2412. var frag = document.createDocumentFragment();
  2413. var temp = document.createElement('div');
  2414. var classHTML = '';
  2415. if (element.className) {
  2416. classHTML = 'class="' + element.className + '" ';
  2417. } else if (element.attributes && element.attributes['class']) {
  2418. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2419. }
  2420. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2421. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2422. '<param name="pluginId" value="' + elementId + '" /> ' +
  2423. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2424. '<param name="windowless" value="true" /> ' +
  2425. '<param name="streamId" value="' + streamId + '" /> ' +
  2426. '</object>';
  2427. while (temp.firstChild) {
  2428. frag.appendChild(temp.firstChild);
  2429. }
  2430. var height = '';
  2431. var width = '';
  2432. if (element.getBoundingClientRect) {
  2433. var rectObject = element.getBoundingClientRect();
  2434. width = rectObject.width + 'px';
  2435. height = rectObject.height + 'px';
  2436. }
  2437. else if (element.width) {
  2438. width = element.width;
  2439. height = element.height;
  2440. } else {
  2441. // TODO: What scenario could bring us here?
  2442. }
  2443. element.parentNode.insertBefore(frag, element);
  2444. frag = document.getElementById(elementId);
  2445. frag.width = width;
  2446. frag.height = height;
  2447. element.parentNode.removeChild(element);
  2448. } else {
  2449. var children = element.children;
  2450. for (var i = 0; i !== children.length; ++i) {
  2451. if (children[i].name === 'streamId') {
  2452. children[i].value = streamId;
  2453. break;
  2454. }
  2455. }
  2456. element.setStreamId(streamId);
  2457. }
  2458. var newElement = document.getElementById(elementId);
  2459. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2460. if (isIE) { // on IE the event needs to be plugged manually
  2461. newElement.attachEvent('onplaying', newElement.onplaying);
  2462. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2463. newElement._TemOnClick = function (id) {
  2464. var arg = {
  2465. srcElement : document.getElementById(id)
  2466. };
  2467. newElement.onclick(arg);
  2468. };
  2469. }
  2470. return newElement;
  2471. } else {
  2472. return element;
  2473. }
  2474. };
  2475. reattachMediaStream = function (to, from) {
  2476. var stream = null;
  2477. var children = from.children;
  2478. for (var i = 0; i !== children.length; ++i) {
  2479. if (children[i].name === 'streamId') {
  2480. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2481. stream = AdapterJS.WebRTCPlugin.plugin
  2482. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2483. break;
  2484. }
  2485. }
  2486. if (stream !== null) {
  2487. return attachMediaStream(to, stream);
  2488. } else {
  2489. console.log('Could not find the stream associated with this element');
  2490. }
  2491. };
  2492. RTCIceCandidate = function (candidate) {
  2493. if (!candidate.sdpMid) {
  2494. candidate.sdpMid = '';
  2495. }
  2496. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2497. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2498. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2499. );
  2500. };
  2501. // inject plugin
  2502. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2503. AdapterJS.WebRTCPlugin.injectPlugin();
  2504. };
  2505. // This function will be called if the plugin is needed (browser different
  2506. // from Chrome or Firefox), but the plugin is not installed.
  2507. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2508. function() {
  2509. AdapterJS.addEvent(document,
  2510. 'readystatechange',
  2511. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2512. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2513. };
  2514. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2515. if (AdapterJS.options.hidePluginInstallPrompt) {
  2516. return;
  2517. }
  2518. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2519. if(downloadLink) { // if download link
  2520. var popupString;
  2521. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2522. popupString = 'This website requires you to install the ' +
  2523. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2524. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2525. ' WebRTC Plugin</a>' +
  2526. ' to work on this browser.';
  2527. } else { // no portal link, just print a generic explanation
  2528. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2529. }
  2530. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2531. } else { // no download link, just print a generic explanation
  2532. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2533. }
  2534. };
  2535. // Try to detect the plugin and act accordingly
  2536. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2537. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2538. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2539. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2540. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2541. }
  2542. (function () {
  2543. 'use strict';
  2544. var baseGetUserMedia = null;
  2545. AdapterJS.TEXT.EXTENSION = {
  2546. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2547. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2548. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2549. BUTTON_FF: 'Install Now',
  2550. BUTTON_CHROME: 'Go to Chrome Web Store'
  2551. };
  2552. var clone = function(obj) {
  2553. if (null == obj || "object" != typeof obj) return obj;
  2554. var copy = obj.constructor();
  2555. for (var attr in obj) {
  2556. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2557. }
  2558. return copy;
  2559. };
  2560. if (window.navigator.mozGetUserMedia) {
  2561. baseGetUserMedia = window.navigator.getUserMedia;
  2562. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2563. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2564. // intercepting screensharing requests
  2565. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2566. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2567. }
  2568. var updatedConstraints = clone(constraints);
  2569. //constraints.video.mediaSource = constraints.video.mediaSource;
  2570. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2571. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2572. // strange but this works anyway
  2573. var checkIfReady = setInterval(function () {
  2574. if (document.readyState === 'complete') {
  2575. clearInterval(checkIfReady);
  2576. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2577. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2578. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2579. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2580. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2581. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2582. } else {
  2583. failureCb(error);
  2584. }
  2585. });
  2586. }
  2587. }, 1);
  2588. } else { // regular GetUserMediaRequest
  2589. baseGetUserMedia(constraints, successCb, failureCb);
  2590. }
  2591. };
  2592. getUserMedia = navigator.getUserMedia;
  2593. } else if (window.navigator.webkitGetUserMedia) {
  2594. baseGetUserMedia = window.navigator.getUserMedia;
  2595. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2596. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2597. if (window.webrtcDetectedBrowser !== 'chrome') {
  2598. throw new Error('Current browser does not support screensharing');
  2599. }
  2600. // would be fine since no methods
  2601. var updatedConstraints = clone(constraints);
  2602. var chromeCallback = function(error, sourceId) {
  2603. if(!error) {
  2604. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2605. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2606. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2607. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2608. if (sourceId) {
  2609. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2610. }
  2611. delete updatedConstraints.video.mediaSource;
  2612. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2613. } else {
  2614. if (error === 'permission-denied') {
  2615. throw new Error('Permission denied for screen retrieval');
  2616. } else {
  2617. throw new Error('Failed retrieving selected screen');
  2618. }
  2619. }
  2620. };
  2621. var onIFrameCallback = function (event) {
  2622. if (!event.data) {
  2623. return;
  2624. }
  2625. if (event.data.chromeMediaSourceId) {
  2626. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2627. chromeCallback('permission-denied');
  2628. } else {
  2629. chromeCallback(null, event.data.chromeMediaSourceId);
  2630. }
  2631. }
  2632. if (event.data.chromeExtensionStatus) {
  2633. if (event.data.chromeExtensionStatus === 'not-installed') {
  2634. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2635. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2636. event.data.data, true, true);
  2637. } else {
  2638. chromeCallback(event.data.chromeExtensionStatus, null);
  2639. }
  2640. }
  2641. // this event listener is no more needed
  2642. window.removeEventListener('message', onIFrameCallback);
  2643. };
  2644. window.addEventListener('message', onIFrameCallback);
  2645. postFrameMessage({
  2646. captureSourceId: true
  2647. });
  2648. } else {
  2649. baseGetUserMedia(constraints, successCb, failureCb);
  2650. }
  2651. };
  2652. getUserMedia = navigator.getUserMedia;
  2653. } else {
  2654. baseGetUserMedia = window.navigator.getUserMedia;
  2655. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2656. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2657. // would be fine since no methods
  2658. var updatedConstraints = clone(constraints);
  2659. // wait for plugin to be ready
  2660. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2661. // check if screensharing feature is available
  2662. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2663. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2664. // set the constraints
  2665. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2666. updatedConstraints.video.optional.push({
  2667. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2668. });
  2669. delete updatedConstraints.video.mediaSource;
  2670. } else {
  2671. throw new Error('Your WebRTC plugin does not support screensharing');
  2672. }
  2673. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2674. });
  2675. } else {
  2676. baseGetUserMedia(constraints, successCb, failureCb);
  2677. }
  2678. };
  2679. getUserMedia = window.navigator.getUserMedia;
  2680. }
  2681. if (window.webrtcDetectedBrowser === 'chrome') {
  2682. var iframe = document.createElement('iframe');
  2683. iframe.onload = function() {
  2684. iframe.isLoaded = true;
  2685. };
  2686. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2687. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2688. iframe.style.display = 'none';
  2689. (document.body || document.documentElement).appendChild(iframe);
  2690. var postFrameMessage = function (object) {
  2691. object = object || {};
  2692. if (!iframe.isLoaded) {
  2693. setTimeout(function () {
  2694. iframe.contentWindow.postMessage(object, '*');
  2695. }, 100);
  2696. return;
  2697. }
  2698. iframe.contentWindow.postMessage(object, '*');
  2699. };
  2700. }
  2701. })();
  2702. },{}],11:[function(require,module,exports){
  2703. var UI = {};
  2704. var VideoLayout = require("./videolayout/VideoLayout.js");
  2705. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2706. var Prezi = require("./prezi/Prezi.js");
  2707. var Etherpad = require("./etherpad/Etherpad.js");
  2708. var Chat = require("./side_pannels/chat/Chat.js");
  2709. var Toolbar = require("./toolbars/Toolbar");
  2710. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2711. var BottomToolbar = require("./toolbars/BottomToolbar");
  2712. var ContactList = require("./side_pannels/contactlist/ContactList");
  2713. var Avatar = require("./avatar/Avatar");
  2714. var EventEmitter = require("events");
  2715. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2716. var Settings = require("./../settings/Settings");
  2717. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2718. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2719. UI.messageHandler = require("./util/MessageHandler");
  2720. var messageHandler = UI.messageHandler;
  2721. var Authentication = require("./authentication/Authentication");
  2722. var UIUtil = require("./util/UIUtil");
  2723. var NicknameHandler = require("./util/NicknameHandler");
  2724. var CQEvents = require("../../service/connectionquality/CQEvents");
  2725. var DesktopSharingEventTypes
  2726. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2727. var RTCEvents = require("../../service/RTC/RTCEvents");
  2728. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2729. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2730. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2731. var MemberEvents = require("../../service/members/Events");
  2732. var eventEmitter = new EventEmitter();
  2733. var roomName = null;
  2734. function promptDisplayName() {
  2735. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2736. message += APP.translation.translateString(
  2737. "dialog.displayNameRequired");
  2738. message += '</h2>' +
  2739. '<input name="displayName" type="text" data-i18n=' +
  2740. '"[placeholder]defaultNickname" placeholder="' +
  2741. APP.translation.translateString(
  2742. "defaultNickname", {name: "Jane Pink"}) +
  2743. '" autofocus>';
  2744. var buttonTxt
  2745. = APP.translation.generateTranslationHTML("dialog.Ok");
  2746. var buttons = [];
  2747. buttons.push({title: buttonTxt, value: "ok"});
  2748. messageHandler.openDialog(null, message,
  2749. true,
  2750. buttons,
  2751. function (e, v, m, f) {
  2752. if (v == "ok") {
  2753. var displayName = f.displayName;
  2754. if (displayName) {
  2755. VideoLayout.inputDisplayNameHandler(displayName);
  2756. return true;
  2757. }
  2758. }
  2759. e.preventDefault();
  2760. },
  2761. function () {
  2762. var form = $.prompt.getPrompt();
  2763. var input = form.find("input[name='displayName']");
  2764. input.focus();
  2765. var button = form.find("button");
  2766. button.attr("disabled", "disabled");
  2767. input.keyup(function () {
  2768. if(!input.val())
  2769. button.attr("disabled", "disabled");
  2770. else
  2771. button.removeAttr("disabled");
  2772. });
  2773. }
  2774. );
  2775. }
  2776. function notifyForInitialMute()
  2777. {
  2778. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2779. "notify.muted", null, {timeOut: 120000});
  2780. }
  2781. function setupPrezi()
  2782. {
  2783. $("#reloadPresentationLink").click(function()
  2784. {
  2785. Prezi.reloadPresentation();
  2786. });
  2787. }
  2788. function setupChat()
  2789. {
  2790. Chat.init();
  2791. $("#toggle_smileys").click(function() {
  2792. Chat.toggleSmileys();
  2793. });
  2794. }
  2795. function setupToolbars() {
  2796. Toolbar.init(UI);
  2797. Toolbar.setupButtonsFromConfig();
  2798. BottomToolbar.init();
  2799. }
  2800. function streamHandler(stream, isMuted) {
  2801. switch (stream.type)
  2802. {
  2803. case "audio":
  2804. VideoLayout.changeLocalAudio(stream, isMuted);
  2805. break;
  2806. case "video":
  2807. VideoLayout.changeLocalVideo(stream, isMuted);
  2808. break;
  2809. case "stream":
  2810. VideoLayout.changeLocalStream(stream, isMuted);
  2811. break;
  2812. }
  2813. }
  2814. function onXmppConnectionFailed(stropheErrorMsg) {
  2815. var title = APP.translation.generateTranslationHTML(
  2816. "dialog.error");
  2817. var message;
  2818. if (stropheErrorMsg) {
  2819. message = APP.translation.generateTranslationHTML(
  2820. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2821. } else {
  2822. message = APP.translation.generateTranslationHTML(
  2823. "dialog.connectError");
  2824. }
  2825. messageHandler.openDialog(
  2826. title, message, true, {}, function (e, v, m, f) { return false; });
  2827. }
  2828. function onDisposeConference(unload) {
  2829. Toolbar.showAuthenticateButton(false);
  2830. }
  2831. function onDisplayNameChanged(jid, displayName) {
  2832. ContactList.onDisplayNameChange(jid, displayName);
  2833. SettingsMenu.onDisplayNameChange(jid, displayName);
  2834. VideoLayout.onDisplayNameChanged(jid, displayName);
  2835. }
  2836. function registerListeners() {
  2837. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2838. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2839. APP.RTC.addStreamListener(function (stream) {
  2840. VideoLayout.onRemoteStreamAdded(stream);
  2841. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2842. APP.RTC.addStreamListener(function (jid) {
  2843. VideoLayout.onVideoTypeChanged(jid);
  2844. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  2845. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2846. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  2847. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2848. });
  2849. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2850. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2851. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2852. endpointsEnteringLastN, stream);
  2853. });
  2854. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2855. function (devices) {
  2856. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2857. })
  2858. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  2859. {
  2860. var resourceJid;
  2861. if(jid === APP.statistics.LOCAL_JID)
  2862. {
  2863. resourceJid = AudioLevels.LOCAL_LEVEL;
  2864. if(APP.RTC.localAudio.isMuted())
  2865. {
  2866. audioLevel = 0;
  2867. }
  2868. }
  2869. else
  2870. {
  2871. resourceJid = Strophe.getResourceFromJid(jid);
  2872. }
  2873. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2874. UI.getLargeVideoJid());
  2875. });
  2876. APP.desktopsharing.addListener(function () {
  2877. ToolbarToggler.showDesktopSharingButton();
  2878. }, DesktopSharingEventTypes.INIT);
  2879. APP.desktopsharing.addListener(
  2880. Toolbar.changeDesktopSharingButtonState,
  2881. DesktopSharingEventTypes.SWITCHING_DONE);
  2882. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2883. VideoLayout.updateLocalConnectionStats);
  2884. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2885. VideoLayout.updateConnectionStats);
  2886. APP.connectionquality.addListener(CQEvents.STOP,
  2887. VideoLayout.onStatsStop);
  2888. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2889. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2890. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2891. messageHandler.openMessageDialog(
  2892. 'dialog.serviceUnavailable',
  2893. 'dialog.gracefulShutdown'
  2894. );
  2895. });
  2896. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2897. var title = APP.translation.generateTranslationHTML(
  2898. "dialog.reservationError");
  2899. var message = APP.translation.generateTranslationHTML(
  2900. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2901. messageHandler.openDialog(
  2902. title,
  2903. message,
  2904. true, {},
  2905. function (event, value, message, formVals)
  2906. {
  2907. return false;
  2908. }
  2909. );
  2910. });
  2911. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2912. messageHandler.openMessageDialog("dialog.sessTerminated",
  2913. "dialog.kickMessage");
  2914. });
  2915. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2916. //FIXME: use Session Terminated from translation, but
  2917. // 'reason' text comes from XMPP packet and is not translated
  2918. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2919. messageHandler.openDialog(
  2920. title, reason, true, {},
  2921. function (event, value, message, formVals)
  2922. {
  2923. return false;
  2924. }
  2925. );
  2926. });
  2927. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2928. messageHandler.showError("dialog.error",
  2929. "dialog.bridgeUnavailable");
  2930. });
  2931. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2932. Avatar.setUserAvatar(from, id);
  2933. });
  2934. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2935. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2936. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2937. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2938. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2939. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2940. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2941. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2942. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2943. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2944. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2945. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2946. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2947. onAuthenticationRequired);
  2948. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2949. function (resource, devices) {
  2950. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2951. });
  2952. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  2953. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  2954. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2955. onDtmfSupportChanged);
  2956. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  2957. SettingsMenu.setStartMuted(audio, video);
  2958. });
  2959. }
  2960. /**
  2961. * Mutes/unmutes the local video.
  2962. *
  2963. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2964. * @param options an object which specifies optional arguments such as the
  2965. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2966. * specifies whether the method was initiated in response to a user command (in
  2967. * contrast to an automatic decision taken by the application logic)
  2968. */
  2969. function setVideoMute(mute, options) {
  2970. APP.RTC.setVideoMute(mute,
  2971. UI.setVideoMuteButtonsState,
  2972. options);
  2973. }
  2974. function onResize()
  2975. {
  2976. Chat.resizeChat();
  2977. VideoLayout.resizeLargeVideoContainer();
  2978. }
  2979. function bindEvents()
  2980. {
  2981. /**
  2982. * Resizes and repositions videos in full screen mode.
  2983. */
  2984. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  2985. onResize);
  2986. $(window).resize(onResize);
  2987. }
  2988. UI.start = function (init) {
  2989. document.title = interfaceConfig.APP_NAME;
  2990. if(config.enableWelcomePage && window.location.pathname == "/" &&
  2991. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  2992. {
  2993. $("#videoconference_page").hide();
  2994. var setupWelcomePage = require("./welcome_page/WelcomePage");
  2995. setupWelcomePage();
  2996. return;
  2997. }
  2998. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  2999. var leftWatermarkDiv
  3000. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  3001. leftWatermarkDiv.css({display: 'block'});
  3002. leftWatermarkDiv.parent().get(0).href
  3003. = interfaceConfig.JITSI_WATERMARK_LINK;
  3004. }
  3005. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  3006. var rightWatermarkDiv
  3007. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  3008. rightWatermarkDiv.css({display: 'block'});
  3009. rightWatermarkDiv.parent().get(0).href
  3010. = interfaceConfig.BRAND_WATERMARK_LINK;
  3011. rightWatermarkDiv.get(0).style.backgroundImage
  3012. = "url(images/rightwatermark.png)";
  3013. }
  3014. if (interfaceConfig.SHOW_POWERED_BY) {
  3015. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  3016. }
  3017. $("#welcome_page").hide();
  3018. $("#videospace").mousemove(function () {
  3019. return ToolbarToggler.showToolbar();
  3020. });
  3021. // Set the defaults for prompt dialogs.
  3022. jQuery.prompt.setDefaults({persistent: false});
  3023. VideoLayout.init(eventEmitter);
  3024. AudioLevels.init();
  3025. NicknameHandler.init(eventEmitter);
  3026. registerListeners();
  3027. bindEvents();
  3028. setupPrezi();
  3029. setupToolbars();
  3030. setupChat();
  3031. document.title = interfaceConfig.APP_NAME;
  3032. $("#downloadlog").click(function (event) {
  3033. dump(event.target);
  3034. });
  3035. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3036. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3037. {
  3038. $("#videoconference_page").hide();
  3039. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3040. setupWelcomePage();
  3041. return;
  3042. }
  3043. $("#welcome_page").hide();
  3044. // Display notice message at the top of the toolbar
  3045. if (config.noticeMessage) {
  3046. $('#noticeText').text(config.noticeMessage);
  3047. $('#notice').css({display: 'block'});
  3048. }
  3049. if (!RTCBrowserType.isIExplorer()) {
  3050. document.getElementById('largeVideo').volume = 0;
  3051. }
  3052. if(config.requireDisplayName) {
  3053. var currentSettings = Settings.getSettings();
  3054. if (!currentSettings.displayName) {
  3055. promptDisplayName();
  3056. }
  3057. }
  3058. init();
  3059. toastr.options = {
  3060. "closeButton": true,
  3061. "debug": false,
  3062. "positionClass": "notification-bottom-right",
  3063. "onclick": null,
  3064. "showDuration": "300",
  3065. "hideDuration": "1000",
  3066. "timeOut": "2000",
  3067. "extendedTimeOut": "1000",
  3068. "showEasing": "swing",
  3069. "hideEasing": "linear",
  3070. "showMethod": "fadeIn",
  3071. "hideMethod": "fadeOut",
  3072. "reposition": function() {
  3073. if(PanelToggler.isVisible()) {
  3074. $("#toast-container").addClass("notification-bottom-right-center");
  3075. } else {
  3076. $("#toast-container").removeClass("notification-bottom-right-center");
  3077. }
  3078. },
  3079. "newestOnTop": false
  3080. };
  3081. SettingsMenu.init();
  3082. };
  3083. function chatAddError(errorMessage, originalText)
  3084. {
  3085. return Chat.chatAddError(errorMessage, originalText);
  3086. };
  3087. function chatSetSubject(text)
  3088. {
  3089. return Chat.chatSetSubject(text);
  3090. };
  3091. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3092. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3093. }
  3094. function onMucJoined(jid, info) {
  3095. Toolbar.updateRoomUrl(window.location.href);
  3096. var meHTML = APP.translation.generateTranslationHTML("me");
  3097. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3098. var settings = Settings.getSettings();
  3099. // Add myself to the contact list.
  3100. ContactList.addContact(jid, settings.email || settings.uid);
  3101. // Once we've joined the muc show the toolbar
  3102. ToolbarToggler.showToolbar();
  3103. var displayName = !config.displayJids
  3104. ? info.displayName : Strophe.getResourceFromJid(jid);
  3105. if (displayName)
  3106. onDisplayNameChanged('localVideoContainer', displayName);
  3107. VideoLayout.mucJoined();
  3108. }
  3109. function initEtherpad(name) {
  3110. Etherpad.init(name);
  3111. }
  3112. function onMucMemberLeft(jid) {
  3113. console.log('left.muc', jid);
  3114. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3115. '>.displayname').html();
  3116. messageHandler.notify(displayName,'notify.somebody',
  3117. 'disconnected',
  3118. 'notify.disconnected');
  3119. if(!config.startAudioMuted ||
  3120. config.startAudioMuted > APP.members.size())
  3121. UIUtil.playSoundNotification('userLeft');
  3122. // Need to call this with a slight delay, otherwise the element couldn't be
  3123. // found for some reason.
  3124. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  3125. window.setTimeout(function () {
  3126. var container = document.getElementById(
  3127. 'participant_' + Strophe.getResourceFromJid(jid));
  3128. if (container) {
  3129. ContactList.removeContact(jid);
  3130. VideoLayout.removeConnectionIndicator(jid);
  3131. // hide here, wait for video to close before removing
  3132. $(container).hide();
  3133. VideoLayout.resizeThumbnails();
  3134. }
  3135. }, 10);
  3136. VideoLayout.participantLeft(jid);
  3137. };
  3138. function onLocalRoleChanged(jid, info, pres, isModerator)
  3139. {
  3140. console.info("My role changed, new role: " + info.role);
  3141. onModeratorStatusChanged(isModerator);
  3142. VideoLayout.showModeratorIndicator();
  3143. SettingsMenu.onRoleChanged();
  3144. if (isModerator) {
  3145. Authentication.closeAuthenticationWindow();
  3146. messageHandler.notify(null, "notify.me",
  3147. 'connected', "notify.moderator");
  3148. }
  3149. }
  3150. function onModeratorStatusChanged(isModerator) {
  3151. Toolbar.showSipCallButton(isModerator);
  3152. Toolbar.showRecordingButton(
  3153. isModerator); //&&
  3154. // FIXME:
  3155. // Recording visible if
  3156. // there are at least 2(+ 1 focus) participants
  3157. //Object.keys(connection.emuc.members).length >= 3);
  3158. }
  3159. function onPasswordRequired(callback) {
  3160. // password is required
  3161. Toolbar.lockLockButton();
  3162. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3163. message += APP.translation.translateString(
  3164. "dialog.passwordRequired");
  3165. message += '</h2>' +
  3166. '<input name="lockKey" type="text" data-i18n=' +
  3167. '"[placeholder]dialog.password" placeholder="' +
  3168. APP.translation.translateString("dialog.password") +
  3169. '" autofocus>';
  3170. messageHandler.openTwoButtonDialog(null, null, null, message,
  3171. true,
  3172. "dialog.Ok",
  3173. function (e, v, m, f) {},
  3174. null,
  3175. function (e, v, m, f) {
  3176. if (v) {
  3177. var lockKey = f.lockKey;
  3178. if (lockKey) {
  3179. Toolbar.setSharedKey(lockKey);
  3180. callback(lockKey);
  3181. }
  3182. }
  3183. },
  3184. ':input:first'
  3185. );
  3186. }
  3187. /**
  3188. * The dialpad button is shown iff there is at least one member that supports
  3189. * DTMF (e.g. jigasi).
  3190. */
  3191. function onDtmfSupportChanged(dtmfSupport) {
  3192. //TODO: enable when the UI is ready
  3193. //Toolbar.showDialPadButton(dtmfSupport);
  3194. }
  3195. function onMucMemberJoined(jid, id, displayName) {
  3196. messageHandler.notify(displayName,'notify.somebody',
  3197. 'connected',
  3198. 'notify.connected');
  3199. if(!config.startAudioMuted ||
  3200. config.startAudioMuted > APP.members.size())
  3201. UIUtil.playSoundNotification('userJoined');
  3202. // Add Peer's container
  3203. VideoLayout.ensurePeerContainerExists(jid,id);
  3204. }
  3205. function onMucPresenceStatus(jid, info) {
  3206. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3207. }
  3208. function onMucRoleChanged(role, displayName) {
  3209. VideoLayout.showModeratorIndicator();
  3210. if (role === 'moderator') {
  3211. var messageKey, messageOptions = {};
  3212. if (!displayName) {
  3213. messageKey = "notify.grantedToUnknown";
  3214. }
  3215. else
  3216. {
  3217. messageKey = "notify.grantedTo";
  3218. messageOptions = {to: displayName};
  3219. }
  3220. messageHandler.notify(
  3221. displayName,'notify.somebody',
  3222. 'connected', messageKey,
  3223. messageOptions);
  3224. }
  3225. }
  3226. function onAuthenticationRequired(intervalCallback) {
  3227. Authentication.openAuthenticationDialog(
  3228. roomName, intervalCallback, function () {
  3229. Toolbar.authenticateClicked();
  3230. });
  3231. };
  3232. function onLastNChanged(oldValue, newValue) {
  3233. if (config.muteLocalVideoIfNotInLastN) {
  3234. setVideoMute(!newValue, { 'byUser': false });
  3235. }
  3236. }
  3237. UI.toggleSmileys = function () {
  3238. Chat.toggleSmileys();
  3239. };
  3240. UI.getSettings = function () {
  3241. return Settings.getSettings();
  3242. };
  3243. UI.toggleFilmStrip = function () {
  3244. return BottomToolbar.toggleFilmStrip();
  3245. };
  3246. UI.toggleChat = function () {
  3247. return BottomToolbar.toggleChat();
  3248. };
  3249. UI.toggleContactList = function () {
  3250. return BottomToolbar.toggleContactList();
  3251. };
  3252. UI.inputDisplayNameHandler = function (value) {
  3253. VideoLayout.inputDisplayNameHandler(value);
  3254. };
  3255. UI.getLargeVideoJid = function()
  3256. {
  3257. return VideoLayout.getLargeVideoJid();
  3258. };
  3259. UI.generateRoomName = function() {
  3260. if(roomName)
  3261. return roomName;
  3262. var roomnode = null;
  3263. var path = window.location.pathname;
  3264. // determinde the room node from the url
  3265. // TODO: just the roomnode or the whole bare jid?
  3266. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3267. // custom function might be responsible for doing the pushstate
  3268. roomnode = config.getroomnode(path);
  3269. } else {
  3270. /* fall back to default strategy
  3271. * this is making assumptions about how the URL->room mapping happens.
  3272. * It currently assumes deployment at root, with a rewrite like the
  3273. * following one (for nginx):
  3274. location ~ ^/([a-zA-Z0-9]+)$ {
  3275. rewrite ^/(.*)$ / break;
  3276. }
  3277. */
  3278. if (path.length > 1) {
  3279. roomnode = path.substr(1).toLowerCase();
  3280. } else {
  3281. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3282. roomnode = word.toLowerCase();
  3283. window.history.pushState('VideoChat',
  3284. 'Room: ' + word, window.location.pathname + word);
  3285. }
  3286. }
  3287. roomName = roomnode + '@' + config.hosts.muc;
  3288. return roomName;
  3289. };
  3290. UI.connectionIndicatorShowMore = function(jid)
  3291. {
  3292. return VideoLayout.showMore(jid);
  3293. };
  3294. UI.showLoginPopup = function(callback)
  3295. {
  3296. console.log('password is required');
  3297. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3298. message += APP.translation.translateString(
  3299. "dialog.passwordRequired");
  3300. message += '</h2>' +
  3301. '<input name="username" type="text" ' +
  3302. 'placeholder="user@domain.net" autofocus>' +
  3303. '<input name="password" ' +
  3304. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3305. ' placeholder="user password">';
  3306. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3307. true,
  3308. "dialog.Ok",
  3309. function (e, v, m, f) {
  3310. if (v) {
  3311. if (f.username !== null && f.password != null) {
  3312. callback(f.username, f.password);
  3313. }
  3314. }
  3315. },
  3316. null, null, ':input:first'
  3317. );
  3318. }
  3319. UI.checkForNicknameAndJoin = function () {
  3320. Authentication.closeAuthenticationDialog();
  3321. Authentication.stopInterval();
  3322. var nick = null;
  3323. if (config.useNicks) {
  3324. nick = window.prompt('Your nickname (optional)');
  3325. }
  3326. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3327. };
  3328. function dump(elem, filename) {
  3329. elem = elem.parentNode;
  3330. elem.download = filename || 'meetlog.json';
  3331. elem.href = 'data:application/json;charset=utf-8,\n';
  3332. var data = APP.xmpp.populateData();
  3333. var metadata = {};
  3334. metadata.time = new Date();
  3335. metadata.url = window.location.href;
  3336. metadata.ua = navigator.userAgent;
  3337. var log = APP.xmpp.getLogger();
  3338. if (log) {
  3339. metadata.xmpp = log;
  3340. }
  3341. data.metadata = metadata;
  3342. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3343. return false;
  3344. }
  3345. UI.getRoomName = function () {
  3346. return roomName;
  3347. };
  3348. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3349. if(muteAudio || muteVideo) notifyForInitialMute();
  3350. if(muteAudio) UI.setAudioMuted(true);
  3351. if(muteVideo) UI.setVideoMute(true);
  3352. }
  3353. /**
  3354. * Mutes/unmutes the local video.
  3355. */
  3356. UI.toggleVideo = function () {
  3357. setVideoMute(!APP.RTC.localVideo.isMuted());
  3358. };
  3359. /**
  3360. * Mutes / unmutes audio for the local participant.
  3361. */
  3362. UI.toggleAudio = function() {
  3363. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3364. };
  3365. /**
  3366. * Sets muted audio state for the local participant.
  3367. */
  3368. UI.setAudioMuted = function (mute, earlyMute) {
  3369. var audioMute = null;
  3370. if(earlyMute)
  3371. audioMute = function (mute, cb) {
  3372. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3373. };
  3374. else
  3375. audioMute = function (mute, cb) {
  3376. return APP.xmpp.setAudioMute(mute, cb);
  3377. }
  3378. if(!audioMute(mute, function () {
  3379. VideoLayout.showLocalAudioIndicator(mute);
  3380. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3381. }))
  3382. {
  3383. // We still click the button.
  3384. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3385. return;
  3386. }
  3387. }
  3388. UI.addListener = function (type, listener) {
  3389. eventEmitter.on(type, listener);
  3390. }
  3391. UI.clickOnVideo = function (videoNumber) {
  3392. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3393. if (remoteVideos.length > videoNumber) {
  3394. remoteVideos[videoNumber].click();
  3395. }
  3396. }
  3397. //Used by torture
  3398. UI.showToolbar = function () {
  3399. return ToolbarToggler.showToolbar();
  3400. }
  3401. //Used by torture
  3402. UI.dockToolbar = function (isDock) {
  3403. return ToolbarToggler.dockToolbar(isDock);
  3404. }
  3405. UI.setVideoMuteButtonsState = function (mute) {
  3406. var video = $('#video');
  3407. var communicativeClass = "icon-camera";
  3408. var muteClass = "icon-camera icon-camera-disabled";
  3409. if (mute) {
  3410. video.removeClass(communicativeClass);
  3411. video.addClass(muteClass);
  3412. } else {
  3413. video.removeClass(muteClass);
  3414. video.addClass(communicativeClass);
  3415. }
  3416. }
  3417. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3418. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3419. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3420. if(resourceJid === APP.xmpp.myResource())
  3421. SettingsMenu.changeAvatar(thumbUrl);
  3422. }
  3423. UI.setVideoMute = setVideoMute;
  3424. module.exports = UI;
  3425. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes":105,"../../service/connectionquality/CQEvents":108,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../../service/members/Events":110,"../../service/xmpp/XMPPEvents":112,"../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":113}],12:[function(require,module,exports){
  3426. var CanvasUtil = require("./CanvasUtils");
  3427. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3428. function initActiveSpeakerAudioLevels() {
  3429. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3430. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3431. // Draw a circle.
  3432. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3433. // Add a shadow around the circle
  3434. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3435. ASDrawContext.shadowOffsetX = 0;
  3436. ASDrawContext.shadowOffsetY = 0;
  3437. }
  3438. /**
  3439. * The audio Levels plugin.
  3440. */
  3441. var AudioLevels = (function(my) {
  3442. var audioLevelCanvasCache = {};
  3443. my.LOCAL_LEVEL = 'local';
  3444. my.init = function () {
  3445. initActiveSpeakerAudioLevels();
  3446. }
  3447. /**
  3448. * Updates the audio level canvas for the given peerJid. If the canvas
  3449. * didn't exist we create it.
  3450. */
  3451. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3452. var resourceJid = null;
  3453. var videoSpanId = null;
  3454. if (!peerJid)
  3455. videoSpanId = 'localVideoContainer';
  3456. else {
  3457. resourceJid = Strophe.getResourceFromJid(peerJid);
  3458. videoSpanId = 'participant_' + resourceJid;
  3459. }
  3460. var videoSpan = document.getElementById(videoSpanId);
  3461. if (!videoSpan) {
  3462. if (resourceJid)
  3463. console.error("No video element for jid", resourceJid);
  3464. else
  3465. console.error("No video element for local video.");
  3466. return;
  3467. }
  3468. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3469. var videoSpaceWidth = $('#remoteVideos').width();
  3470. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3471. var thumbnailWidth = thumbnailSize[0];
  3472. var thumbnailHeight = thumbnailSize[1];
  3473. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3474. audioLevelCanvas = document.createElement('canvas');
  3475. audioLevelCanvas.className = "audiolevel";
  3476. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3477. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3478. resizeAudioLevelCanvas( audioLevelCanvas,
  3479. thumbnailWidth,
  3480. thumbnailHeight);
  3481. videoSpan.appendChild(audioLevelCanvas);
  3482. } else {
  3483. audioLevelCanvas = audioLevelCanvas.get(0);
  3484. resizeAudioLevelCanvas( audioLevelCanvas,
  3485. thumbnailWidth,
  3486. thumbnailHeight);
  3487. }
  3488. };
  3489. /**
  3490. * Updates the audio level UI for the given resourceJid.
  3491. *
  3492. * @param resourceJid the resource jid indicating the video element for
  3493. * which we draw the audio level
  3494. * @param audioLevel the newAudio level to render
  3495. */
  3496. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3497. drawAudioLevelCanvas(resourceJid, audioLevel);
  3498. var videoSpanId = getVideoSpanId(resourceJid);
  3499. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3500. if (!audioLevelCanvas)
  3501. return;
  3502. var drawContext = audioLevelCanvas.getContext('2d');
  3503. var canvasCache = audioLevelCanvasCache[resourceJid];
  3504. drawContext.clearRect (0, 0,
  3505. audioLevelCanvas.width, audioLevelCanvas.height);
  3506. drawContext.drawImage(canvasCache, 0, 0);
  3507. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3508. if(!APP.xmpp.myJid()) {
  3509. return;
  3510. }
  3511. resourceJid = APP.xmpp.myResource();
  3512. }
  3513. if(resourceJid === largeVideoResourceJid) {
  3514. window.requestAnimationFrame(function () {
  3515. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3516. });
  3517. }
  3518. };
  3519. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3520. if($("#activeSpeaker").css("visibility") == "hidden")
  3521. return;
  3522. ASDrawContext.clearRect(0, 0, 300, 300);
  3523. if(audioLevel == 0)
  3524. return;
  3525. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3526. // Fill the shape.
  3527. ASDrawContext.fill();
  3528. };
  3529. /**
  3530. * Resizes the given audio level canvas to match the given thumbnail size.
  3531. */
  3532. function resizeAudioLevelCanvas(audioLevelCanvas,
  3533. thumbnailWidth,
  3534. thumbnailHeight) {
  3535. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3536. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3537. }
  3538. /**
  3539. * Draws the audio level canvas into the cached canvas object.
  3540. *
  3541. * @param resourceJid the resource jid indicating the video element for
  3542. * which we draw the audio level
  3543. * @param audioLevel the newAudio level to render
  3544. */
  3545. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3546. if (!audioLevelCanvasCache[resourceJid]) {
  3547. var videoSpanId = getVideoSpanId(resourceJid);
  3548. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3549. /*
  3550. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3551. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3552. * error. Since audio levels are frequently updated, the errors have
  3553. * been observed to pile into the console, strain the CPU.
  3554. */
  3555. if (audioLevelCanvasOrig)
  3556. {
  3557. audioLevelCanvasCache[resourceJid]
  3558. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3559. }
  3560. }
  3561. var canvas = audioLevelCanvasCache[resourceJid];
  3562. if (!canvas)
  3563. return;
  3564. var drawContext = canvas.getContext('2d');
  3565. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3566. var shadowLevel = getShadowLevel(audioLevel);
  3567. if (shadowLevel > 0)
  3568. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3569. CanvasUtil.drawRoundRectGlow( drawContext,
  3570. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  3571. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3572. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3573. interfaceConfig.CANVAS_RADIUS,
  3574. interfaceConfig.SHADOW_COLOR,
  3575. shadowLevel);
  3576. }
  3577. /**
  3578. * Returns the shadow/glow level for the given audio level.
  3579. *
  3580. * @param audioLevel the audio level from which we determine the shadow
  3581. * level
  3582. */
  3583. function getShadowLevel (audioLevel) {
  3584. var shadowLevel = 0;
  3585. if (audioLevel <= 0.3) {
  3586. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3587. }
  3588. else if (audioLevel <= 0.6) {
  3589. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3590. }
  3591. else {
  3592. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3593. }
  3594. return shadowLevel;
  3595. }
  3596. /**
  3597. * Returns the video span id corresponding to the given resourceJid or local
  3598. * user.
  3599. */
  3600. function getVideoSpanId(resourceJid) {
  3601. var videoSpanId = null;
  3602. if (resourceJid === AudioLevels.LOCAL_LEVEL
  3603. || (APP.xmpp.myResource() && resourceJid
  3604. === APP.xmpp.myResource()))
  3605. videoSpanId = 'localVideoContainer';
  3606. else
  3607. videoSpanId = 'participant_' + resourceJid;
  3608. return videoSpanId;
  3609. }
  3610. /**
  3611. * Indicates that the remote video has been resized.
  3612. */
  3613. $(document).bind('remotevideo.resized', function (event, width, height) {
  3614. var resized = false;
  3615. $('#remoteVideos>span>canvas').each(function() {
  3616. var canvas = $(this).get(0);
  3617. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3618. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3619. resized = true;
  3620. }
  3621. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3622. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3623. resized = true;
  3624. }
  3625. });
  3626. if (resized)
  3627. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3628. audioLevelCanvasCache[resourceJid].width
  3629. = width + interfaceConfig.CANVAS_EXTRA;
  3630. audioLevelCanvasCache[resourceJid].height
  3631. = height + interfaceConfig.CANVAS_EXTRA;
  3632. });
  3633. });
  3634. return my;
  3635. })(AudioLevels || {});
  3636. module.exports = AudioLevels;
  3637. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3638. /**
  3639. * Utility class for drawing canvas shapes.
  3640. */
  3641. var CanvasUtil = (function(my) {
  3642. /**
  3643. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3644. * of the glow.
  3645. *
  3646. * @param drawContext the context of the canvas to draw to
  3647. * @param x the x coordinate of the round rectangle
  3648. * @param y the y coordinate of the round rectangle
  3649. * @param w the width of the round rectangle
  3650. * @param h the height of the round rectangle
  3651. * @param glowColor the color of the glow
  3652. * @param glowWidth the width of the glow
  3653. */
  3654. my.drawRoundRectGlow
  3655. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3656. // Save the previous state of the context.
  3657. drawContext.save();
  3658. if (w < 2 * r) r = w / 2;
  3659. if (h < 2 * r) r = h / 2;
  3660. // Draw a round rectangle.
  3661. drawContext.beginPath();
  3662. drawContext.moveTo(x+r, y);
  3663. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3664. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3665. drawContext.arcTo(x, y+h, x, y, r);
  3666. drawContext.arcTo(x, y, x+w, y, r);
  3667. drawContext.closePath();
  3668. // Add a shadow around the rectangle
  3669. drawContext.shadowColor = glowColor;
  3670. drawContext.shadowBlur = glowWidth;
  3671. drawContext.shadowOffsetX = 0;
  3672. drawContext.shadowOffsetY = 0;
  3673. // Fill the shape.
  3674. drawContext.fill();
  3675. drawContext.save();
  3676. drawContext.restore();
  3677. // 1) Uncomment this line to use Composite Operation, which is doing the
  3678. // same as the clip function below and is also antialiasing the round
  3679. // border, but is said to be less fast performance wise.
  3680. // drawContext.globalCompositeOperation='destination-out';
  3681. drawContext.beginPath();
  3682. drawContext.moveTo(x+r, y);
  3683. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3684. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3685. drawContext.arcTo(x, y+h, x, y, r);
  3686. drawContext.arcTo(x, y, x+w, y, r);
  3687. drawContext.closePath();
  3688. // 2) Uncomment this line to use Composite Operation, which is doing the
  3689. // same as the clip function below and is also antialiasing the round
  3690. // border, but is said to be less fast performance wise.
  3691. // drawContext.fill();
  3692. // Comment these two lines if choosing to do the same with composite
  3693. // operation above 1 and 2.
  3694. drawContext.clip();
  3695. drawContext.clearRect(0, 0, 277, 200);
  3696. // Restore the previous context state.
  3697. drawContext.restore();
  3698. };
  3699. /**
  3700. * Clones the given canvas.
  3701. *
  3702. * @return the new cloned canvas.
  3703. */
  3704. my.cloneCanvas = function (oldCanvas) {
  3705. /*
  3706. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3707. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3708. * levels are frequently updated, the errors have been observed to pile
  3709. * into the console, strain the CPU.
  3710. */
  3711. if (!oldCanvas)
  3712. return oldCanvas;
  3713. //create a new canvas
  3714. var newCanvas = document.createElement('canvas');
  3715. var context = newCanvas.getContext('2d');
  3716. //set dimensions
  3717. newCanvas.width = oldCanvas.width;
  3718. newCanvas.height = oldCanvas.height;
  3719. //apply the old canvas to the new one
  3720. context.drawImage(oldCanvas, 0, 0);
  3721. //return the new canvas
  3722. return newCanvas;
  3723. };
  3724. return my;
  3725. })(CanvasUtil || {});
  3726. module.exports = CanvasUtil;
  3727. },{}],14:[function(require,module,exports){
  3728. /* global $, APP*/
  3729. var LoginDialog = require('./LoginDialog');
  3730. var Moderator = require('../../xmpp/moderator');
  3731. /* Initial "authentication required" dialog */
  3732. var authDialog = null;
  3733. /* Loop retry ID that wits for other user to create the room */
  3734. var authRetryId = null;
  3735. var authenticationWindow = null;
  3736. var Authentication = {
  3737. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3738. // This is the loop that will wait for the room to be created by
  3739. // someone else. 'auth_required.moderator' will bring us back here.
  3740. authRetryId = window.setTimeout(intervalCallback, 5000);
  3741. // Show prompt only if it's not open
  3742. if (authDialog !== null) {
  3743. return;
  3744. }
  3745. // extract room name from 'room@muc.server.net'
  3746. var room = roomName.substr(0, roomName.indexOf('@'));
  3747. var title
  3748. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3749. var msg
  3750. = APP.translation.generateTranslationHTML(
  3751. "dialog.WaitForHostMsg", {room: room});
  3752. var buttonTxt
  3753. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3754. var buttons = [];
  3755. buttons.push({title: buttonTxt, value: "authNow"});
  3756. authDialog = APP.UI.messageHandler.openDialog(
  3757. title,
  3758. msg,
  3759. true,
  3760. buttons,
  3761. function (onSubmitEvent, submitValue) {
  3762. // Do not close the dialog yet
  3763. onSubmitEvent.preventDefault();
  3764. // Open login popup
  3765. if (submitValue === 'authNow') {
  3766. callback();
  3767. }
  3768. }
  3769. );
  3770. },
  3771. closeAuthenticationWindow: function () {
  3772. if (authenticationWindow) {
  3773. authenticationWindow.close();
  3774. authenticationWindow = null;
  3775. }
  3776. },
  3777. xmppAuthenticate: function () {
  3778. var loginDialog = LoginDialog.show(
  3779. function (connection, state) {
  3780. if (!state) {
  3781. // User cancelled
  3782. loginDialog.close();
  3783. return;
  3784. } else if (state == APP.xmpp.Status.CONNECTED) {
  3785. loginDialog.close();
  3786. Authentication.stopInterval();
  3787. Authentication.closeAuthenticationDialog();
  3788. // Close the connection as anonymous one will be used
  3789. // to create the conference. Session-id will authorize
  3790. // the request.
  3791. connection.disconnect();
  3792. var roomName = APP.UI.generateRoomName();
  3793. Moderator.allocateConferenceFocus(roomName, function () {
  3794. // If it's not "on the fly" authentication now join
  3795. // the conference room
  3796. if (!APP.xmpp.getMUCJoined()) {
  3797. APP.UI.checkForNicknameAndJoin();
  3798. }
  3799. });
  3800. }
  3801. }, true);
  3802. },
  3803. focusAuthenticationWindow: function () {
  3804. // If auth window exists just bring it to the front
  3805. if (authenticationWindow) {
  3806. authenticationWindow.focus();
  3807. return;
  3808. }
  3809. },
  3810. closeAuthenticationDialog: function () {
  3811. // Close authentication dialog if opened
  3812. if (authDialog) {
  3813. authDialog.close();
  3814. authDialog = null;
  3815. }
  3816. },
  3817. createAuthenticationWindow: function (callback, url) {
  3818. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3819. url, 910, 660,
  3820. // On closed
  3821. function () {
  3822. // Close authentication dialog if opened
  3823. Authentication.closeAuthenticationDialog();
  3824. callback();
  3825. authenticationWindow = null;
  3826. });
  3827. return authenticationWindow;
  3828. },
  3829. stopInterval: function () {
  3830. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3831. if (authRetryId) {
  3832. window.clearTimeout(authRetryId);
  3833. authRetryId = null;
  3834. }
  3835. }
  3836. };
  3837. module.exports = Authentication;
  3838. },{"../../xmpp/moderator":58,"./LoginDialog":15}],15:[function(require,module,exports){
  3839. /* global $, APP, config*/
  3840. var XMPP = require('../../xmpp/xmpp');
  3841. var Moderator = require('../../xmpp/moderator');
  3842. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3843. // anonymous domain is not enabled
  3844. /**
  3845. * Creates new <tt>Dialog</tt> instance.
  3846. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3847. * when we either fail to connect or succeed(check Strophe.Status).
  3848. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3849. * in order to create session-id after the connection is established.
  3850. * @constructor
  3851. */
  3852. function Dialog(callback, obtainSession) {
  3853. var self = this;
  3854. var stop = false;
  3855. var connection = APP.xmpp.createConnection();
  3856. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3857. message += APP.translation.translateString("dialog.passwordRequired");
  3858. message += '</h2>' +
  3859. '<input name="username" type="text" ' +
  3860. 'placeholder="user@domain.net" autofocus>' +
  3861. '<input name="password" ' +
  3862. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3863. ' placeholder="user password">';
  3864. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3865. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3866. var states = {
  3867. login: {
  3868. html: message,
  3869. buttons: [
  3870. { title: okButton, value: true},
  3871. { title: cancelButton, value: false}
  3872. ],
  3873. focus: ':input:first',
  3874. submit: function (e, v, m, f) {
  3875. e.preventDefault();
  3876. if (v) {
  3877. var jid = f.username;
  3878. var password = f.password;
  3879. if (jid && password) {
  3880. stop = false;
  3881. connection.reset();
  3882. connDialog.goToState('connecting');
  3883. connection.connect(jid, password, stateHandler);
  3884. }
  3885. } else {
  3886. // User cancelled
  3887. stop = true;
  3888. callback();
  3889. }
  3890. }
  3891. },
  3892. connecting: {
  3893. title: APP.translation.translateString('dialog.connecting'),
  3894. html: '<div id="connectionStatus"></div>',
  3895. buttons: [],
  3896. defaultButton: 0
  3897. },
  3898. finished: {
  3899. title: APP.translation.translateString('dialog.error'),
  3900. html: '<div id="errorMessage"></div>',
  3901. buttons: [
  3902. {
  3903. title: APP.translation.translateString('dialog.retry'),
  3904. value: 'retry'
  3905. },
  3906. {
  3907. title: APP.translation.translateString('dialog.Cancel'),
  3908. value: 'cancel'
  3909. },
  3910. ],
  3911. defaultButton: 0,
  3912. submit: function (e, v, m, f) {
  3913. e.preventDefault();
  3914. if (v === 'retry')
  3915. connDialog.goToState('login');
  3916. else
  3917. callback();
  3918. }
  3919. }
  3920. };
  3921. var connDialog
  3922. = APP.UI.messageHandler.openDialogWithStates(states,
  3923. { persistent: true, closeText: '' }, null);
  3924. var stateHandler = function (status, message) {
  3925. if (stop) {
  3926. return;
  3927. }
  3928. var translateKey = "connection." + XMPP.getStatusString(status);
  3929. var statusStr = APP.translation.translateString(translateKey);
  3930. // Display current state
  3931. var connectionStatus =
  3932. connDialog.getState('connecting').find('#connectionStatus');
  3933. connectionStatus.text(statusStr);
  3934. switch (status) {
  3935. case XMPP.Status.CONNECTED:
  3936. stop = true;
  3937. if (!obtainSession) {
  3938. callback(connection, status);
  3939. return;
  3940. }
  3941. // Obtaining session-id status
  3942. connectionStatus.text(
  3943. APP.translation.translateString(
  3944. 'connection.FETCH_SESSION_ID'));
  3945. // Authenticate with Jicofo and obtain session-id
  3946. var roomName = APP.UI.generateRoomName();
  3947. // Jicofo will return new session-id when connected
  3948. // from authenticated domain
  3949. connection.sendIQ(
  3950. Moderator.createConferenceIq(roomName),
  3951. function (result) {
  3952. connectionStatus.text(
  3953. APP.translation.translateString(
  3954. 'connection.GOT_SESSION_ID'));
  3955. stop = true;
  3956. // Parse session-id
  3957. Moderator.parseSessionId(result);
  3958. callback(connection, status);
  3959. },
  3960. function (error) {
  3961. console.error("Auth on the fly failed", error);
  3962. stop = true;
  3963. var errorMsg =
  3964. APP.translation.translateString(
  3965. 'connection.GET_SESSION_ID_ERROR') +
  3966. $(error).find('>error').attr('code');
  3967. self.displayError(errorMsg);
  3968. connection.disconnect();
  3969. });
  3970. break;
  3971. case XMPP.Status.AUTHFAIL:
  3972. case XMPP.Status.CONNFAIL:
  3973. case XMPP.Status.DISCONNECTED:
  3974. stop = true;
  3975. callback(connection, status);
  3976. var errorMessage = statusStr;
  3977. if (message)
  3978. {
  3979. errorMessage += ': ' + message;
  3980. }
  3981. self.displayError(errorMessage);
  3982. break;
  3983. default:
  3984. break;
  3985. }
  3986. };
  3987. /**
  3988. * Displays error message in 'finished' state which allows either to cancel
  3989. * or retry.
  3990. * @param message the final message to be displayed.
  3991. */
  3992. this.displayError = function (message) {
  3993. var finishedState = connDialog.getState('finished');
  3994. var errorMessageElem = finishedState.find('#errorMessage');
  3995. errorMessageElem.text(message);
  3996. connDialog.goToState('finished');
  3997. };
  3998. /**
  3999. * Closes LoginDialog.
  4000. */
  4001. this.close = function () {
  4002. stop = true;
  4003. connDialog.close();
  4004. };
  4005. }
  4006. var LoginDialog = {
  4007. /**
  4008. * Displays login prompt used to establish new XMPP connection. Given
  4009. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4010. * called when we connect successfully(status === CONNECTED) or when we fail
  4011. * to do so. On connection failure program can call Dialog.close() method in
  4012. * order to cancel or do nothing to let the user retry.
  4013. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4014. * called when we either fail to connect or succeed(check
  4015. * Strophe.Status).
  4016. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4017. * Jicofo in order to create session-id after the connection is
  4018. * established.
  4019. * @returns {Dialog}
  4020. */
  4021. show: function (callback, obtainSession) {
  4022. return new Dialog(callback, obtainSession);
  4023. }
  4024. };
  4025. module.exports = LoginDialog;
  4026. },{"../../xmpp/moderator":58,"../../xmpp/xmpp":66}],16:[function(require,module,exports){
  4027. var Settings = require("../../settings/Settings");
  4028. var users = {};
  4029. var Avatar = {
  4030. /**
  4031. * Sets the user's avatar in the settings menu(if local user), contact list
  4032. * and thumbnail
  4033. * @param jid jid of the user
  4034. * @param id email or userID to be used as a hash
  4035. */
  4036. setUserAvatar: function (jid, id) {
  4037. if (id) {
  4038. if (users[jid] === id) {
  4039. return;
  4040. }
  4041. users[jid] = id;
  4042. }
  4043. var thumbUrl = this.getGravatarUrl(users[jid] || jid, 100);
  4044. var contactListUrl = this.getGravatarUrl(users[jid] || jid);
  4045. var resourceJid = Strophe.getResourceFromJid(jid);
  4046. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4047. },
  4048. getGravatarUrl: function (id, size) {
  4049. if(id === APP.xmpp.myJid() || !id) {
  4050. id = Settings.getSettings().uid;
  4051. }
  4052. return 'https://www.gravatar.com/avatar/' +
  4053. MD5.hexdigest(id.trim().toLowerCase()) +
  4054. "?d=wavatar&size=" + (size || "30");
  4055. }
  4056. };
  4057. module.exports = Avatar;
  4058. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4059. /* global $, config,
  4060. setLargeVideoVisible, Util */
  4061. var VideoLayout = require("../videolayout/VideoLayout");
  4062. var Prezi = require("../prezi/Prezi");
  4063. var UIUtil = require("../util/UIUtil");
  4064. var etherpadName = null;
  4065. var etherpadIFrame = null;
  4066. var domain = null;
  4067. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4068. /**
  4069. * Resizes the etherpad.
  4070. */
  4071. function resize() {
  4072. if ($('#etherpad>iframe').length) {
  4073. var remoteVideos = $('#remoteVideos');
  4074. var availableHeight
  4075. = window.innerHeight - remoteVideos.outerHeight();
  4076. var availableWidth = UIUtil.getAvailableVideoWidth();
  4077. $('#etherpad>iframe').width(availableWidth);
  4078. $('#etherpad>iframe').height(availableHeight);
  4079. }
  4080. }
  4081. /**
  4082. * Creates the Etherpad button and adds it to the toolbar.
  4083. */
  4084. function enableEtherpadButton() {
  4085. if (!$('#etherpadButton').is(":visible"))
  4086. $('#etherpadButton').css({display: 'inline-block'});
  4087. }
  4088. /**
  4089. * Creates the IFrame for the etherpad.
  4090. */
  4091. function createIFrame() {
  4092. etherpadIFrame = document.createElement('iframe');
  4093. etherpadIFrame.src = domain + etherpadName + options;
  4094. etherpadIFrame.frameBorder = 0;
  4095. etherpadIFrame.scrolling = "no";
  4096. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  4097. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  4098. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  4099. document.getElementById('etherpad').appendChild(etherpadIFrame);
  4100. etherpadIFrame.onload = function() {
  4101. document.domain = document.domain;
  4102. bubbleIframeMouseMove(etherpadIFrame);
  4103. setTimeout(function() {
  4104. // the iframes inside of the etherpad are
  4105. // not yet loaded when the etherpad iframe is loaded
  4106. var outer = etherpadIFrame.
  4107. contentDocument.getElementsByName("ace_outer")[0];
  4108. bubbleIframeMouseMove(outer);
  4109. var inner = outer.
  4110. contentDocument.getElementsByName("ace_inner")[0];
  4111. bubbleIframeMouseMove(inner);
  4112. }, 2000);
  4113. };
  4114. }
  4115. function bubbleIframeMouseMove(iframe){
  4116. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4117. iframe.contentWindow.onmousemove = function(e){
  4118. if(existingOnMouseMove) existingOnMouseMove(e);
  4119. var evt = document.createEvent("MouseEvents");
  4120. var boundingClientRect = iframe.getBoundingClientRect();
  4121. evt.initMouseEvent(
  4122. "mousemove",
  4123. true, // bubbles
  4124. false, // not cancelable
  4125. window,
  4126. e.detail,
  4127. e.screenX,
  4128. e.screenY,
  4129. e.clientX + boundingClientRect.left,
  4130. e.clientY + boundingClientRect.top,
  4131. e.ctrlKey,
  4132. e.altKey,
  4133. e.shiftKey,
  4134. e.metaKey,
  4135. e.button,
  4136. null // no related element
  4137. );
  4138. iframe.dispatchEvent(evt);
  4139. };
  4140. }
  4141. /**
  4142. * On video selected event.
  4143. */
  4144. $(document).bind('video.selected', function (event, isPresentation) {
  4145. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  4146. Etherpad.toggleEtherpad(isPresentation);
  4147. });
  4148. var Etherpad = {
  4149. /**
  4150. * Initializes the etherpad.
  4151. */
  4152. init: function (name) {
  4153. if (config.etherpad_base && !etherpadName && name) {
  4154. domain = config.etherpad_base;
  4155. etherpadName = name;
  4156. enableEtherpadButton();
  4157. /**
  4158. * Resizes the etherpad, when the window is resized.
  4159. */
  4160. $(window).resize(function () {
  4161. resize();
  4162. });
  4163. }
  4164. },
  4165. /**
  4166. * Opens/hides the Etherpad.
  4167. */
  4168. toggleEtherpad: function (isPresentation) {
  4169. if (!etherpadIFrame)
  4170. createIFrame();
  4171. var largeVideo = null;
  4172. if (Prezi.isPresentationVisible())
  4173. largeVideo = $('#presentation>iframe');
  4174. else
  4175. largeVideo = $('#largeVideo');
  4176. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  4177. $('#activeSpeaker').css('visibility', 'hidden');
  4178. largeVideo.fadeOut(300, function () {
  4179. if (Prezi.isPresentationVisible()) {
  4180. largeVideo.css({opacity: '0'});
  4181. } else {
  4182. VideoLayout.setLargeVideoVisible(false);
  4183. }
  4184. });
  4185. $('#etherpad>iframe').fadeIn(300, function () {
  4186. document.body.style.background = '#eeeeee';
  4187. $('#etherpad>iframe').css({visibility: 'visible'});
  4188. $('#etherpad').css({zIndex: 2});
  4189. });
  4190. }
  4191. else if ($('#etherpad>iframe')) {
  4192. $('#etherpad>iframe').fadeOut(300, function () {
  4193. $('#etherpad>iframe').css({visibility: 'hidden'});
  4194. $('#etherpad').css({zIndex: 0});
  4195. document.body.style.background = 'black';
  4196. });
  4197. if (!isPresentation) {
  4198. $('#largeVideo').fadeIn(300, function () {
  4199. VideoLayout.setLargeVideoVisible(true);
  4200. });
  4201. }
  4202. }
  4203. resize();
  4204. },
  4205. isVisible: function() {
  4206. var etherpadIframe = $('#etherpad>iframe');
  4207. return etherpadIframe && etherpadIframe.is(':visible');
  4208. }
  4209. };
  4210. module.exports = Etherpad;
  4211. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4212. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4213. var UIUtil = require("../util/UIUtil");
  4214. var VideoLayout = require("../videolayout/VideoLayout");
  4215. var messageHandler = require("../util/MessageHandler");
  4216. var PreziPlayer = require("./PreziPlayer");
  4217. var preziPlayer = null;
  4218. var Prezi = {
  4219. /**
  4220. * Reloads the current presentation.
  4221. */
  4222. reloadPresentation: function() {
  4223. var iframe = document.getElementById(preziPlayer.options.preziId);
  4224. iframe.src = iframe.src;
  4225. },
  4226. /**
  4227. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4228. * otherwise.
  4229. */
  4230. isPresentationVisible: function () {
  4231. return ($('#presentation>iframe') != null
  4232. && $('#presentation>iframe').css('opacity') == 1);
  4233. },
  4234. /**
  4235. * Opens the Prezi dialog, from which the user could choose a presentation
  4236. * to load.
  4237. */
  4238. openPreziDialog: function() {
  4239. var myprezi = APP.xmpp.getPrezi();
  4240. if (myprezi) {
  4241. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4242. null,
  4243. "dialog.removePreziMsg",
  4244. null,
  4245. false,
  4246. "dialog.Remove",
  4247. function(e,v,m,f) {
  4248. if(v) {
  4249. APP.xmpp.removePreziFromPresence();
  4250. }
  4251. }
  4252. );
  4253. }
  4254. else if (preziPlayer != null) {
  4255. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4256. null, "dialog.sharePreziMsg",
  4257. null,
  4258. false,
  4259. "dialog.Ok",
  4260. function(e,v,m,f) {
  4261. $.prompt.close();
  4262. }
  4263. );
  4264. }
  4265. else {
  4266. var html = APP.translation.generateTranslationHTML(
  4267. "dialog.sharePreziTitle");
  4268. var cancelButton = APP.translation.generateTranslationHTML(
  4269. "dialog.Cancel");
  4270. var shareButton = APP.translation.generateTranslationHTML(
  4271. "dialog.Share");
  4272. var backButton = APP.translation.generateTranslationHTML(
  4273. "dialog.Back");
  4274. var buttons = [];
  4275. var buttons1 = [];
  4276. // Cancel button to both states
  4277. buttons.push({title: cancelButton, value: false});
  4278. buttons1.push({title: cancelButton, value: false});
  4279. // Share button
  4280. buttons.push({title: shareButton, value: true});
  4281. // Back button
  4282. buttons1.push({title: backButton, value: true});
  4283. var linkError = APP.translation.generateTranslationHTML(
  4284. "dialog.preziLinkError");
  4285. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4286. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4287. var openPreziState = {
  4288. state0: {
  4289. html: '<h2>' + html + '</h2>' +
  4290. '<input name="preziUrl" type="text" ' +
  4291. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4292. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4293. '\' placeholder="' + defaultUrl + '" autofocus>',
  4294. persistent: false,
  4295. buttons: buttons,
  4296. focus: ':input:first',
  4297. defaultButton: 0,
  4298. submit: function (e, v, m, f) {
  4299. e.preventDefault();
  4300. if(v)
  4301. {
  4302. var preziUrl = f.preziUrl;
  4303. if (preziUrl)
  4304. {
  4305. var urlValue
  4306. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4307. if (urlValue.indexOf('http://prezi.com/') != 0
  4308. && urlValue.indexOf('https://prezi.com/') != 0)
  4309. {
  4310. $.prompt.goToState('state1');
  4311. return false;
  4312. }
  4313. else {
  4314. var presIdTmp = urlValue.substring(
  4315. urlValue.indexOf("prezi.com/") + 10);
  4316. if (!isAlphanumeric(presIdTmp)
  4317. || presIdTmp.indexOf('/') < 2) {
  4318. $.prompt.goToState('state1');
  4319. return false;
  4320. }
  4321. else {
  4322. APP.xmpp.addToPresence("prezi", urlValue);
  4323. $.prompt.close();
  4324. }
  4325. }
  4326. }
  4327. }
  4328. else
  4329. $.prompt.close();
  4330. }
  4331. },
  4332. state1: {
  4333. html: '<h2>' + html + '</h2>' +
  4334. linkError,
  4335. persistent: false,
  4336. buttons: buttons1,
  4337. focus: ':input:first',
  4338. defaultButton: 1,
  4339. submit: function (e, v, m, f) {
  4340. e.preventDefault();
  4341. if (v === 0)
  4342. $.prompt.close();
  4343. else
  4344. $.prompt.goToState('state0');
  4345. }
  4346. }
  4347. };
  4348. messageHandler.openDialogWithStates(openPreziState);
  4349. }
  4350. }
  4351. };
  4352. /**
  4353. * A new presentation has been added.
  4354. *
  4355. * @param event the event indicating the add of a presentation
  4356. * @param jid the jid from which the presentation was added
  4357. * @param presUrl url of the presentation
  4358. * @param currentSlide the current slide to which we should move
  4359. */
  4360. function presentationAdded(event, jid, presUrl, currentSlide) {
  4361. console.log("presentation added", presUrl);
  4362. var presId = getPresentationId(presUrl);
  4363. var elementId = 'participant_'
  4364. + Strophe.getResourceFromJid(jid)
  4365. + '_' + presId;
  4366. VideoLayout.addPreziContainer(elementId);
  4367. VideoLayout.resizeThumbnails();
  4368. var controlsEnabled = false;
  4369. if (jid === APP.xmpp.myJid())
  4370. controlsEnabled = true;
  4371. setPresentationVisible(true);
  4372. $('#largeVideoContainer').hover(
  4373. function (event) {
  4374. if (Prezi.isPresentationVisible()) {
  4375. var reloadButtonRight = window.innerWidth
  4376. - $('#presentation>iframe').offset().left
  4377. - $('#presentation>iframe').width();
  4378. $('#reloadPresentation').css({ right: reloadButtonRight,
  4379. display:'inline-block'});
  4380. }
  4381. },
  4382. function (event) {
  4383. if (!Prezi.isPresentationVisible())
  4384. $('#reloadPresentation').css({display:'none'});
  4385. else {
  4386. var e = event.toElement || event.relatedTarget;
  4387. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4388. $('#reloadPresentation').css({display:'none'});
  4389. }
  4390. });
  4391. preziPlayer = new PreziPlayer(
  4392. 'presentation',
  4393. {preziId: presId,
  4394. width: getPresentationWidth(),
  4395. height: getPresentationHeihgt(),
  4396. controls: controlsEnabled,
  4397. debug: true
  4398. });
  4399. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4400. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4401. console.log("prezi status", event.value);
  4402. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4403. if (jid != APP.xmpp.myJid())
  4404. preziPlayer.flyToStep(currentSlide);
  4405. }
  4406. });
  4407. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4408. console.log("event value", event.value);
  4409. APP.xmpp.addToPresence("preziSlide", event.value);
  4410. });
  4411. $("#" + elementId).css( 'background-image',
  4412. 'url(../images/avatarprezi.png)');
  4413. $("#" + elementId).click(
  4414. function () {
  4415. setPresentationVisible(true);
  4416. }
  4417. );
  4418. };
  4419. /**
  4420. * A presentation has been removed.
  4421. *
  4422. * @param event the event indicating the remove of a presentation
  4423. * @param jid the jid for which the presentation was removed
  4424. * @param the url of the presentation
  4425. */
  4426. function presentationRemoved(event, jid, presUrl) {
  4427. console.log('presentation removed', presUrl);
  4428. var presId = getPresentationId(presUrl);
  4429. setPresentationVisible(false);
  4430. $('#participant_'
  4431. + Strophe.getResourceFromJid(jid)
  4432. + '_' + presId).remove();
  4433. $('#presentation>iframe').remove();
  4434. if (preziPlayer != null) {
  4435. preziPlayer.destroy();
  4436. preziPlayer = null;
  4437. }
  4438. };
  4439. /**
  4440. * Indicates if the given string is an alphanumeric string.
  4441. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4442. * purpose of checking URIs.
  4443. */
  4444. function isAlphanumeric(unsafeText) {
  4445. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4446. return regex.test(unsafeText);
  4447. }
  4448. /**
  4449. * Returns the presentation id from the given url.
  4450. */
  4451. function getPresentationId (presUrl) {
  4452. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4453. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4454. }
  4455. /**
  4456. * Returns the presentation width.
  4457. */
  4458. function getPresentationWidth() {
  4459. var availableWidth = UIUtil.getAvailableVideoWidth();
  4460. var availableHeight = getPresentationHeihgt();
  4461. var aspectRatio = 16.0 / 9.0;
  4462. if (availableHeight < availableWidth / aspectRatio) {
  4463. availableWidth = Math.floor(availableHeight * aspectRatio);
  4464. }
  4465. return availableWidth;
  4466. }
  4467. /**
  4468. * Returns the presentation height.
  4469. */
  4470. function getPresentationHeihgt() {
  4471. var remoteVideos = $('#remoteVideos');
  4472. return window.innerHeight - remoteVideos.outerHeight();
  4473. }
  4474. /**
  4475. * Resizes the presentation iframe.
  4476. */
  4477. function resize() {
  4478. if ($('#presentation>iframe')) {
  4479. $('#presentation>iframe').width(getPresentationWidth());
  4480. $('#presentation>iframe').height(getPresentationHeihgt());
  4481. }
  4482. }
  4483. /**
  4484. * Shows/hides a presentation.
  4485. */
  4486. function setPresentationVisible(visible) {
  4487. var prezi = $('#presentation>iframe');
  4488. if (visible) {
  4489. // Trigger the video.selected event to indicate a change in the
  4490. // large video.
  4491. $(document).trigger("video.selected", [true]);
  4492. $('#largeVideo').fadeOut(300);
  4493. prezi.fadeIn(300, function() {
  4494. prezi.css({opacity:'1'});
  4495. ToolbarToggler.dockToolbar(true);
  4496. VideoLayout.setLargeVideoVisible(false);
  4497. });
  4498. $('#activeSpeaker').css('visibility', 'hidden');
  4499. }
  4500. else {
  4501. if (prezi.css('opacity') == '1') {
  4502. prezi.fadeOut(300, function () {
  4503. prezi.css({opacity:'0'});
  4504. $('#reloadPresentation').css({display:'none'});
  4505. $('#largeVideo').fadeIn(300, function() {
  4506. VideoLayout.setLargeVideoVisible(true);
  4507. ToolbarToggler.dockToolbar(false);
  4508. });
  4509. });
  4510. }
  4511. }
  4512. }
  4513. /**
  4514. * Presentation has been removed.
  4515. */
  4516. $(document).bind('presentationremoved.muc', presentationRemoved);
  4517. /**
  4518. * Presentation has been added.
  4519. */
  4520. $(document).bind('presentationadded.muc', presentationAdded);
  4521. /*
  4522. * Indicates presentation slide change.
  4523. */
  4524. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4525. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4526. preziPlayer.flyToStep(current);
  4527. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4528. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4529. preziPlayer.flyToStep(current, i);
  4530. }
  4531. }
  4532. });
  4533. /**
  4534. * On video selected event.
  4535. */
  4536. $(document).bind('video.selected', function (event, isPresentation) {
  4537. if (!isPresentation && $('#presentation>iframe')) {
  4538. setPresentationVisible(false);
  4539. }
  4540. });
  4541. $(window).resize(function () {
  4542. resize();
  4543. });
  4544. module.exports = Prezi;
  4545. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4546. (function() {
  4547. "use strict";
  4548. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4549. window.PreziPlayer = (function() {
  4550. PreziPlayer.API_VERSION = 1;
  4551. PreziPlayer.CURRENT_STEP = 'currentStep';
  4552. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4553. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4554. PreziPlayer.STATUS_LOADING = 'loading';
  4555. PreziPlayer.STATUS_READY = 'ready';
  4556. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4557. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4558. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4559. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4560. PreziPlayer.EVENT_STATUS = "statusChange";
  4561. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4562. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4563. PreziPlayer.domain = "https://prezi.com";
  4564. PreziPlayer.path = "/player/";
  4565. PreziPlayer.players = {};
  4566. PreziPlayer.binded_methods = ['changesHandler'];
  4567. PreziPlayer.createMultiplePlayers = function(optionArray){
  4568. for(var i=0; i<optionArray.length; i++) {
  4569. var optionSet = optionArray[i];
  4570. new PreziPlayer(optionSet.id, optionSet);
  4571. };
  4572. };
  4573. PreziPlayer.messageReceived = function(event){
  4574. var message, item, player;
  4575. try {
  4576. message = JSON.parse(event.data);
  4577. if (message.id && (player = PreziPlayer.players[message.id])) {
  4578. if (player.options.debug === true) {
  4579. if (console && console.log)
  4580. console.log('received', message);
  4581. }
  4582. if (message.type === "changes") {
  4583. player.changesHandler(message);
  4584. }
  4585. for (var i = 0; i < player.callbacks.length; i++) {
  4586. item = player.callbacks[i];
  4587. if (item && message.type === item.event) {
  4588. item.callback(message);
  4589. }
  4590. }
  4591. }
  4592. } catch (e) { }
  4593. };
  4594. function PreziPlayer(id, options) {
  4595. var params, paramString = "", _this = this;
  4596. if (PreziPlayer.players[id]){
  4597. PreziPlayer.players[id].destroy();
  4598. }
  4599. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4600. var method_name = PreziPlayer.binded_methods[i];
  4601. _this[method_name] = __bind(_this[method_name], _this);
  4602. };
  4603. options = options || {};
  4604. this.options = options;
  4605. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4606. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4607. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4608. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4609. this.callbacks = [];
  4610. this.id = id;
  4611. this.embedTo = document.getElementById(id);
  4612. if (!this.embedTo) {
  4613. throw "The element id is not available.";
  4614. }
  4615. this.iframe = document.createElement('iframe');
  4616. params = [
  4617. { name: 'oid', value: options.preziId },
  4618. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4619. { name: 'controls', value: options.controls ? 1 : 0 }
  4620. ];
  4621. for(var i=0; i<params.length; i++) {
  4622. var param = params[i];
  4623. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4624. };
  4625. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4626. this.iframe.frameBorder = 0;
  4627. this.iframe.scrolling = "no";
  4628. this.iframe.width = options.width || 640;
  4629. this.iframe.height = options.height || 480;
  4630. this.embedTo.innerHTML = '';
  4631. // JITSI: IN CASE SOMETHING GOES WRONG.
  4632. try {
  4633. this.embedTo.appendChild(this.iframe);
  4634. }
  4635. catch (err) {
  4636. console.log("CATCH ERROR");
  4637. }
  4638. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4639. // crashes for us.
  4640. this.initPollInterval = setInterval(function(){
  4641. _this.sendMessage({'action': 'init'});
  4642. }, 500);
  4643. PreziPlayer.players[id] = this;
  4644. }
  4645. PreziPlayer.prototype.changesHandler = function(message) {
  4646. var key, value, j, item;
  4647. if (this.initPollInterval) {
  4648. clearInterval(this.initPollInterval);
  4649. this.initPollInterval = false;
  4650. }
  4651. for (key in message.data) {
  4652. if (message.data.hasOwnProperty(key)){
  4653. value = message.data[key];
  4654. this.values[key] = value;
  4655. for (j=0; j<this.callbacks.length; j++) {
  4656. item = this.callbacks[j];
  4657. if (item && item.event === key + "Change"){
  4658. item.callback({type: item.event, value: value});
  4659. }
  4660. }
  4661. }
  4662. }
  4663. };
  4664. PreziPlayer.prototype.destroy = function() {
  4665. if (this.initPollInterval) {
  4666. clearInterval(this.initPollInterval);
  4667. this.initPollInterval = false;
  4668. }
  4669. this.embedTo.innerHTML = '';
  4670. };
  4671. PreziPlayer.prototype.sendMessage = function(message) {
  4672. if (this.options.debug === true) {
  4673. if (console && console.log) console.log('sent', message);
  4674. }
  4675. message.version = PreziPlayer.API_VERSION;
  4676. message.id = this.id;
  4677. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4678. };
  4679. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4680. PreziPlayer.prototype.flyToNextStep = function() {
  4681. return this.sendMessage({
  4682. 'action': 'present',
  4683. 'data': ['moveToNextStep']
  4684. });
  4685. };
  4686. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4687. PreziPlayer.prototype.flyToPreviousStep = function() {
  4688. return this.sendMessage({
  4689. 'action': 'present',
  4690. 'data': ['moveToPrevStep']
  4691. });
  4692. };
  4693. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4694. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4695. var obj = this;
  4696. // check animation_step
  4697. if (animation_step > 0 &&
  4698. obj.values.animationCountOnSteps &&
  4699. obj.values.animationCountOnSteps[step] <= animation_step) {
  4700. animation_step = obj.values.animationCountOnSteps[step];
  4701. }
  4702. // jump to animation steps by calling flyToNextStep()
  4703. function doAnimationSteps() {
  4704. if (obj.values.isMoving == true) {
  4705. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4706. return;
  4707. }
  4708. while (animation_step-- > 0) {
  4709. obj.flyToNextStep(); // do the animation steps
  4710. }
  4711. }
  4712. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4713. // jump to the step
  4714. return this.sendMessage({
  4715. 'action': 'present',
  4716. 'data': ['moveToStep', step]
  4717. });
  4718. };
  4719. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4720. PreziPlayer.prototype.flyToObject = function(objectId) {
  4721. return this.sendMessage({
  4722. 'action': 'present',
  4723. 'data': ['moveToObject', objectId]
  4724. });
  4725. };
  4726. PreziPlayer.prototype.play = function(defaultDelay) {
  4727. return this.sendMessage({
  4728. 'action': 'present',
  4729. 'data': ['startAutoPlay', defaultDelay]
  4730. });
  4731. };
  4732. PreziPlayer.prototype.stop = function() {
  4733. return this.sendMessage({
  4734. 'action': 'present',
  4735. 'data': ['stopAutoPlay']
  4736. });
  4737. };
  4738. PreziPlayer.prototype.pause = function(defaultDelay) {
  4739. return this.sendMessage({
  4740. 'action': 'present',
  4741. 'data': ['pauseAutoPlay', defaultDelay]
  4742. });
  4743. };
  4744. PreziPlayer.prototype.getCurrentStep = function() {
  4745. return this.values.currentStep;
  4746. };
  4747. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4748. return this.values.currentAnimationStep;
  4749. };
  4750. PreziPlayer.prototype.getCurrentObject = function() {
  4751. return this.values.currentObject;
  4752. };
  4753. PreziPlayer.prototype.getStatus = function() {
  4754. return this.values.status;
  4755. };
  4756. PreziPlayer.prototype.isPlaying = function() {
  4757. return this.values.isAutoPlaying;
  4758. };
  4759. PreziPlayer.prototype.getStepCount = function() {
  4760. return this.values.stepCount;
  4761. };
  4762. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4763. return this.values.animationCountOnSteps;
  4764. };
  4765. PreziPlayer.prototype.getTitle = function() {
  4766. return this.values.title;
  4767. };
  4768. PreziPlayer.prototype.setDimensions = function(dims) {
  4769. for (var parameter in dims) {
  4770. this.iframe[parameter] = dims[parameter];
  4771. }
  4772. }
  4773. PreziPlayer.prototype.getDimensions = function() {
  4774. return {
  4775. width: parseInt(this.iframe.width, 10),
  4776. height: parseInt(this.iframe.height, 10)
  4777. }
  4778. }
  4779. PreziPlayer.prototype.on = function(event, callback) {
  4780. this.callbacks.push({
  4781. event: event,
  4782. callback: callback
  4783. });
  4784. };
  4785. PreziPlayer.prototype.off = function(event, callback) {
  4786. var j, item;
  4787. if (event === undefined) {
  4788. this.callbacks = [];
  4789. }
  4790. j = this.callbacks.length;
  4791. while (j--) {
  4792. item = this.callbacks[j];
  4793. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4794. this.callbacks.splice(j, 1);
  4795. }
  4796. }
  4797. };
  4798. if (window.addEventListener) {
  4799. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4800. } else {
  4801. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4802. }
  4803. return PreziPlayer;
  4804. })();
  4805. })();
  4806. module.exports = PreziPlayer;
  4807. },{}],20:[function(require,module,exports){
  4808. var Chat = require("./chat/Chat");
  4809. var ContactList = require("./contactlist/ContactList");
  4810. var Settings = require("./../../settings/Settings");
  4811. var SettingsMenu = require("./settings/SettingsMenu");
  4812. var VideoLayout = require("../videolayout/VideoLayout");
  4813. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4814. var UIUtil = require("../util/UIUtil");
  4815. var LargeVideo = require("../videolayout/LargeVideo");
  4816. /**
  4817. * Toggler for the chat, contact list, settings menu, etc..
  4818. */
  4819. var PanelToggler = (function(my) {
  4820. var currentlyOpen = null;
  4821. var buttons = {
  4822. '#chatspace': '#chatBottomButton',
  4823. '#contactlist': '#contactListButton',
  4824. '#settingsmenu': '#settingsButton'
  4825. };
  4826. /**
  4827. * Toggles the windows in the side panel
  4828. * @param object the window that should be shown
  4829. * @param selector the selector for the element containing the panel
  4830. * @param onOpenComplete function to be called when the panel is opened
  4831. * @param onOpen function to be called if the window is going to be opened
  4832. * @param onClose function to be called if the window is going to be closed
  4833. */
  4834. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4835. UIUtil.buttonClick(buttons[selector], "active");
  4836. if (object.isVisible()) {
  4837. $("#toast-container").animate({
  4838. right: '5px'
  4839. },
  4840. {
  4841. queue: false,
  4842. duration: 500
  4843. });
  4844. $(selector).hide("slide", {
  4845. direction: "right",
  4846. queue: false,
  4847. duration: 500
  4848. });
  4849. if(typeof onClose === "function") {
  4850. onClose();
  4851. }
  4852. currentlyOpen = null;
  4853. }
  4854. else {
  4855. // Undock the toolbar when the chat is shown and if we're in a
  4856. // video mode.
  4857. if (LargeVideo.isLargeVideoVisible()) {
  4858. ToolbarToggler.dockToolbar(false);
  4859. }
  4860. if(currentlyOpen) {
  4861. var current = $(currentlyOpen);
  4862. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4863. current.css('z-index', 4);
  4864. setTimeout(function () {
  4865. current.css('display', 'none');
  4866. current.css('z-index', 5);
  4867. }, 500);
  4868. }
  4869. $("#toast-container").animate({
  4870. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4871. },
  4872. {
  4873. queue: false,
  4874. duration: 500
  4875. });
  4876. $(selector).show("slide", {
  4877. direction: "right",
  4878. queue: false,
  4879. duration: 500,
  4880. complete: onOpenComplete
  4881. });
  4882. if(typeof onOpen === "function") {
  4883. onOpen();
  4884. }
  4885. currentlyOpen = selector;
  4886. }
  4887. };
  4888. /**
  4889. * Opens / closes the chat area.
  4890. */
  4891. my.toggleChat = function() {
  4892. var chatCompleteFunction = Chat.isVisible() ?
  4893. function() {} : function () {
  4894. Chat.scrollChatToBottom();
  4895. $('#chatspace').trigger('shown');
  4896. };
  4897. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4898. toggle(Chat,
  4899. '#chatspace',
  4900. function () {
  4901. // Request the focus in the nickname field or the chat input field.
  4902. if ($('#nickname').css('visibility') === 'visible') {
  4903. $('#nickinput').focus();
  4904. } else {
  4905. $('#usermsg').focus();
  4906. }
  4907. },
  4908. null,
  4909. Chat.resizeChat,
  4910. null);
  4911. };
  4912. /**
  4913. * Opens / closes the contact list area.
  4914. */
  4915. my.toggleContactList = function () {
  4916. var completeFunction = ContactList.isVisible() ?
  4917. function() {} : function () { $('#contactlist').trigger('shown');};
  4918. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4919. toggle(ContactList,
  4920. '#contactlist',
  4921. null,
  4922. function() {
  4923. ContactList.setVisualNotification(false);
  4924. },
  4925. null);
  4926. };
  4927. /**
  4928. * Opens / closes the settings menu
  4929. */
  4930. my.toggleSettingsMenu = function() {
  4931. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4932. toggle(SettingsMenu,
  4933. '#settingsmenu',
  4934. null,
  4935. function() {
  4936. var settings = Settings.getSettings();
  4937. $('#setDisplayName').get(0).value = settings.displayName;
  4938. $('#setEmail').get(0).value = settings.email;
  4939. },
  4940. null);
  4941. };
  4942. /**
  4943. * Returns the size of the side panel.
  4944. */
  4945. my.getPanelSize = function () {
  4946. var availableHeight = window.innerHeight;
  4947. var availableWidth = window.innerWidth;
  4948. var panelWidth = 200;
  4949. if (availableWidth * 0.2 < 200) {
  4950. panelWidth = availableWidth * 0.2;
  4951. }
  4952. return [panelWidth, availableHeight];
  4953. };
  4954. my.isVisible = function() {
  4955. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4956. };
  4957. return my;
  4958. }(PanelToggler || {}));
  4959. module.exports = PanelToggler;
  4960. },{"../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){
  4961. /* global $, Util, nickname:true */
  4962. var Replacement = require("./Replacement");
  4963. var CommandsProcessor = require("./Commands");
  4964. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4965. var smileys = require("./smileys.json").smileys;
  4966. var NicknameHandler = require("../../util/NicknameHandler");
  4967. var UIUtil = require("../../util/UIUtil");
  4968. var UIEvents = require("../../../../service/UI/UIEvents");
  4969. var notificationInterval = false;
  4970. var unreadMessages = 0;
  4971. /**
  4972. * Shows/hides a visual notification, indicating that a message has arrived.
  4973. */
  4974. function setVisualNotification(show) {
  4975. var unreadMsgElement = document.getElementById('unreadMessages');
  4976. var unreadMsgBottomElement
  4977. = document.getElementById('bottomUnreadMessages');
  4978. var glower = $('#chatButton');
  4979. var bottomGlower = $('#chatBottomButton');
  4980. if (unreadMessages) {
  4981. unreadMsgElement.innerHTML = unreadMessages.toString();
  4982. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4983. ToolbarToggler.dockToolbar(true);
  4984. var chatButtonElement
  4985. = document.getElementById('chatButton').parentNode;
  4986. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4987. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4988. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4989. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4990. unreadMsgElement.setAttribute(
  4991. 'style',
  4992. 'top:' + topIndent +
  4993. '; left:' + leftIndent + ';');
  4994. var chatBottomButtonElement
  4995. = document.getElementById('chatBottomButton').parentNode;
  4996. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4997. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4998. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4999. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5000. unreadMsgBottomElement.setAttribute(
  5001. 'style',
  5002. 'top:' + bottomTopIndent +
  5003. '; left:' + bottomLeftIndent + ';');
  5004. if (!glower.hasClass('icon-chat-simple')) {
  5005. glower.removeClass('icon-chat');
  5006. glower.addClass('icon-chat-simple');
  5007. }
  5008. }
  5009. else {
  5010. unreadMsgElement.innerHTML = '';
  5011. unreadMsgBottomElement.innerHTML = '';
  5012. glower.removeClass('icon-chat-simple');
  5013. glower.addClass('icon-chat');
  5014. }
  5015. if (show && !notificationInterval) {
  5016. notificationInterval = window.setInterval(function () {
  5017. glower.toggleClass('active');
  5018. bottomGlower.toggleClass('active glowing');
  5019. }, 800);
  5020. }
  5021. else if (!show && notificationInterval) {
  5022. window.clearInterval(notificationInterval);
  5023. notificationInterval = false;
  5024. glower.removeClass('active');
  5025. bottomGlower.removeClass('glowing');
  5026. bottomGlower.addClass('active');
  5027. }
  5028. }
  5029. /**
  5030. * Returns the current time in the format it is shown to the user
  5031. * @returns {string}
  5032. */
  5033. function getCurrentTime(stamp) {
  5034. var now = (stamp? new Date(stamp): new Date());
  5035. var hour = now.getHours();
  5036. var minute = now.getMinutes();
  5037. var second = now.getSeconds();
  5038. if(hour.toString().length === 1) {
  5039. hour = '0'+hour;
  5040. }
  5041. if(minute.toString().length === 1) {
  5042. minute = '0'+minute;
  5043. }
  5044. if(second.toString().length === 1) {
  5045. second = '0'+second;
  5046. }
  5047. return hour+':'+minute+':'+second;
  5048. }
  5049. function toggleSmileys()
  5050. {
  5051. var smileys = $('#smileysContainer');
  5052. if(!smileys.is(':visible')) {
  5053. smileys.show("slide", { direction: "down", duration: 300});
  5054. } else {
  5055. smileys.hide("slide", { direction: "down", duration: 300});
  5056. }
  5057. $('#usermsg').focus();
  5058. }
  5059. function addClickFunction(smiley, number) {
  5060. smiley.onclick = function addSmileyToMessage() {
  5061. var usermsg = $('#usermsg');
  5062. var message = usermsg.val();
  5063. message += smileys['smiley' + number];
  5064. usermsg.val(message);
  5065. usermsg.get(0).setSelectionRange(message.length, message.length);
  5066. toggleSmileys();
  5067. usermsg.focus();
  5068. };
  5069. }
  5070. /**
  5071. * Adds the smileys container to the chat
  5072. */
  5073. function addSmileys() {
  5074. var smileysContainer = document.createElement('div');
  5075. smileysContainer.id = 'smileysContainer';
  5076. for(var i = 1; i <= 21; i++) {
  5077. var smileyContainer = document.createElement('div');
  5078. smileyContainer.id = 'smiley' + i;
  5079. smileyContainer.className = 'smileyContainer';
  5080. var smiley = document.createElement('img');
  5081. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5082. smiley.className = 'smiley';
  5083. addClickFunction(smiley, i);
  5084. smileyContainer.appendChild(smiley);
  5085. smileysContainer.appendChild(smileyContainer);
  5086. }
  5087. $("#chatspace").append(smileysContainer);
  5088. }
  5089. /**
  5090. * Resizes the chat conversation.
  5091. */
  5092. function resizeChatConversation() {
  5093. var msgareaHeight = $('#usermsg').outerHeight();
  5094. var chatspace = $('#chatspace');
  5095. var width = chatspace.width();
  5096. var chat = $('#chatconversation');
  5097. var smileys = $('#smileysarea');
  5098. smileys.height(msgareaHeight);
  5099. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5100. $('#smileysContainer').css('bottom', msgareaHeight);
  5101. chat.width(width - 10);
  5102. chat.height(window.innerHeight - 15 - msgareaHeight);
  5103. }
  5104. /**
  5105. * Chat related user interface.
  5106. */
  5107. var Chat = (function (my) {
  5108. /**
  5109. * Initializes chat related interface.
  5110. */
  5111. my.init = function () {
  5112. if(NicknameHandler.getNickname())
  5113. Chat.setChatConversationMode(true);
  5114. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5115. function (nickname) {
  5116. Chat.setChatConversationMode(true);
  5117. });
  5118. $('#nickinput').keydown(function (event) {
  5119. if (event.keyCode === 13) {
  5120. event.preventDefault();
  5121. var val = UIUtil.escapeHtml(this.value);
  5122. this.value = '';
  5123. if (!NicknameHandler.getNickname()) {
  5124. NicknameHandler.setNickname(val);
  5125. return;
  5126. }
  5127. }
  5128. });
  5129. $('#usermsg').keydown(function (event) {
  5130. if (event.keyCode === 13) {
  5131. event.preventDefault();
  5132. var value = this.value;
  5133. $('#usermsg').val('').trigger('autosize.resize');
  5134. this.focus();
  5135. var command = new CommandsProcessor(value);
  5136. if(command.isCommand())
  5137. {
  5138. command.processCommand();
  5139. }
  5140. else
  5141. {
  5142. var message = UIUtil.escapeHtml(value);
  5143. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5144. }
  5145. }
  5146. });
  5147. var onTextAreaResize = function () {
  5148. resizeChatConversation();
  5149. Chat.scrollChatToBottom();
  5150. };
  5151. $('#usermsg').autosize({callback: onTextAreaResize});
  5152. $("#chatspace").bind("shown",
  5153. function () {
  5154. unreadMessages = 0;
  5155. setVisualNotification(false);
  5156. });
  5157. addSmileys();
  5158. };
  5159. /**
  5160. * Appends the given message to the chat conversation.
  5161. */
  5162. my.updateChatConversation = function (from, displayName, message, myjid, stamp) {
  5163. var divClassName = '';
  5164. if (APP.xmpp.myJid() === from) {
  5165. divClassName = "localuser";
  5166. }
  5167. else {
  5168. divClassName = "remoteuser";
  5169. if (!Chat.isVisible()) {
  5170. unreadMessages++;
  5171. UIUtil.playSoundNotification('chatNotification');
  5172. setVisualNotification(true);
  5173. }
  5174. }
  5175. // replace links and smileys
  5176. // Strophe already escapes special symbols on sending,
  5177. // so we escape here only tags to avoid double &amp;
  5178. var escMessage = message.replace(/</g, '&lt;').
  5179. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5180. var escDisplayName = UIUtil.escapeHtml(displayName);
  5181. message = Replacement.processReplacements(escMessage);
  5182. var messageContainer =
  5183. '<div class="chatmessage">'+
  5184. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5185. '<div class="username ' + divClassName +'">' + escDisplayName +
  5186. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5187. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5188. '</div>';
  5189. $('#chatconversation').append(messageContainer);
  5190. $('#chatconversation').animate(
  5191. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5192. };
  5193. /**
  5194. * Appends error message to the conversation
  5195. * @param errorMessage the received error message.
  5196. * @param originalText the original message.
  5197. */
  5198. my.chatAddError = function(errorMessage, originalText)
  5199. {
  5200. errorMessage = UIUtil.escapeHtml(errorMessage);
  5201. originalText = UIUtil.escapeHtml(originalText);
  5202. $('#chatconversation').append(
  5203. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5204. (originalText? (' \"'+ originalText + '\"') : "") +
  5205. ' was not sent.' +
  5206. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5207. $('#chatconversation').animate(
  5208. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5209. };
  5210. /**
  5211. * Sets the subject to the UI
  5212. * @param subject the subject
  5213. */
  5214. my.chatSetSubject = function(subject)
  5215. {
  5216. if(subject)
  5217. subject = subject.trim();
  5218. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5219. if(subject === "")
  5220. {
  5221. $("#subject").css({display: "none"});
  5222. }
  5223. else
  5224. {
  5225. $("#subject").css({display: "block"});
  5226. }
  5227. };
  5228. /**
  5229. * Sets the chat conversation mode.
  5230. */
  5231. my.setChatConversationMode = function (isConversationMode) {
  5232. if (isConversationMode) {
  5233. $('#nickname').css({visibility: 'hidden'});
  5234. $('#chatconversation').css({visibility: 'visible'});
  5235. $('#usermsg').css({visibility: 'visible'});
  5236. $('#smileysarea').css({visibility: 'visible'});
  5237. $('#usermsg').focus();
  5238. }
  5239. };
  5240. /**
  5241. * Resizes the chat area.
  5242. */
  5243. my.resizeChat = function () {
  5244. var chatSize = require("../SidePanelToggler").getPanelSize();
  5245. $('#chatspace').width(chatSize[0]);
  5246. $('#chatspace').height(chatSize[1]);
  5247. resizeChatConversation();
  5248. };
  5249. /**
  5250. * Indicates if the chat is currently visible.
  5251. */
  5252. my.isVisible = function () {
  5253. return $('#chatspace').is(":visible");
  5254. };
  5255. /**
  5256. * Shows and hides the window with the smileys
  5257. */
  5258. my.toggleSmileys = toggleSmileys;
  5259. /**
  5260. * Scrolls chat to the bottom.
  5261. */
  5262. my.scrollChatToBottom = function() {
  5263. setTimeout(function () {
  5264. $('#chatconversation').scrollTop(
  5265. $('#chatconversation')[0].scrollHeight);
  5266. }, 5);
  5267. };
  5268. return my;
  5269. }(Chat || {}));
  5270. module.exports = Chat;
  5271. },{"../../../../service/UI/UIEvents":106,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5272. var UIUtil = require("../../util/UIUtil");
  5273. /**
  5274. * List with supported commands. The keys are the names of the commands and
  5275. * the value is the function that processes the message.
  5276. * @type {{String: function}}
  5277. */
  5278. var commands = {
  5279. "topic" : processTopic
  5280. };
  5281. /**
  5282. * Extracts the command from the message.
  5283. * @param message the received message
  5284. * @returns {string} the command
  5285. */
  5286. function getCommand(message)
  5287. {
  5288. if(message)
  5289. {
  5290. for(var command in commands)
  5291. {
  5292. if(message.indexOf("/" + command) == 0)
  5293. return command;
  5294. }
  5295. }
  5296. return "";
  5297. };
  5298. /**
  5299. * Processes the data for topic command.
  5300. * @param commandArguments the arguments of the topic command.
  5301. */
  5302. function processTopic(commandArguments)
  5303. {
  5304. var topic = UIUtil.escapeHtml(commandArguments);
  5305. APP.xmpp.setSubject(topic);
  5306. }
  5307. /**
  5308. * Constructs new CommandProccessor instance from a message that
  5309. * handles commands received via chat messages.
  5310. * @param message the message
  5311. * @constructor
  5312. */
  5313. function CommandsProcessor(message)
  5314. {
  5315. var command = getCommand(message);
  5316. /**
  5317. * Returns the name of the command.
  5318. * @returns {String} the command
  5319. */
  5320. this.getCommand = function()
  5321. {
  5322. return command;
  5323. };
  5324. var messageArgument = message.substr(command.length + 2);
  5325. /**
  5326. * Returns the arguments of the command.
  5327. * @returns {string}
  5328. */
  5329. this.getArgument = function()
  5330. {
  5331. return messageArgument;
  5332. };
  5333. }
  5334. /**
  5335. * Checks whether this instance is valid command or not.
  5336. * @returns {boolean}
  5337. */
  5338. CommandsProcessor.prototype.isCommand = function()
  5339. {
  5340. if(this.getCommand())
  5341. return true;
  5342. return false;
  5343. };
  5344. /**
  5345. * Processes the command.
  5346. */
  5347. CommandsProcessor.prototype.processCommand = function()
  5348. {
  5349. if(!this.isCommand())
  5350. return;
  5351. commands[this.getCommand()](this.getArgument());
  5352. };
  5353. module.exports = CommandsProcessor;
  5354. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5355. var Smileys = require("./smileys.json");
  5356. /**
  5357. * Processes links and smileys in "body"
  5358. */
  5359. function processReplacements(body)
  5360. {
  5361. //make links clickable
  5362. body = linkify(body);
  5363. //add smileys
  5364. body = smilify(body);
  5365. return body;
  5366. }
  5367. /**
  5368. * Finds and replaces all links in the links in "body"
  5369. * with their <a href=""></a>
  5370. */
  5371. function linkify(inputText)
  5372. {
  5373. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5374. //URLs starting with http://, https://, or ftp://
  5375. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5376. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5377. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5378. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5379. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5380. //Change email addresses to mailto:: links.
  5381. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5382. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5383. return replacedText;
  5384. }
  5385. /**
  5386. * Replaces common smiley strings with images
  5387. */
  5388. function smilify(body)
  5389. {
  5390. if(!body) {
  5391. return body;
  5392. }
  5393. var regexs = Smileys["regexs"];
  5394. for(var smiley in regexs) {
  5395. if(regexs.hasOwnProperty(smiley)) {
  5396. body = body.replace(regexs[smiley],
  5397. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5398. }
  5399. }
  5400. return body;
  5401. }
  5402. module.exports = {
  5403. processReplacements: processReplacements,
  5404. linkify: linkify
  5405. };
  5406. },{"./smileys.json":24}],24:[function(require,module,exports){
  5407. module.exports={
  5408. "smileys": {
  5409. "smiley1": ":)",
  5410. "smiley2": ":(",
  5411. "smiley3": ":D",
  5412. "smiley4": "(y)",
  5413. "smiley5": " :P",
  5414. "smiley6": "(wave)",
  5415. "smiley7": "(blush)",
  5416. "smiley8": "(chuckle)",
  5417. "smiley9": "(shocked)",
  5418. "smiley10": ":*",
  5419. "smiley11": "(n)",
  5420. "smiley12": "(search)",
  5421. "smiley13": " <3",
  5422. "smiley14": "(oops)",
  5423. "smiley15": "(angry)",
  5424. "smiley16": "(angel)",
  5425. "smiley17": "(sick)",
  5426. "smiley18": ";(",
  5427. "smiley19": "(bomb)",
  5428. "smiley20": "(clap)",
  5429. "smiley21": " ;)"
  5430. },
  5431. "regexs": {
  5432. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5433. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5434. "smiley1": /(:-\)|:\))/gi,
  5435. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5436. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5437. "smiley6": /(\(wave\))/gi,
  5438. "smiley7": /(\(blush\))/gi,
  5439. "smiley8": /(\(chuckle\))/gi,
  5440. "smiley9": /(:-0|\(shocked\))/gi,
  5441. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5442. "smiley11": /(\(n\))/gi,
  5443. "smiley12": /(\(search\))/g,
  5444. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5445. "smiley14": /(\(oops\))/gi,
  5446. "smiley15": /(\(angry\))/gi,
  5447. "smiley16": /(\(angel\))/gi,
  5448. "smiley17": /(\(sick\))/gi,
  5449. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5450. "smiley19": /(\(bomb\))/gi,
  5451. "smiley20": /(\(clap\))/gi,
  5452. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5453. }
  5454. }
  5455. },{}],25:[function(require,module,exports){
  5456. var numberOfContacts = 0;
  5457. var notificationInterval;
  5458. /**
  5459. * Updates the number of participants in the contact list button and sets
  5460. * the glow
  5461. * @param delta indicates whether a new user has joined (1) or someone has
  5462. * left(-1)
  5463. */
  5464. function updateNumberOfParticipants(delta) {
  5465. numberOfContacts += delta;
  5466. if (numberOfContacts === 1) {
  5467. // when the user is alone we don't show the number of participants
  5468. $("#numberOfParticipants").text('');
  5469. ContactList.setVisualNotification(false);
  5470. } else if (numberOfContacts > 1) {
  5471. ContactList.setVisualNotification(!ContactList.isVisible());
  5472. $("#numberOfParticipants").text(numberOfContacts);
  5473. } else {
  5474. console.error("Invalid number of participants: " + numberOfContacts);
  5475. }
  5476. }
  5477. /**
  5478. * Creates the avatar element.
  5479. *
  5480. * @return the newly created avatar element
  5481. */
  5482. function createAvatar(id) {
  5483. var avatar = document.createElement('img');
  5484. avatar.className = "icon-avatar avatar";
  5485. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  5486. return avatar;
  5487. }
  5488. /**
  5489. * Creates the display name paragraph.
  5490. *
  5491. * @param displayName the display name to set
  5492. */
  5493. function createDisplayNameParagraph(key, displayName) {
  5494. var p = document.createElement('p');
  5495. if(displayName)
  5496. p.innerText = displayName;
  5497. else if(key)
  5498. {
  5499. p.setAttribute("data-i18n",key);
  5500. p.innerText = APP.translation.translateString(key);
  5501. }
  5502. return p;
  5503. }
  5504. function stopGlowing(glower) {
  5505. window.clearInterval(notificationInterval);
  5506. notificationInterval = false;
  5507. glower.removeClass('glowing');
  5508. if (!ContactList.isVisible()) {
  5509. glower.removeClass('active');
  5510. }
  5511. }
  5512. /**
  5513. * Contact list.
  5514. */
  5515. var ContactList = {
  5516. /**
  5517. * Indicates if the chat is currently visible.
  5518. *
  5519. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5520. * otherwise
  5521. */
  5522. isVisible: function () {
  5523. return $('#contactlist').is(":visible");
  5524. },
  5525. /**
  5526. * Adds a contact for the given peerJid if such doesn't yet exist.
  5527. *
  5528. * @param peerJid the peerJid corresponding to the contact
  5529. * @param id the user's email or userId used to get the user's avatar
  5530. */
  5531. ensureAddContact: function (peerJid, id) {
  5532. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5533. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5534. if (!contact || contact.length <= 0)
  5535. ContactList.addContact(peerJid, id);
  5536. },
  5537. /**
  5538. * Adds a contact for the given peer jid.
  5539. *
  5540. * @param peerJid the jid of the contact to add
  5541. * @param id the email or userId of the user
  5542. */
  5543. addContact: function (peerJid, id) {
  5544. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5545. var contactlist = $('#contacts');
  5546. var newContact = document.createElement('li');
  5547. newContact.id = resourceJid;
  5548. newContact.className = "clickable";
  5549. newContact.onclick = function (event) {
  5550. if (event.currentTarget.className === "clickable") {
  5551. $(ContactList).trigger('contactclicked', [peerJid]);
  5552. }
  5553. };
  5554. newContact.appendChild(createAvatar(id));
  5555. newContact.appendChild(createDisplayNameParagraph("participant"));
  5556. if (resourceJid === APP.xmpp.myResource()) {
  5557. contactlist.prepend(newContact);
  5558. }
  5559. else {
  5560. contactlist.append(newContact);
  5561. }
  5562. updateNumberOfParticipants(1);
  5563. },
  5564. /**
  5565. * Removes a contact for the given peer jid.
  5566. *
  5567. * @param peerJid the peerJid corresponding to the contact to remove
  5568. */
  5569. removeContact: function (peerJid) {
  5570. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5571. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5572. if (contact && contact.length > 0) {
  5573. var contactlist = $('#contactlist>ul');
  5574. contactlist.get(0).removeChild(contact.get(0));
  5575. updateNumberOfParticipants(-1);
  5576. }
  5577. },
  5578. setVisualNotification: function (show, stopGlowingIn) {
  5579. var glower = $('#contactListButton');
  5580. if (show && !notificationInterval) {
  5581. notificationInterval = window.setInterval(function () {
  5582. glower.toggleClass('active glowing');
  5583. }, 800);
  5584. }
  5585. else if (!show && notificationInterval) {
  5586. stopGlowing(glower);
  5587. }
  5588. if (stopGlowingIn) {
  5589. setTimeout(function () {
  5590. stopGlowing(glower);
  5591. }, stopGlowingIn);
  5592. }
  5593. },
  5594. setClickable: function (resourceJid, isClickable) {
  5595. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5596. if (isClickable) {
  5597. contact.addClass('clickable');
  5598. } else {
  5599. contact.removeClass('clickable');
  5600. }
  5601. },
  5602. onDisplayNameChange: function (peerJid, displayName) {
  5603. if (peerJid === 'localVideoContainer')
  5604. peerJid = APP.xmpp.myJid();
  5605. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5606. var contactName = $('#contacts #' + resourceJid + '>p');
  5607. if (contactName && displayName && displayName.length > 0)
  5608. contactName.html(displayName);
  5609. },
  5610. userAvatarChanged: function (resourceJid, contactListUrl) {
  5611. // set the avatar in the contact list
  5612. var contact = $('#' + resourceJid + '>img');
  5613. if (contact && contact.length > 0) {
  5614. contact.get(0).src = contactListUrl;
  5615. }
  5616. }
  5617. };
  5618. module.exports = ContactList;
  5619. },{}],26:[function(require,module,exports){
  5620. var Avatar = require("../../avatar/Avatar");
  5621. var Settings = require("./../../../settings/Settings");
  5622. var UIUtil = require("../../util/UIUtil");
  5623. var languages = require("../../../../service/translation/languages");
  5624. function generateLanguagesSelectBox()
  5625. {
  5626. var currentLang = APP.translation.getCurrentLanguage();
  5627. var html = "<select id=\"languages_selectbox\">";
  5628. var langArray = languages.getLanguages();
  5629. for(var i = 0; i < langArray.length; i++)
  5630. {
  5631. var lang = langArray[i];
  5632. html += "<option ";
  5633. if(lang === currentLang)
  5634. html += "selected ";
  5635. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5636. html += "</option>";
  5637. }
  5638. return html + "</select>";
  5639. }
  5640. var SettingsMenu = {
  5641. init: function () {
  5642. $("#startMutedOptions").before(generateLanguagesSelectBox());
  5643. APP.translation.translateElement($("#languages_selectbox"));
  5644. $('#settingsmenu>input').keyup(function(event){
  5645. if(event.keyCode === 13) {//enter
  5646. SettingsMenu.update();
  5647. }
  5648. });
  5649. if(APP.xmpp.isModerator())
  5650. {
  5651. $("#startMutedOptions").css("display", "block");
  5652. }
  5653. else
  5654. {
  5655. $("#startMutedOptions").css("display", "none");
  5656. }
  5657. $("#updateSettings").click(function () {
  5658. SettingsMenu.update();
  5659. });
  5660. },
  5661. onRoleChanged: function () {
  5662. if(APP.xmpp.isModerator())
  5663. {
  5664. $("#startMutedOptions").css("display", "block");
  5665. }
  5666. else
  5667. {
  5668. $("#startMutedOptions").css("display", "none");
  5669. }
  5670. },
  5671. setStartMuted: function (audio, video) {
  5672. $("#startAudioMuted").attr("checked", audio);
  5673. $("#startVideoMuted").attr("checked", video);
  5674. },
  5675. update: function() {
  5676. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5677. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5678. if(newDisplayName) {
  5679. var displayName = Settings.setDisplayName(newDisplayName);
  5680. APP.xmpp.addToPresence("displayName", displayName, true);
  5681. }
  5682. var language = $("#languages_selectbox").val();
  5683. APP.translation.setLanguage(language);
  5684. Settings.setLanguage(language);
  5685. APP.xmpp.addToPresence("email", newEmail);
  5686. var email = Settings.setEmail(newEmail);
  5687. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5688. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5689. APP.xmpp.addToPresence("startMuted",
  5690. [startAudioMuted, startVideoMuted]);
  5691. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5692. },
  5693. isVisible: function() {
  5694. return $('#settingsmenu').is(':visible');
  5695. },
  5696. setDisplayName: function(newDisplayName) {
  5697. var displayName = Settings.setDisplayName(newDisplayName);
  5698. $('#setDisplayName').get(0).value = displayName;
  5699. },
  5700. onDisplayNameChange: function(peerJid, newDisplayName) {
  5701. if(peerJid === 'localVideoContainer' ||
  5702. peerJid === APP.xmpp.myJid()) {
  5703. this.setDisplayName(newDisplayName);
  5704. }
  5705. },
  5706. changeAvatar: function (thumbUrl) {
  5707. $('#avatar').get(0).src = thumbUrl;
  5708. }
  5709. };
  5710. module.exports = SettingsMenu;
  5711. },{"../../../../service/translation/languages":111,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5712. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5713. var buttonHandlers = {
  5714. "bottom_toolbar_contact_list": function () {
  5715. BottomToolbar.toggleContactList();
  5716. },
  5717. "bottom_toolbar_film_strip": function () {
  5718. BottomToolbar.toggleFilmStrip();
  5719. },
  5720. "bottom_toolbar_chat": function () {
  5721. BottomToolbar.toggleChat();
  5722. }
  5723. };
  5724. var BottomToolbar = (function (my) {
  5725. my.init = function () {
  5726. for(var k in buttonHandlers)
  5727. $("#" + k).click(buttonHandlers[k]);
  5728. };
  5729. my.toggleChat = function() {
  5730. PanelToggler.toggleChat();
  5731. };
  5732. my.toggleContactList = function() {
  5733. PanelToggler.toggleContactList();
  5734. };
  5735. my.toggleFilmStrip = function() {
  5736. var filmstrip = $("#remoteVideos");
  5737. filmstrip.toggleClass("hidden");
  5738. };
  5739. $(document).bind("remotevideo.resized", function (event, width, height) {
  5740. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5741. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5742. });
  5743. return my;
  5744. }(BottomToolbar || {}));
  5745. module.exports = BottomToolbar;
  5746. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5747. /* global APP,$, buttonClick, config, lockRoom,
  5748. setSharedKey, Util */
  5749. var messageHandler = require("../util/MessageHandler");
  5750. var BottomToolbar = require("./BottomToolbar");
  5751. var Prezi = require("../prezi/Prezi");
  5752. var Etherpad = require("../etherpad/Etherpad");
  5753. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5754. var Authentication = require("../authentication/Authentication");
  5755. var UIUtil = require("../util/UIUtil");
  5756. var AuthenticationEvents
  5757. = require("../../../service/authentication/AuthenticationEvents");
  5758. var roomUrl = null;
  5759. var sharedKey = '';
  5760. var UI = null;
  5761. var buttonHandlers =
  5762. {
  5763. "toolbar_button_mute": function () {
  5764. return APP.UI.toggleAudio();
  5765. },
  5766. "toolbar_button_camera": function () {
  5767. return APP.UI.toggleVideo();
  5768. },
  5769. /*"toolbar_button_authentication": function () {
  5770. return Toolbar.authenticateClicked();
  5771. },*/
  5772. "toolbar_button_record": function () {
  5773. return toggleRecording();
  5774. },
  5775. "toolbar_button_security": function () {
  5776. return Toolbar.openLockDialog();
  5777. },
  5778. "toolbar_button_link": function () {
  5779. return Toolbar.openLinkDialog();
  5780. },
  5781. "toolbar_button_chat": function () {
  5782. return BottomToolbar.toggleChat();
  5783. },
  5784. "toolbar_button_prezi": function () {
  5785. return Prezi.openPreziDialog();
  5786. },
  5787. "toolbar_button_etherpad": function () {
  5788. return Etherpad.toggleEtherpad(0);
  5789. },
  5790. "toolbar_button_desktopsharing": function () {
  5791. return APP.desktopsharing.toggleScreenSharing();
  5792. },
  5793. "toolbar_button_fullScreen": function()
  5794. {
  5795. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  5796. return Toolbar.toggleFullScreen();
  5797. },
  5798. "toolbar_button_sip": function () {
  5799. return callSipButtonClicked();
  5800. },
  5801. "toolbar_button_dialpad": function () {
  5802. return dialpadButtonClicked();
  5803. },
  5804. "toolbar_button_settings": function () {
  5805. PanelToggler.toggleSettingsMenu();
  5806. },
  5807. "toolbar_button_hangup": function () {
  5808. return hangup();
  5809. },
  5810. "toolbar_button_login": function () {
  5811. Toolbar.authenticateClicked();
  5812. },
  5813. "toolbar_button_logout": function () {
  5814. // Ask for confirmation
  5815. messageHandler.openTwoButtonDialog(
  5816. "dialog.logoutTitle",
  5817. null,
  5818. "dialog.logoutQuestion",
  5819. null,
  5820. false,
  5821. "dialog.Yes",
  5822. function (evt, yes) {
  5823. if (yes) {
  5824. APP.xmpp.logout(function (url) {
  5825. if (url) {
  5826. window.location.href = url;
  5827. } else {
  5828. hangup();
  5829. }
  5830. });
  5831. }
  5832. });
  5833. }
  5834. };
  5835. function hangup() {
  5836. APP.xmpp.disposeConference();
  5837. if(config.enableWelcomePage)
  5838. {
  5839. setTimeout(function()
  5840. {
  5841. window.localStorage.welcomePageDisabled = false;
  5842. window.location.pathname = "/";
  5843. }, 10000);
  5844. }
  5845. var title = APP.translation.generateTranslationHTML(
  5846. "dialog.sessTerminated");
  5847. var msg = APP.translation.generateTranslationHTML(
  5848. "dialog.hungUp");
  5849. var button = APP.translation.generateTranslationHTML(
  5850. "dialog.joinAgain");
  5851. var buttons = [];
  5852. buttons.push({title: button, value: true});
  5853. UI.messageHandler.openDialog(
  5854. title,
  5855. msg,
  5856. true,
  5857. buttons,
  5858. function(event, value, message, formVals)
  5859. {
  5860. window.location.reload();
  5861. return false;
  5862. }
  5863. );
  5864. }
  5865. /**
  5866. * Starts or stops the recording for the conference.
  5867. */
  5868. function toggleRecording() {
  5869. APP.xmpp.toggleRecording(function (callback) {
  5870. var msg = APP.translation.generateTranslationHTML(
  5871. "dialog.recordingToken");
  5872. var token = APP.translation.translateString("dialog.token");
  5873. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5874. '<h2>' + msg + '</h2>' +
  5875. '<input name="recordingToken" type="text" ' +
  5876. ' data-i18n="[placeholder]dialog.token" ' +
  5877. 'placeholder="' + token + '" autofocus>',
  5878. false,
  5879. "dialog.Save",
  5880. function (e, v, m, f) {
  5881. if (v) {
  5882. var token = f.recordingToken;
  5883. if (token) {
  5884. callback(UIUtil.escapeHtml(token));
  5885. }
  5886. }
  5887. },
  5888. null,
  5889. function () { },
  5890. ':input:first'
  5891. );
  5892. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  5893. }
  5894. /**
  5895. * Locks / unlocks the room.
  5896. */
  5897. function lockRoom(lock) {
  5898. var currentSharedKey = '';
  5899. if (lock)
  5900. currentSharedKey = sharedKey;
  5901. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5902. // password is required
  5903. if (sharedKey)
  5904. {
  5905. console.log('set room password');
  5906. Toolbar.lockLockButton();
  5907. }
  5908. else
  5909. {
  5910. console.log('removed room password');
  5911. Toolbar.unlockLockButton();
  5912. }
  5913. }, function (err) {
  5914. console.warn('setting password failed', err);
  5915. messageHandler.showError("dialog.lockTitle",
  5916. "dialog.lockMessage");
  5917. Toolbar.setSharedKey('');
  5918. }, function () {
  5919. console.warn('room passwords not supported');
  5920. messageHandler.showError("dialog.warning",
  5921. "dialog.passwordNotSupported");
  5922. Toolbar.setSharedKey('');
  5923. });
  5924. };
  5925. /**
  5926. * Invite participants to conference.
  5927. */
  5928. function inviteParticipants() {
  5929. if (roomUrl === null)
  5930. return;
  5931. var sharedKeyText = "";
  5932. if (sharedKey && sharedKey.length > 0) {
  5933. sharedKeyText =
  5934. APP.translation.translateString("email.sharedKey",
  5935. {sharedKey: sharedKey});
  5936. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5937. }
  5938. var supportedBrowsers = "Chromium, Google Chrome " +
  5939. APP.translation.translateString("email.and") + " Opera";
  5940. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5941. var subject = APP.translation.translateString("email.subject",
  5942. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5943. var body = APP.translation.translateString("email.body",
  5944. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5945. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5946. body = body.replace(/\n/g, "%0D%0A");
  5947. if (window.localStorage.displayname) {
  5948. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5949. }
  5950. if (interfaceConfig.INVITATION_POWERED_BY) {
  5951. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5952. }
  5953. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5954. }
  5955. function dialpadButtonClicked()
  5956. {
  5957. //TODO show the dialpad window
  5958. }
  5959. function callSipButtonClicked()
  5960. {
  5961. var defaultNumber
  5962. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5963. var sipMsg = APP.translation.generateTranslationHTML(
  5964. "dialog.sipMsg");
  5965. messageHandler.openTwoButtonDialog(null, null, null,
  5966. '<h2>' + sipMsg + '</h2>' +
  5967. '<input name="sipNumber" type="text"' +
  5968. ' value="' + defaultNumber + '" autofocus>',
  5969. false,
  5970. "dialog.Dial",
  5971. function (e, v, m, f) {
  5972. if (v) {
  5973. var numberInput = f.sipNumber;
  5974. if (numberInput) {
  5975. APP.xmpp.dial(
  5976. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5977. }
  5978. }
  5979. },
  5980. null, null, ':input:first'
  5981. );
  5982. }
  5983. var Toolbar = (function (my) {
  5984. my.init = function (ui) {
  5985. for(var k in buttonHandlers)
  5986. $("#" + k).click(buttonHandlers[k]);
  5987. UI = ui;
  5988. // Update login info
  5989. APP.xmpp.addListener(
  5990. AuthenticationEvents.IDENTITY_UPDATED,
  5991. function (authenticationEnabled, userIdentity) {
  5992. var loggedIn = false;
  5993. if (userIdentity) {
  5994. loggedIn = true;
  5995. }
  5996. Toolbar.showAuthenticateButton(authenticationEnabled);
  5997. if (authenticationEnabled) {
  5998. Toolbar.setAuthenticatedIdentity(userIdentity);
  5999. Toolbar.showLoginButton(!loggedIn);
  6000. Toolbar.showLogoutButton(loggedIn);
  6001. }
  6002. }
  6003. );
  6004. },
  6005. /**
  6006. * Sets shared key
  6007. * @param sKey the shared key
  6008. */
  6009. my.setSharedKey = function (sKey) {
  6010. sharedKey = sKey;
  6011. };
  6012. my.authenticateClicked = function () {
  6013. Authentication.focusAuthenticationWindow();
  6014. if (!APP.xmpp.isExternalAuthEnabled()) {
  6015. Authentication.xmppAuthenticate();
  6016. return;
  6017. }
  6018. // Get authentication URL
  6019. if (!APP.xmpp.getMUCJoined()) {
  6020. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6021. // If conference has not been started yet - redirect to login page
  6022. window.location.href = url;
  6023. });
  6024. } else {
  6025. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6026. // Otherwise - open popup with authentication URL
  6027. var authenticationWindow = Authentication.createAuthenticationWindow(
  6028. function () {
  6029. // On popup closed - retry room allocation
  6030. APP.xmpp.allocateConferenceFocus(
  6031. APP.UI.getRoomName(),
  6032. function () { console.info("AUTH DONE"); }
  6033. );
  6034. }, url);
  6035. if (!authenticationWindow) {
  6036. messageHandler.openMessageDialog(
  6037. null, "dialog.popupError");
  6038. }
  6039. });
  6040. }
  6041. };
  6042. /**
  6043. * Updates the room invite url.
  6044. */
  6045. my.updateRoomUrl = function (newRoomUrl) {
  6046. roomUrl = newRoomUrl;
  6047. // If the invite dialog has been already opened we update the information.
  6048. var inviteLink = document.getElementById('inviteLinkRef');
  6049. if (inviteLink) {
  6050. inviteLink.value = roomUrl;
  6051. inviteLink.select();
  6052. $('#inviteLinkRef').parent()
  6053. .find('button[value=true]').prop('disabled', false);
  6054. }
  6055. };
  6056. /**
  6057. * Disables and enables some of the buttons.
  6058. */
  6059. my.setupButtonsFromConfig = function () {
  6060. if (config.disablePrezi)
  6061. {
  6062. $("#prezi_button").css({display: "none"});
  6063. }
  6064. };
  6065. /**
  6066. * Opens the lock room dialog.
  6067. */
  6068. my.openLockDialog = function () {
  6069. // Only the focus is able to set a shared key.
  6070. if (!APP.xmpp.isModerator()) {
  6071. if (sharedKey) {
  6072. messageHandler.openMessageDialog(null,
  6073. "dialog.passwordError");
  6074. } else {
  6075. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6076. }
  6077. } else {
  6078. if (sharedKey) {
  6079. messageHandler.openTwoButtonDialog(null, null,
  6080. "dialog.passwordCheck",
  6081. null,
  6082. false,
  6083. "dialog.Remove",
  6084. function (e, v) {
  6085. if (v) {
  6086. Toolbar.setSharedKey('');
  6087. lockRoom(false);
  6088. }
  6089. });
  6090. } else {
  6091. var msg = APP.translation.generateTranslationHTML(
  6092. "dialog.passwordMsg");
  6093. var yourPassword = APP.translation.translateString(
  6094. "dialog.yourPassword");
  6095. messageHandler.openTwoButtonDialog(null, null, null,
  6096. '<h2>' + msg + '</h2>' +
  6097. '<input name="lockKey" type="text"' +
  6098. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6099. 'placeholder="' + yourPassword + '" autofocus>',
  6100. false,
  6101. "dialog.Save",
  6102. function (e, v, m, f) {
  6103. if (v) {
  6104. var lockKey = f.lockKey;
  6105. if (lockKey) {
  6106. Toolbar.setSharedKey(
  6107. UIUtil.escapeHtml(lockKey));
  6108. lockRoom(true);
  6109. }
  6110. }
  6111. },
  6112. null, null, 'input:first'
  6113. );
  6114. }
  6115. }
  6116. };
  6117. /**
  6118. * Opens the invite link dialog.
  6119. */
  6120. my.openLinkDialog = function () {
  6121. var inviteAttreibutes;
  6122. if (roomUrl === null) {
  6123. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6124. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6125. } else {
  6126. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6127. }
  6128. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6129. null, null,
  6130. '<input id="inviteLinkRef" type="text" ' +
  6131. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6132. false,
  6133. "dialog.Invite",
  6134. function (e, v) {
  6135. if (v) {
  6136. if (roomUrl) {
  6137. inviteParticipants();
  6138. }
  6139. }
  6140. },
  6141. function (event) {
  6142. if (roomUrl) {
  6143. document.getElementById('inviteLinkRef').select();
  6144. } else {
  6145. if (event && event.target)
  6146. $(event.target)
  6147. .find('button[value=true]').prop('disabled', true);
  6148. }
  6149. }
  6150. );
  6151. };
  6152. /**
  6153. * Opens the settings dialog.
  6154. * FIXME: not used ?
  6155. */
  6156. my.openSettingsDialog = function () {
  6157. var settings1 = APP.translation.generateTranslationHTML(
  6158. "dialog.settings1");
  6159. var settings2 = APP.translation.generateTranslationHTML(
  6160. "dialog.settings2");
  6161. var settings3 = APP.translation.generateTranslationHTML(
  6162. "dialog.settings3");
  6163. var yourPassword = APP.translation.translateString(
  6164. "dialog.yourPassword");
  6165. messageHandler.openTwoButtonDialog(null,
  6166. '<h2>' + settings1 + '</h2>' +
  6167. '<input type="checkbox" id="initMuted">' +
  6168. settings2 + '<br/>' +
  6169. '<input type="checkbox" id="requireNicknames">' +
  6170. settings3 +
  6171. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6172. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6173. null,
  6174. null,
  6175. false,
  6176. "dialog.Save",
  6177. function () {
  6178. document.getElementById('lockKey').focus();
  6179. },
  6180. function (e, v) {
  6181. if (v) {
  6182. if ($('#initMuted').is(":checked")) {
  6183. // it is checked
  6184. }
  6185. if ($('#requireNicknames').is(":checked")) {
  6186. // it is checked
  6187. }
  6188. /*
  6189. var lockKey = document.getElementById('lockKey');
  6190. if (lockKey.value) {
  6191. setSharedKey(lockKey.value);
  6192. lockRoom(true);
  6193. }
  6194. */
  6195. }
  6196. }
  6197. );
  6198. };
  6199. /**
  6200. * Toggles the application in and out of full screen mode
  6201. * (a.k.a. presentation mode in Chrome).
  6202. */
  6203. my.toggleFullScreen = function () {
  6204. var fsElement = document.documentElement;
  6205. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6206. //Enter Full Screen
  6207. if (fsElement.mozRequestFullScreen) {
  6208. fsElement.mozRequestFullScreen();
  6209. }
  6210. else {
  6211. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6212. }
  6213. } else {
  6214. //Exit Full Screen
  6215. if (document.mozCancelFullScreen) {
  6216. document.mozCancelFullScreen();
  6217. } else {
  6218. document.webkitCancelFullScreen();
  6219. }
  6220. }
  6221. };
  6222. /**
  6223. * Unlocks the lock button state.
  6224. */
  6225. my.unlockLockButton = function () {
  6226. if ($("#lockIcon").hasClass("icon-security-locked"))
  6227. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6228. };
  6229. /**
  6230. * Updates the lock button state to locked.
  6231. */
  6232. my.lockLockButton = function () {
  6233. if ($("#lockIcon").hasClass("icon-security"))
  6234. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6235. };
  6236. /**
  6237. * Shows or hides authentication button
  6238. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6239. */
  6240. my.showAuthenticateButton = function (show) {
  6241. if (show) {
  6242. $('#authentication').css({display: "inline"});
  6243. }
  6244. else {
  6245. $('#authentication').css({display: "none"});
  6246. }
  6247. };
  6248. // Shows or hides the 'recording' button.
  6249. my.showRecordingButton = function (show) {
  6250. if (!config.enableRecording) {
  6251. return;
  6252. }
  6253. if (show) {
  6254. $('#recording').css({display: "inline"});
  6255. }
  6256. else {
  6257. $('#recording').css({display: "none"});
  6258. }
  6259. };
  6260. // Sets the state of the recording button
  6261. my.setRecordingButtonState = function (isRecording) {
  6262. var selector = $('#recordButton');
  6263. if (isRecording) {
  6264. selector.removeClass("icon-recEnable");
  6265. selector.addClass("icon-recEnable active");
  6266. } else {
  6267. selector.removeClass("icon-recEnable active");
  6268. selector.addClass("icon-recEnable");
  6269. }
  6270. };
  6271. // Shows or hides SIP calls button
  6272. my.showSipCallButton = function (show) {
  6273. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6274. $('#sipCallButton').css({display: "inline-block"});
  6275. } else {
  6276. $('#sipCallButton').css({display: "none"});
  6277. }
  6278. };
  6279. // Shows or hides the dialpad button
  6280. my.showDialPadButton = function (show) {
  6281. if (show) {
  6282. $('#dialPadButton').css({display: "inline-block"});
  6283. } else {
  6284. $('#dialPadButton').css({display: "none"});
  6285. }
  6286. };
  6287. /**
  6288. * Displays user authenticated identity name(login).
  6289. * @param authIdentity identity name to be displayed.
  6290. */
  6291. my.setAuthenticatedIdentity = function (authIdentity) {
  6292. if (authIdentity) {
  6293. var selector = $('#toolbar_auth_identity');
  6294. selector.css({display: "list-item"});
  6295. selector.text(authIdentity);
  6296. } else {
  6297. $('#toolbar_auth_identity').css({display: "none"});
  6298. }
  6299. };
  6300. /**
  6301. * Shows/hides login button.
  6302. * @param show <tt>true</tt> to show
  6303. */
  6304. my.showLoginButton = function (show) {
  6305. if (show) {
  6306. $('#toolbar_button_login').css({display: "list-item"});
  6307. } else {
  6308. $('#toolbar_button_login').css({display: "none"});
  6309. }
  6310. };
  6311. /**
  6312. * Shows/hides logout button.
  6313. * @param show <tt>true</tt> to show
  6314. */
  6315. my.showLogoutButton = function (show) {
  6316. if (show) {
  6317. $('#toolbar_button_logout').css({display: "list-item"});
  6318. } else {
  6319. $('#toolbar_button_logout').css({display: "none"});
  6320. }
  6321. };
  6322. /**
  6323. * Sets the state of the button. The button has blue glow if desktop
  6324. * streaming is active.
  6325. * @param active the state of the desktop streaming.
  6326. */
  6327. my.changeDesktopSharingButtonState = function (active) {
  6328. var button = $("#desktopsharing > a");
  6329. if (active)
  6330. {
  6331. button.addClass("glow");
  6332. }
  6333. else
  6334. {
  6335. button.removeClass("glow");
  6336. }
  6337. };
  6338. return my;
  6339. }(Toolbar || {}));
  6340. module.exports = Toolbar;
  6341. },{"../../../service/authentication/AuthenticationEvents":107,"../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){
  6342. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  6343. var toolbarTimeoutObject,
  6344. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6345. function showDesktopSharingButton() {
  6346. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6347. $('#desktopsharing').css({display: "inline"});
  6348. } else {
  6349. $('#desktopsharing').css({display: "none"});
  6350. }
  6351. }
  6352. /**
  6353. * Hides the toolbar.
  6354. */
  6355. function hideToolbar() {
  6356. if(config.alwaysVisibleToolbar)
  6357. return;
  6358. var header = $("#header"),
  6359. bottomToolbar = $("#bottomToolbar");
  6360. var isToolbarHover = false;
  6361. header.find('*').each(function () {
  6362. var id = $(this).attr('id');
  6363. if ($("#" + id + ":hover").length > 0) {
  6364. isToolbarHover = true;
  6365. }
  6366. });
  6367. if ($("#bottomToolbar:hover").length > 0) {
  6368. isToolbarHover = true;
  6369. }
  6370. clearTimeout(toolbarTimeoutObject);
  6371. toolbarTimeoutObject = null;
  6372. if (!isToolbarHover) {
  6373. header.hide("slide", { direction: "up", duration: 300});
  6374. $('#subject').animate({top: "-=40"}, 300);
  6375. if ($("#remoteVideos").hasClass("hidden")) {
  6376. bottomToolbar.hide(
  6377. "slide", {direction: "right", duration: 300});
  6378. }
  6379. }
  6380. else {
  6381. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6382. }
  6383. }
  6384. var ToolbarToggler = {
  6385. /**
  6386. * Shows the main toolbar.
  6387. */
  6388. showToolbar: function () {
  6389. var header = $("#header"),
  6390. bottomToolbar = $("#bottomToolbar");
  6391. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6392. header.show("slide", { direction: "up", duration: 300});
  6393. $('#subject').animate({top: "+=40"}, 300);
  6394. if (!bottomToolbar.is(":visible")) {
  6395. bottomToolbar.show(
  6396. "slide", {direction: "right", duration: 300});
  6397. }
  6398. if (toolbarTimeoutObject) {
  6399. clearTimeout(toolbarTimeoutObject);
  6400. toolbarTimeoutObject = null;
  6401. }
  6402. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6403. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6404. }
  6405. if (APP.xmpp.isModerator())
  6406. {
  6407. // TODO: Enable settings functionality.
  6408. // Need to uncomment the settings button in index.html.
  6409. // $('#settingsButton').css({visibility:"visible"});
  6410. }
  6411. // Show/hide desktop sharing button
  6412. showDesktopSharingButton();
  6413. },
  6414. /**
  6415. * Docks/undocks the toolbar.
  6416. *
  6417. * @param isDock indicates what operation to perform
  6418. */
  6419. dockToolbar: function (isDock) {
  6420. if (isDock) {
  6421. // First make sure the toolbar is shown.
  6422. if (!$('#header').is(':visible')) {
  6423. this.showToolbar();
  6424. }
  6425. // Then clear the time out, to dock the toolbar.
  6426. if (toolbarTimeoutObject) {
  6427. clearTimeout(toolbarTimeoutObject);
  6428. toolbarTimeoutObject = null;
  6429. }
  6430. }
  6431. else {
  6432. if (!$('#header').is(':visible')) {
  6433. this.showToolbar();
  6434. }
  6435. else {
  6436. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6437. }
  6438. }
  6439. },
  6440. showDesktopSharingButton: showDesktopSharingButton
  6441. };
  6442. module.exports = ToolbarToggler;
  6443. },{}],30:[function(require,module,exports){
  6444. var JitsiPopover = (function () {
  6445. /**
  6446. * Constructs new JitsiPopover and attaches it to the element
  6447. * @param element jquery selector
  6448. * @param options the options for the popover.
  6449. * @constructor
  6450. */
  6451. function JitsiPopover(element, options)
  6452. {
  6453. this.options = {
  6454. skin: "white",
  6455. content: ""
  6456. };
  6457. if(options)
  6458. {
  6459. if(options.skin)
  6460. this.options.skin = options.skin;
  6461. if(options.content)
  6462. this.options.content = options.content;
  6463. }
  6464. this.elementIsHovered = false;
  6465. this.popoverIsHovered = false;
  6466. this.popoverShown = false;
  6467. element.data("jitsi_popover", this);
  6468. this.element = element;
  6469. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6470. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6471. '<div class="jitsiPopupmenuPadding"></div></div>';
  6472. var self = this;
  6473. this.element.on("mouseenter", function () {
  6474. self.elementIsHovered = true;
  6475. self.show();
  6476. }).on("mouseleave", function () {
  6477. self.elementIsHovered = false;
  6478. setTimeout(function () {
  6479. self.hide();
  6480. }, 10);
  6481. });
  6482. }
  6483. /**
  6484. * Shows the popover
  6485. */
  6486. JitsiPopover.prototype.show = function () {
  6487. this.createPopover();
  6488. this.popoverShown = true;
  6489. };
  6490. /**
  6491. * Hides the popover
  6492. */
  6493. JitsiPopover.prototype.hide = function () {
  6494. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  6495. {
  6496. this.forceHide();
  6497. }
  6498. };
  6499. /**
  6500. * Hides the popover
  6501. */
  6502. JitsiPopover.prototype.forceHide = function () {
  6503. $(".jitsipopover").remove();
  6504. this.popoverShown = false;
  6505. };
  6506. /**
  6507. * Creates the popover html
  6508. */
  6509. JitsiPopover.prototype.createPopover = function () {
  6510. $("body").append(this.template);
  6511. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6512. var self = this;
  6513. $(".jitsipopover").on("mouseenter", function () {
  6514. self.popoverIsHovered = true;
  6515. }).on("mouseleave", function () {
  6516. self.popoverIsHovered = false;
  6517. self.hide();
  6518. });
  6519. this.refreshPosition();
  6520. };
  6521. /**
  6522. * Refreshes the position of the popover
  6523. */
  6524. JitsiPopover.prototype.refreshPosition = function () {
  6525. $(".jitsipopover").position({
  6526. my: "bottom",
  6527. at: "top",
  6528. collision: "fit",
  6529. of: this.element,
  6530. using: function (position, elements) {
  6531. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  6532. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  6533. $(".jitsipopover > .arrow").css({left: calcLeft});
  6534. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  6535. }
  6536. });
  6537. };
  6538. /**
  6539. * Updates the content of popover.
  6540. * @param content new content
  6541. */
  6542. JitsiPopover.prototype.updateContent = function (content) {
  6543. this.options.content = content;
  6544. if(!this.popoverShown)
  6545. return;
  6546. $(".jitsipopover").remove();
  6547. this.createPopover();
  6548. };
  6549. return JitsiPopover;
  6550. })();
  6551. module.exports = JitsiPopover;
  6552. },{}],31:[function(require,module,exports){
  6553. /* global $, APP, jQuery, toastr */
  6554. var messageHandler = (function(my) {
  6555. /**
  6556. * Shows a message to the user.
  6557. *
  6558. * @param titleString the title of the message
  6559. * @param messageString the text of the message
  6560. */
  6561. my.openMessageDialog = function(titleKey, messageKey) {
  6562. var title = null;
  6563. if(titleKey)
  6564. {
  6565. title = APP.translation.generateTranslationHTML(titleKey);
  6566. }
  6567. var message = APP.translation.generateTranslationHTML(messageKey);
  6568. $.prompt(message,
  6569. {
  6570. title: title,
  6571. persistent: false
  6572. }
  6573. );
  6574. };
  6575. /**
  6576. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6577. *
  6578. * @param titleString the title of the message
  6579. * @param msgString the text of the message
  6580. * @param persistent boolean value which determines whether the message is persistent or not
  6581. * @param leftButton the fist button's text
  6582. * @param submitFunction function to be called on submit
  6583. * @param loadedFunction function to be called after the prompt is fully loaded
  6584. * @param closeFunction function to be called after the prompt is closed
  6585. * @param focus optional focus selector or button index to be focused after
  6586. * the dialog is opened
  6587. * @param defaultButton index of default button which will be activated when
  6588. * the user press 'enter'. Indexed from 0.
  6589. */
  6590. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6591. persistent, leftButtonKey, submitFunction, loadedFunction,
  6592. closeFunction, focus, defaultButton)
  6593. {
  6594. var buttons = [];
  6595. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6596. buttons.push({ title: leftButton, value: true});
  6597. var cancelButton
  6598. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6599. buttons.push({title: cancelButton, value: false});
  6600. var message = msgString, title = titleString;
  6601. if (titleKey)
  6602. {
  6603. title = APP.translation.generateTranslationHTML(titleKey);
  6604. }
  6605. if (msgKey) {
  6606. message = APP.translation.generateTranslationHTML(msgKey);
  6607. }
  6608. $.prompt(message, {
  6609. title: title,
  6610. persistent: false,
  6611. buttons: buttons,
  6612. defaultButton: defaultButton,
  6613. focus: focus,
  6614. loaded: loadedFunction,
  6615. submit: submitFunction,
  6616. close: closeFunction
  6617. });
  6618. };
  6619. /**
  6620. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6621. *
  6622. * @param titleString the title of the message
  6623. * @param msgString the text of the message
  6624. * @param persistent boolean value which determines whether the message is persistent or not
  6625. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  6626. * that will be passed to submitFunction
  6627. * @param submitFunction function to be called on submit
  6628. * @param loadedFunction function to be called after the prompt is fully loaded
  6629. */
  6630. my.openDialog = function (titleString, msgString, persistent, buttons,
  6631. submitFunction, loadedFunction) {
  6632. var args = {
  6633. title: titleString,
  6634. persistent: persistent,
  6635. buttons: buttons,
  6636. defaultButton: 1,
  6637. loaded: loadedFunction,
  6638. submit: submitFunction
  6639. };
  6640. if (persistent) {
  6641. args.closeText = '';
  6642. }
  6643. return new Impromptu(msgString, args);
  6644. };
  6645. /**
  6646. * Closes currently opened dialog.
  6647. */
  6648. my.closeDialog = function () {
  6649. $.prompt.close();
  6650. };
  6651. /**
  6652. * Shows a dialog with different states to the user.
  6653. *
  6654. * @param statesObject object containing all the states of the dialog
  6655. */
  6656. my.openDialogWithStates = function (statesObject, options) {
  6657. return new Impromptu(statesObject, options);
  6658. };
  6659. /**
  6660. * Opens new popup window for given <tt>url</tt> centered over current
  6661. * window.
  6662. *
  6663. * @param url the URL to be displayed in the popup window
  6664. * @param w the width of the popup window
  6665. * @param h the height of the popup window
  6666. * @param onPopupClosed optional callback function called when popup window
  6667. * has been closed.
  6668. *
  6669. * @returns popup window object if opened successfully or undefined
  6670. * in case we failed to open it(popup blocked)
  6671. */
  6672. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6673. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6674. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6675. var popup = window.open(
  6676. url, '_blank',
  6677. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6678. if (popup && onPopupClosed) {
  6679. var pollTimer = window.setInterval(function () {
  6680. if (popup.closed !== false) {
  6681. window.clearInterval(pollTimer);
  6682. onPopupClosed();
  6683. }
  6684. }, 200);
  6685. }
  6686. return popup;
  6687. };
  6688. /**
  6689. * Shows a dialog prompting the user to send an error report.
  6690. *
  6691. * @param titleString the title of the message
  6692. * @param msgString the text of the message
  6693. * @param error the error that is being reported
  6694. */
  6695. my.openReportDialog = function(titleKey, msgKey, error) {
  6696. my.openMessageDialog(titleKey, msgKey);
  6697. console.log(error);
  6698. //FIXME send the error to the server
  6699. };
  6700. /**
  6701. * Shows an error dialog to the user.
  6702. * @param title the title of the message
  6703. * @param message the text of the messafe
  6704. */
  6705. my.showError = function(titleKey, msgKey) {
  6706. if(!titleKey) {
  6707. titleKey = "dialog.oops";
  6708. }
  6709. if(!msgKey)
  6710. {
  6711. msgKey = "dialog.defaultError";
  6712. }
  6713. messageHandler.openMessageDialog(titleKey, msgKey);
  6714. };
  6715. my.notify = function(displayName, displayNameKey,
  6716. cls, messageKey, messageArguments, options) {
  6717. var displayNameSpan = '<span class="nickname" ';
  6718. if(displayName)
  6719. {
  6720. displayNameSpan += ">" + displayName;
  6721. }
  6722. else
  6723. {
  6724. displayNameSpan += "data-i18n='" + displayNameKey +
  6725. "'>" + APP.translation.translateString(displayNameKey);
  6726. }
  6727. displayNameSpan += "</span>";
  6728. toastr.info(
  6729. displayNameSpan + '<br>' +
  6730. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6731. (messageArguments?
  6732. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6733. : "") + ">" +
  6734. APP.translation.translateString(messageKey,
  6735. messageArguments) +
  6736. '</span>', null, options);
  6737. };
  6738. return my;
  6739. }(messageHandler || {}));
  6740. module.exports = messageHandler;
  6741. },{}],32:[function(require,module,exports){
  6742. var UIEvents = require("../../../service/UI/UIEvents");
  6743. var nickname = null;
  6744. var eventEmitter = null;
  6745. var NickanameHandler = {
  6746. init: function (emitter) {
  6747. eventEmitter = emitter;
  6748. var storedDisplayName = window.localStorage.displayname;
  6749. if (storedDisplayName) {
  6750. nickname = storedDisplayName;
  6751. }
  6752. },
  6753. setNickname: function (newNickname) {
  6754. if (!newNickname || nickname === newNickname)
  6755. return;
  6756. nickname = newNickname;
  6757. window.localStorage.displayname = nickname;
  6758. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6759. },
  6760. getNickname: function () {
  6761. return nickname;
  6762. },
  6763. addListener: function (type, listener) {
  6764. eventEmitter.on(type, listener);
  6765. }
  6766. };
  6767. module.exports = NickanameHandler;
  6768. },{"../../../service/UI/UIEvents":106}],33:[function(require,module,exports){
  6769. /**
  6770. * Created by hristo on 12/22/14.
  6771. */
  6772. module.exports = {
  6773. /**
  6774. * Returns the available video width.
  6775. */
  6776. getAvailableVideoWidth: function (isVisible) {
  6777. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6778. if(typeof isVisible === "undefined" || isVisible === null)
  6779. isVisible = PanelToggler.isVisible();
  6780. var rightPanelWidth
  6781. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6782. return window.innerWidth - rightPanelWidth;
  6783. },
  6784. /**
  6785. * Changes the style class of the element given by id.
  6786. */
  6787. buttonClick: function(id, classname) {
  6788. $(id).toggleClass(classname); // add the class to the clicked element
  6789. },
  6790. /**
  6791. * Returns the text width for the given element.
  6792. *
  6793. * @param el the element
  6794. */
  6795. getTextWidth: function (el) {
  6796. return (el.clientWidth + 1);
  6797. },
  6798. /**
  6799. * Returns the text height for the given element.
  6800. *
  6801. * @param el the element
  6802. */
  6803. getTextHeight: function (el) {
  6804. return (el.clientHeight + 1);
  6805. },
  6806. /**
  6807. * Plays the sound given by id.
  6808. *
  6809. * @param id the identifier of the audio element.
  6810. */
  6811. playSoundNotification: function (id) {
  6812. document.getElementById(id).play();
  6813. },
  6814. /**
  6815. * Escapes the given text.
  6816. */
  6817. escapeHtml: function (unsafeText) {
  6818. return $('<div/>').text(unsafeText).html();
  6819. },
  6820. imageToGrayScale: function (canvas) {
  6821. var context = canvas.getContext('2d');
  6822. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6823. var pixels = imgData.data;
  6824. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6825. var grayscale
  6826. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  6827. pixels[i ] = grayscale; // red
  6828. pixels[i+1] = grayscale; // green
  6829. pixels[i+2] = grayscale; // blue
  6830. // pixels[i+3] is alpha
  6831. }
  6832. // redraw the image in black & white
  6833. context.putImageData(imgData, 0, 0);
  6834. },
  6835. setTooltip: function (element, key, position) {
  6836. element.setAttribute("data-i18n", "[data-content]" + key);
  6837. element.setAttribute("data-toggle", "popover");
  6838. element.setAttribute("data-placement", position);
  6839. element.setAttribute("data-html", true);
  6840. element.setAttribute("data-container", "body");
  6841. }
  6842. };
  6843. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6844. var JitsiPopover = require("../util/JitsiPopover");
  6845. /**
  6846. * Constructs new connection indicator.
  6847. * @param videoContainer the video container associated with the indicator.
  6848. * @constructor
  6849. */
  6850. function ConnectionIndicator(videoContainer, jid)
  6851. {
  6852. this.videoContainer = videoContainer;
  6853. this.bandwidth = null;
  6854. this.packetLoss = null;
  6855. this.bitrate = null;
  6856. this.showMoreValue = false;
  6857. this.resolution = null;
  6858. this.transport = [];
  6859. this.popover = null;
  6860. this.jid = jid;
  6861. this.create();
  6862. }
  6863. /**
  6864. * Values for the connection quality
  6865. * @type {{98: string,
  6866. * 81: string,
  6867. * 64: string,
  6868. * 47: string,
  6869. * 30: string,
  6870. * 0: string}}
  6871. */
  6872. ConnectionIndicator.connectionQualityValues = {
  6873. 98: "18px", //full
  6874. 81: "15px",//4 bars
  6875. 64: "11px",//3 bars
  6876. 47: "7px",//2 bars
  6877. 30: "3px",//1 bar
  6878. 0: "0px"//empty
  6879. };
  6880. ConnectionIndicator.getIP = function(value)
  6881. {
  6882. return value.substring(0, value.lastIndexOf(":"));
  6883. };
  6884. ConnectionIndicator.getPort = function(value)
  6885. {
  6886. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6887. };
  6888. ConnectionIndicator.getStringFromArray = function (array) {
  6889. var res = "";
  6890. for(var i = 0; i < array.length; i++)
  6891. {
  6892. res += (i === 0? "" : ", ") + array[i];
  6893. }
  6894. return res;
  6895. };
  6896. /**
  6897. * Generates the html content.
  6898. * @returns {string} the html content.
  6899. */
  6900. ConnectionIndicator.prototype.generateText = function () {
  6901. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6902. var translate = APP.translation.translateString;
  6903. if(this.bitrate === null)
  6904. {
  6905. downloadBitrate = "N/A";
  6906. uploadBitrate = "N/A";
  6907. }
  6908. else
  6909. {
  6910. downloadBitrate =
  6911. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6912. uploadBitrate =
  6913. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6914. }
  6915. if(this.packetLoss === null)
  6916. {
  6917. packetLoss = "N/A";
  6918. }
  6919. else
  6920. {
  6921. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6922. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  6923. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6924. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  6925. }
  6926. var resolutionValue = null;
  6927. if(this.resolution && this.jid != null)
  6928. {
  6929. var keys = Object.keys(this.resolution);
  6930. for(var ssrc in this.resolution)
  6931. {
  6932. resolutionValue = this.resolution[ssrc];
  6933. }
  6934. }
  6935. if(this.jid === null)
  6936. {
  6937. resolution = "";
  6938. if(this.resolution === null || !Object.keys(this.resolution) ||
  6939. Object.keys(this.resolution).length === 0)
  6940. {
  6941. resolution = "N/A";
  6942. }
  6943. else
  6944. for(i in this.resolution)
  6945. {
  6946. resolutionValue = this.resolution[i];
  6947. if(resolutionValue)
  6948. {
  6949. if(resolutionValue.height &&
  6950. resolutionValue.width)
  6951. {
  6952. resolution += (resolution === ""? "" : ", ") +
  6953. resolutionValue.width + "x" +
  6954. resolutionValue.height;
  6955. }
  6956. }
  6957. }
  6958. }
  6959. else if(!resolutionValue ||
  6960. !resolutionValue.height ||
  6961. !resolutionValue.width)
  6962. {
  6963. resolution = "N/A";
  6964. }
  6965. else
  6966. {
  6967. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6968. }
  6969. var result = "<table style='width:100%'>" +
  6970. "<tr>" +
  6971. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6972. translate("connectionindicator.bitrate") + "</span></td>" +
  6973. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6974. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6975. uploadBitrate + "</td>" +
  6976. "</tr><tr>" +
  6977. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6978. translate("connectionindicator.packetloss") + "</span></td>" +
  6979. "<td>" + packetLoss + "</td>" +
  6980. "</tr><tr>" +
  6981. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6982. translate("connectionindicator.resolution") + "</span></td>" +
  6983. "<td>" + resolution + "</td></tr></table>";
  6984. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6985. result += "<div class=\"jitsipopover_showmore\" " +
  6986. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6987. this.jid + "')\" data-i18n='connectionindicator." +
  6988. (this.showMoreValue ? "less" : "more") + "'>" +
  6989. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6990. "</div><br />";
  6991. }
  6992. if(this.showMoreValue)
  6993. {
  6994. var downloadBandwidth, uploadBandwidth, transport;
  6995. if(this.bandwidth === null)
  6996. {
  6997. downloadBandwidth = "N/A";
  6998. uploadBandwidth = "N/A";
  6999. }
  7000. else
  7001. {
  7002. downloadBandwidth = this.bandwidth.download?
  7003. this.bandwidth.download + " Kbps" :
  7004. "N/A";
  7005. uploadBandwidth = this.bandwidth.upload?
  7006. this.bandwidth.upload + " Kbps" :
  7007. "N/A";
  7008. }
  7009. if(!this.transport || this.transport.length === 0)
  7010. {
  7011. transport = "<tr>" +
  7012. "<td><span class='jitsipopover_blue' " +
  7013. "data-i18n='connectionindicator.address'>" +
  7014. translate("connectionindicator.address") + "</span></td>" +
  7015. "<td> N/A</td></tr>";
  7016. }
  7017. else
  7018. {
  7019. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7020. for(i = 0; i < this.transport.length; i++)
  7021. {
  7022. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7023. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7024. var localIP =
  7025. ConnectionIndicator.getIP(this.transport[i].localip);
  7026. var localPort =
  7027. ConnectionIndicator.getPort(this.transport[i].localip);
  7028. if(data.remoteIP.indexOf(ip) == -1)
  7029. {
  7030. data.remoteIP.push(ip);
  7031. }
  7032. if(data.remotePort.indexOf(port) == -1)
  7033. {
  7034. data.remotePort.push(port);
  7035. }
  7036. if(data.localIP.indexOf(localIP) == -1)
  7037. {
  7038. data.localIP.push(localIP);
  7039. }
  7040. if(data.localPort.indexOf(localPort) == -1)
  7041. {
  7042. data.localPort.push(localPort);
  7043. }
  7044. }
  7045. var local_address_key = "connectionindicator.localaddress";
  7046. var remote_address_key = "connectionindicator.remoteaddress";
  7047. var localTransport =
  7048. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7049. local_address_key +"' data-i18n-options='" +
  7050. JSON.stringify({count: data.localIP.length}) + "'>" +
  7051. translate(local_address_key, {count: data.localIP.length}) +
  7052. "</span></td><td> " +
  7053. ConnectionIndicator.getStringFromArray(data.localIP) +
  7054. "</td></tr>";
  7055. transport =
  7056. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7057. remote_address_key + "' data-i18n-options='" +
  7058. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7059. translate(remote_address_key,
  7060. {count: data.remoteIP.length}) +
  7061. "</span></td><td> " +
  7062. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7063. "</td></tr>";
  7064. var key_remote = "connectionindicator.remoteport",
  7065. key_local = "connectionindicator.localport";
  7066. transport += "<tr>" +
  7067. "<td>" +
  7068. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7069. "' data-i18n-options='" +
  7070. JSON.stringify({count: this.transport.length}) + "'>" +
  7071. translate(key_remote, {count: this.transport.length}) +
  7072. "</span></td><td>";
  7073. localTransport += "<tr>" +
  7074. "<td>" +
  7075. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7076. "' data-i18n-options='" +
  7077. JSON.stringify({count: this.transport.length}) + "'>" +
  7078. translate(key_local, {count: this.transport.length}) +
  7079. "</span></td><td>";
  7080. transport +=
  7081. ConnectionIndicator.getStringFromArray(data.remotePort);
  7082. localTransport +=
  7083. ConnectionIndicator.getStringFromArray(data.localPort);
  7084. transport += "</td></tr>";
  7085. transport += localTransport + "</td></tr>";
  7086. transport +="<tr>" +
  7087. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7088. translate("connectionindicator.transport") + "</span></td>" +
  7089. "<td>" + this.transport[0].type + "</td></tr>";
  7090. }
  7091. result += "<table style='width:100%'>" +
  7092. "<tr>" +
  7093. "<td>" +
  7094. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7095. translate("connectionindicator.bandwidth") + "</span>" +
  7096. "</td><td>" +
  7097. "<span class='jitsipopover_green'>&darr;</span>" +
  7098. downloadBandwidth +
  7099. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7100. uploadBandwidth + "</td></tr>";
  7101. result += transport + "</table>";
  7102. }
  7103. return result;
  7104. };
  7105. /**
  7106. * Shows or hide the additional information.
  7107. */
  7108. ConnectionIndicator.prototype.showMore = function () {
  7109. this.showMoreValue = !this.showMoreValue;
  7110. this.updatePopoverData();
  7111. };
  7112. function createIcon(classes)
  7113. {
  7114. var icon = document.createElement("span");
  7115. for(var i in classes)
  7116. {
  7117. icon.classList.add(classes[i]);
  7118. }
  7119. icon.appendChild(
  7120. document.createElement("i")).classList.add("icon-connection");
  7121. return icon;
  7122. }
  7123. /**
  7124. * Creates the indicator
  7125. */
  7126. ConnectionIndicator.prototype.create = function () {
  7127. this.connectionIndicatorContainer = document.createElement("div");
  7128. this.connectionIndicatorContainer.className = "connectionindicator";
  7129. this.connectionIndicatorContainer.style.display = "none";
  7130. this.videoContainer.container.appendChild(this.connectionIndicatorContainer);
  7131. this.popover = new JitsiPopover(
  7132. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7133. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7134. APP.translation.translateString("connectionindicator.na") + "</div>",
  7135. skin: "black"});
  7136. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7137. createIcon(["connection", "connection_empty"]));
  7138. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7139. createIcon(["connection", "connection_full"]));
  7140. };
  7141. /**
  7142. * Removes the indicator
  7143. */
  7144. ConnectionIndicator.prototype.remove = function()
  7145. {
  7146. if (this.connectionIndicatorContainer.parentNode) {
  7147. this.connectionIndicatorContainer.parentNode.removeChild(
  7148. this.connectionIndicatorContainer);
  7149. }
  7150. this.popover.forceHide();
  7151. };
  7152. /**
  7153. * Updates the data of the indicator
  7154. * @param percent the percent of connection quality
  7155. * @param object the statistics data.
  7156. */
  7157. ConnectionIndicator.prototype.updateConnectionQuality =
  7158. function (percent, object) {
  7159. if(percent === null)
  7160. {
  7161. this.connectionIndicatorContainer.style.display = "none";
  7162. this.popover.forceHide();
  7163. return;
  7164. }
  7165. else
  7166. {
  7167. if(this.connectionIndicatorContainer.style.display == "none") {
  7168. this.connectionIndicatorContainer.style.display = "block";
  7169. this.videoContainer.updateIconPositions();
  7170. }
  7171. }
  7172. this.bandwidth = object.bandwidth;
  7173. this.bitrate = object.bitrate;
  7174. this.packetLoss = object.packetLoss;
  7175. this.transport = object.transport;
  7176. if(object.resolution)
  7177. {
  7178. this.resolution = object.resolution;
  7179. }
  7180. for(var quality in ConnectionIndicator.connectionQualityValues)
  7181. {
  7182. if(percent >= quality)
  7183. {
  7184. this.fullIcon.style.width =
  7185. ConnectionIndicator.connectionQualityValues[quality];
  7186. }
  7187. }
  7188. this.updatePopoverData();
  7189. };
  7190. /**
  7191. * Updates the resolution
  7192. * @param resolution the new resolution
  7193. */
  7194. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7195. this.resolution = resolution;
  7196. this.updatePopoverData();
  7197. };
  7198. /**
  7199. * Updates the content of the popover
  7200. */
  7201. ConnectionIndicator.prototype.updatePopoverData = function () {
  7202. this.popover.updateContent(
  7203. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7204. APP.translation.translateElement($(".connection_info"));
  7205. };
  7206. /**
  7207. * Hides the popover
  7208. */
  7209. ConnectionIndicator.prototype.hide = function () {
  7210. this.popover.forceHide();
  7211. };
  7212. /**
  7213. * Hides the indicator
  7214. */
  7215. ConnectionIndicator.prototype.hideIndicator = function () {
  7216. this.connectionIndicatorContainer.style.display = "none";
  7217. if(this.popover)
  7218. this.popover.forceHide();
  7219. };
  7220. module.exports = ConnectionIndicator;
  7221. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7222. var Avatar = require("../avatar/Avatar");
  7223. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7224. var UIUtil = require("../util/UIUtil");
  7225. var UIEvents = require("../../../service/UI/UIEvents");
  7226. var xmpp = require("../../xmpp/xmpp");
  7227. // FIXME: With Temasys we have to re-select everytime
  7228. //var video = $('#largeVideo');
  7229. var currentVideoWidth = null;
  7230. var currentVideoHeight = null;
  7231. // By default we use camera
  7232. var getVideoSize = getCameraVideoSize;
  7233. var getVideoPosition = getCameraVideoPosition;
  7234. var currentSmallVideo = null;
  7235. var oldSmallVideo = null;
  7236. /**
  7237. * Sets the size and position of the given video element.
  7238. *
  7239. * @param video the video element to position
  7240. * @param width the desired video width
  7241. * @param height the desired video height
  7242. * @param horizontalIndent the left and right indent
  7243. * @param verticalIndent the top and bottom indent
  7244. */
  7245. function positionVideo(video,
  7246. width,
  7247. height,
  7248. horizontalIndent,
  7249. verticalIndent,
  7250. animate) {
  7251. if(animate)
  7252. {
  7253. video.animate({
  7254. width: width,
  7255. height: height,
  7256. top: verticalIndent,
  7257. bottom: verticalIndent,
  7258. left: horizontalIndent,
  7259. right: horizontalIndent
  7260. },
  7261. {
  7262. queue: false,
  7263. duration: 500
  7264. });
  7265. }
  7266. else
  7267. {
  7268. video.width(width);
  7269. video.height(height);
  7270. video.css({ top: verticalIndent + 'px',
  7271. bottom: verticalIndent + 'px',
  7272. left: horizontalIndent + 'px',
  7273. right: horizontalIndent + 'px'});
  7274. }
  7275. }
  7276. /**
  7277. * Returns an array of the video dimensions, so that it keeps it's aspect
  7278. * ratio and fits available area with it's larger dimension. This method
  7279. * ensures that whole video will be visible and can leave empty areas.
  7280. *
  7281. * @return an array with 2 elements, the video width and the video height
  7282. */
  7283. function getDesktopVideoSize(videoWidth,
  7284. videoHeight,
  7285. videoSpaceWidth,
  7286. videoSpaceHeight) {
  7287. if (!videoWidth)
  7288. videoWidth = currentVideoWidth;
  7289. if (!videoHeight)
  7290. videoHeight = currentVideoHeight;
  7291. var aspectRatio = videoWidth / videoHeight;
  7292. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7293. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7294. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7295. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7296. {
  7297. availableHeight = videoSpaceHeight;
  7298. availableWidth = availableHeight * aspectRatio;
  7299. }
  7300. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7301. {
  7302. availableWidth = videoSpaceWidth;
  7303. availableHeight = availableWidth / aspectRatio;
  7304. }
  7305. return [availableWidth, availableHeight];
  7306. }
  7307. /**
  7308. * Returns an array of the video horizontal and vertical indents,
  7309. * so that if fits its parent.
  7310. *
  7311. * @return an array with 2 elements, the horizontal indent and the vertical
  7312. * indent
  7313. */
  7314. function getCameraVideoPosition(videoWidth,
  7315. videoHeight,
  7316. videoSpaceWidth,
  7317. videoSpaceHeight) {
  7318. // Parent height isn't completely calculated when we position the video in
  7319. // full screen mode and this is why we use the screen height in this case.
  7320. // Need to think it further at some point and implement it properly.
  7321. var isFullScreen = document.fullScreen ||
  7322. document.mozFullScreen ||
  7323. document.webkitIsFullScreen;
  7324. if (isFullScreen)
  7325. videoSpaceHeight = window.innerHeight;
  7326. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7327. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7328. return [horizontalIndent, verticalIndent];
  7329. }
  7330. /**
  7331. * Returns an array of the video horizontal and vertical indents.
  7332. * Centers horizontally and top aligns vertically.
  7333. *
  7334. * @return an array with 2 elements, the horizontal indent and the vertical
  7335. * indent
  7336. */
  7337. function getDesktopVideoPosition(videoWidth,
  7338. videoHeight,
  7339. videoSpaceWidth,
  7340. videoSpaceHeight) {
  7341. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7342. var verticalIndent = 0;// Top aligned
  7343. return [horizontalIndent, verticalIndent];
  7344. }
  7345. /**
  7346. * Returns an array of the video dimensions, so that it covers the screen.
  7347. * It leaves no empty areas, but some parts of the video might not be visible.
  7348. *
  7349. * @return an array with 2 elements, the video width and the video height
  7350. */
  7351. function getCameraVideoSize(videoWidth,
  7352. videoHeight,
  7353. videoSpaceWidth,
  7354. videoSpaceHeight) {
  7355. if (!videoWidth)
  7356. videoWidth = currentVideoWidth;
  7357. if (!videoHeight)
  7358. videoHeight = currentVideoHeight;
  7359. var aspectRatio = videoWidth / videoHeight;
  7360. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7361. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7362. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7363. availableHeight = videoSpaceHeight;
  7364. availableWidth = availableHeight * aspectRatio;
  7365. }
  7366. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7367. availableWidth = videoSpaceWidth;
  7368. availableHeight = availableWidth / aspectRatio;
  7369. }
  7370. return [availableWidth, availableHeight];
  7371. }
  7372. /**
  7373. * Updates the src of the active speaker avatar
  7374. * @param jid of the current active speaker
  7375. */
  7376. function updateActiveSpeakerAvatarSrc() {
  7377. var avatar = $("#activeSpeakerAvatar")[0];
  7378. var jid = currentSmallVideo.peerJid;
  7379. var url = Avatar.getGravatarUrl(jid);
  7380. if (avatar.src === url)
  7381. return;
  7382. var isMuted = null;
  7383. if (!currentSmallVideo.isLocal &&
  7384. !LargeVideo.VideoLayout.isInLastN(currentSmallVideo.resourceJid)) {
  7385. isMuted = true;
  7386. }
  7387. else
  7388. {
  7389. isMuted = APP.RTC.isVideoMuted(jid);
  7390. }
  7391. if (jid && isMuted !== null) {
  7392. avatar.src = url;
  7393. $("#largeVideo").css("visibility", isMuted ? "hidden" : "visible");
  7394. currentSmallVideo.showAvatar(isMuted);
  7395. }
  7396. }
  7397. function changeVideo(isVisible) {
  7398. updateActiveSpeakerAvatarSrc();
  7399. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7400. var videoTransform = document.getElementById('largeVideo')
  7401. .style.webkitTransform;
  7402. var flipX = currentSmallVideo.flipX;
  7403. if (flipX && videoTransform !== 'scaleX(-1)') {
  7404. document.getElementById('largeVideo').style.webkitTransform
  7405. = "scaleX(-1)";
  7406. }
  7407. else if (!flipX && videoTransform === 'scaleX(-1)') {
  7408. document.getElementById('largeVideo').style.webkitTransform
  7409. = "none";
  7410. }
  7411. var isDesktop = APP.RTC.isVideoSrcDesktop(currentSmallVideo.peerJid);
  7412. // Change the way we'll be measuring and positioning large video
  7413. getVideoSize = isDesktop
  7414. ? getDesktopVideoSize
  7415. : getCameraVideoSize;
  7416. getVideoPosition = isDesktop
  7417. ? getDesktopVideoPosition
  7418. : getCameraVideoPosition;
  7419. // Only if the large video is currently visible.
  7420. // Disable previous dominant speaker video.
  7421. if (oldSmallVideo) {
  7422. oldSmallVideo.enableDominantSpeaker(false);
  7423. }
  7424. // Enable new dominant speaker in the remote videos section.
  7425. if (currentSmallVideo) {
  7426. currentSmallVideo.enableDominantSpeaker(true);
  7427. }
  7428. if (isVisible) {
  7429. $('#largeVideo').fadeIn(300);
  7430. }
  7431. if(oldSmallVideo)
  7432. oldSmallVideo.showAvatar();
  7433. }
  7434. var LargeVideo = {
  7435. init: function (VideoLayout, emitter) {
  7436. this.VideoLayout = VideoLayout;
  7437. this.eventEmitter = emitter;
  7438. var self = this;
  7439. // Listen for large video size updates
  7440. var largeVideo = $('#largeVideo')[0];
  7441. var onplaying = function (arg1, arg2, arg3) {
  7442. // re-select
  7443. if (RTCBrowserType.isTemasysPluginUsed())
  7444. largeVideo = $('#largeVideo')[0];
  7445. currentVideoWidth = largeVideo.videoWidth;
  7446. currentVideoHeight = largeVideo.videoHeight;
  7447. self.position(currentVideoWidth, currentVideoHeight);
  7448. };
  7449. largeVideo.onplaying = onplaying;
  7450. },
  7451. /**
  7452. * Indicates if the large video is currently visible.
  7453. *
  7454. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7455. */
  7456. isLargeVideoVisible: function() {
  7457. return $('#largeVideo').is(':visible');
  7458. },
  7459. /**
  7460. * Updates the large video with the given new video source.
  7461. */
  7462. updateLargeVideo: function(resourceJid, forceUpdate) {
  7463. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7464. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7465. if ((currentSmallVideo && currentSmallVideo.resourceJid !== resourceJid)
  7466. || forceUpdate) {
  7467. $('#activeSpeaker').css('visibility', 'hidden');
  7468. if(currentSmallVideo) {
  7469. oldSmallVideo = currentSmallVideo;
  7470. } else {
  7471. oldSmallVideo = null;
  7472. }
  7473. currentSmallVideo = newSmallVideo;
  7474. var oldJid = null;
  7475. if(oldSmallVideo)
  7476. oldJid = oldSmallVideo.peerJid;
  7477. if (oldJid !== resourceJid) {
  7478. // we want the notification to trigger even if userJid is undefined,
  7479. // or null.
  7480. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  7481. resourceJid);
  7482. }
  7483. $('#largeVideo').fadeOut(300,
  7484. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7485. } else {
  7486. if(currentSmallVideo) {
  7487. currentSmallVideo.showAvatar();
  7488. }
  7489. }
  7490. },
  7491. /**
  7492. * Shows/hides the large video.
  7493. */
  7494. setLargeVideoVisible: function(isVisible) {
  7495. if (isVisible) {
  7496. $('#largeVideo').css({visibility: 'visible'});
  7497. $('.watermark').css({visibility: 'visible'});
  7498. if(currentSmallVideo)
  7499. currentSmallVideo.enableDominantSpeaker(true);
  7500. }
  7501. else {
  7502. $('#largeVideo').css({visibility: 'hidden'});
  7503. $('#activeSpeaker').css('visibility', 'hidden');
  7504. $('.watermark').css({visibility: 'hidden'});
  7505. if(currentSmallVideo)
  7506. currentSmallVideo.enableDominantSpeaker(false);
  7507. }
  7508. },
  7509. onVideoTypeChanged: function (jid) {
  7510. if(jid && currentSmallVideo && jid === currentSmallVideo.peerJid)
  7511. {
  7512. var isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7513. getVideoSize = isDesktop
  7514. ? getDesktopVideoSize
  7515. : getCameraVideoSize;
  7516. getVideoPosition = isDesktop
  7517. ? getDesktopVideoPosition
  7518. : getCameraVideoPosition;
  7519. this.position(null, null);
  7520. }
  7521. },
  7522. /**
  7523. * Positions the large video.
  7524. *
  7525. * @param videoWidth the stream video width
  7526. * @param videoHeight the stream video height
  7527. */
  7528. position: function (videoWidth, videoHeight,
  7529. videoSpaceWidth, videoSpaceHeight, animate) {
  7530. if(!videoSpaceWidth)
  7531. videoSpaceWidth = $('#videospace').width();
  7532. if(!videoSpaceHeight)
  7533. videoSpaceHeight = window.innerHeight;
  7534. var videoSize = getVideoSize(videoWidth,
  7535. videoHeight,
  7536. videoSpaceWidth,
  7537. videoSpaceHeight);
  7538. var largeVideoWidth = videoSize[0];
  7539. var largeVideoHeight = videoSize[1];
  7540. var videoPosition = getVideoPosition(largeVideoWidth,
  7541. largeVideoHeight,
  7542. videoSpaceWidth,
  7543. videoSpaceHeight);
  7544. var horizontalIndent = videoPosition[0];
  7545. var verticalIndent = videoPosition[1];
  7546. positionVideo($('#largeVideo'),
  7547. largeVideoWidth,
  7548. largeVideoHeight,
  7549. horizontalIndent, verticalIndent, animate);
  7550. },
  7551. isLargeVideoOnTop: function () {
  7552. var Etherpad = require("../etherpad/Etherpad");
  7553. var Prezi = require("../prezi/Prezi");
  7554. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  7555. },
  7556. resize: function (animate, isVisible, completeFunction) {
  7557. var availableHeight = window.innerHeight;
  7558. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7559. if (availableWidth < 0 || availableHeight < 0) return;
  7560. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7561. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7562. $('#activeSpeaker').css('top', top);
  7563. if(animate)
  7564. {
  7565. $('#videospace').animate({
  7566. right: window.innerWidth - availableWidth,
  7567. width: availableWidth,
  7568. height: availableHeight
  7569. },
  7570. {
  7571. queue: false,
  7572. duration: 500,
  7573. complete: completeFunction
  7574. });
  7575. $('#largeVideoContainer').animate({
  7576. width: availableWidth,
  7577. height: availableHeight
  7578. },
  7579. {
  7580. queue: false,
  7581. duration: 500
  7582. });
  7583. }
  7584. else
  7585. {
  7586. $('#videospace').width(availableWidth);
  7587. $('#videospace').height(availableHeight);
  7588. $('#largeVideoContainer').width(availableWidth);
  7589. $('#largeVideoContainer').height(availableHeight);
  7590. }
  7591. return [availableWidth, availableHeight];
  7592. },
  7593. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7594. var size = this.resize(true, isVisible, completeFunction);
  7595. this.position(null, null, size[0], size[1], true);
  7596. },
  7597. getResourceJid: function () {
  7598. if(!currentSmallVideo)
  7599. return null;
  7600. return currentSmallVideo.resourceJid;
  7601. },
  7602. updateAvatar: function (resourceJid) {
  7603. if (resourceJid === this.getResourceJid()) {
  7604. updateActiveSpeakerAvatarSrc();
  7605. }
  7606. },
  7607. showAvatar: function (resourceJid, show) {
  7608. if(this.getResourceJid() === resourceJid
  7609. && LargeVideo.isLargeVideoOnTop())
  7610. {
  7611. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7612. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7613. return true;
  7614. }
  7615. return false;
  7616. }
  7617. }
  7618. module.exports = LargeVideo;
  7619. },{"../../../service/UI/UIEvents":106,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":66,"../avatar/Avatar":16,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../util/UIUtil":33}],36:[function(require,module,exports){
  7620. var SmallVideo = require("./SmallVideo");
  7621. var ConnectionIndicator = require("./ConnectionIndicator");
  7622. var NicknameHandler = require("../util/NicknameHandler");
  7623. var UIUtil = require("../util/UIUtil");
  7624. var LargeVideo = require("./LargeVideo");
  7625. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7626. function LocalVideo(VideoLayout)
  7627. {
  7628. this.videoSpanId = "localVideoContainer";
  7629. this.container = $("#localVideoContainer").get(0);
  7630. this.VideoLayout = VideoLayout;
  7631. this.flipX = true;
  7632. this.isLocal = true;
  7633. this.peerJid = null;
  7634. this.resourceJid = null;
  7635. }
  7636. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7637. LocalVideo.prototype.constructor = LocalVideo;
  7638. /**
  7639. * Creates the edit display name button.
  7640. *
  7641. * @returns the edit button
  7642. */
  7643. function createEditDisplayNameButton() {
  7644. var editButton = document.createElement('a');
  7645. editButton.className = 'displayname';
  7646. UIUtil.setTooltip(editButton,
  7647. "videothumbnail.editnickname",
  7648. "top");
  7649. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7650. return editButton;
  7651. }
  7652. /**
  7653. * Sets the display name for the given video span id.
  7654. */
  7655. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7656. if (!this.container) {
  7657. console.warn(
  7658. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  7659. return;
  7660. }
  7661. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7662. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7663. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7664. // If we already have a display name for this video.
  7665. if (nameSpan.length > 0) {
  7666. if (nameSpan.text() !== displayName) {
  7667. if (displayName && displayName.length > 0)
  7668. {
  7669. var meHTML = APP.translation.generateTranslationHTML("me");
  7670. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7671. }
  7672. else
  7673. $('#localDisplayName').html(defaultLocalDisplayName);
  7674. }
  7675. } else {
  7676. var editButton = createEditDisplayNameButton();
  7677. nameSpan = document.createElement('span');
  7678. nameSpan.className = 'displayname';
  7679. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7680. if (displayName && displayName.length > 0) {
  7681. var meHTML = APP.translation.generateTranslationHTML("me");
  7682. nameSpan.innerHTML = displayName + meHTML;
  7683. }
  7684. else {
  7685. nameSpan.innerHTML = defaultLocalDisplayName;
  7686. }
  7687. nameSpan.id = 'localDisplayName';
  7688. this.container.appendChild(editButton);
  7689. //translates popover of edit button
  7690. APP.translation.translateElement($("a.displayname"));
  7691. var editableText = document.createElement('input');
  7692. editableText.className = 'displayname';
  7693. editableText.type = 'text';
  7694. editableText.id = 'editDisplayName';
  7695. if (displayName && displayName.length) {
  7696. editableText.value = displayName;
  7697. }
  7698. var defaultNickname = APP.translation.translateString(
  7699. "defaultNickname", {name: "Jane Pink"});
  7700. editableText.setAttribute('style', 'display:none;');
  7701. editableText.setAttribute('data-18n',
  7702. '[placeholder]defaultNickname');
  7703. editableText.setAttribute("data-i18n-options",
  7704. JSON.stringify({name: "Jane Pink"}));
  7705. editableText.setAttribute("placeholder", defaultNickname);
  7706. this.container.appendChild(editableText);
  7707. var self = this;
  7708. $('#localVideoContainer .displayname')
  7709. .bind("click", function (e) {
  7710. e.preventDefault();
  7711. e.stopPropagation();
  7712. $('#localDisplayName').hide();
  7713. $('#editDisplayName').show();
  7714. $('#editDisplayName').focus();
  7715. $('#editDisplayName').select();
  7716. $('#editDisplayName').one("focusout", function (e) {
  7717. self.VideoLayout.inputDisplayNameHandler(this.value);
  7718. });
  7719. $('#editDisplayName').on('keydown', function (e) {
  7720. if (e.keyCode === 13) {
  7721. e.preventDefault();
  7722. self.VideoLayout.inputDisplayNameHandler(this.value);
  7723. }
  7724. });
  7725. });
  7726. }
  7727. }
  7728. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7729. NicknameHandler.setNickname(name);
  7730. if (!$('#localDisplayName').is(":visible")) {
  7731. if (NicknameHandler.getNickname())
  7732. {
  7733. var meHTML = APP.translation.generateTranslationHTML("me");
  7734. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  7735. }
  7736. else
  7737. {
  7738. var defaultHTML = APP.translation.generateTranslationHTML(
  7739. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7740. $('#localDisplayName')
  7741. .html(defaultHTML);
  7742. }
  7743. $('#localDisplayName').show();
  7744. }
  7745. $('#editDisplayName').hide();
  7746. }
  7747. LocalVideo.prototype.createConnectionIndicator = function()
  7748. {
  7749. if(this.connectionIndicator)
  7750. return;
  7751. this.connectionIndicator
  7752. = new ConnectionIndicator(this, null);
  7753. }
  7754. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7755. var self = this;
  7756. function localVideoClick(event) {
  7757. // FIXME: with Temasys plugin event arg is not an event, but
  7758. // the clicked object itself, so we have to skip this call
  7759. if (event.stopPropagation) {
  7760. event.stopPropagation();
  7761. }
  7762. self.VideoLayout.handleVideoThumbClicked(
  7763. false,
  7764. APP.xmpp.myResource());
  7765. }
  7766. $('#localVideoContainer').off('click');
  7767. $('#localVideoContainer').on('click', localVideoClick);
  7768. // Add hover handler
  7769. $('#localVideoContainer').hover(
  7770. function() {
  7771. self.showDisplayName(true);
  7772. },
  7773. function() {
  7774. if (!LargeVideo.isLargeVideoVisible()
  7775. || APP.xmpp.myResource() !== LargeVideo.getResourceJid())
  7776. self.showDisplayName(false);
  7777. }
  7778. );
  7779. if(isMuted)
  7780. {
  7781. APP.UI.setVideoMute(true);
  7782. return;
  7783. }
  7784. this.flipX = (stream.videoType == "screen")? false : true;
  7785. var localVideo = document.createElement('video');
  7786. localVideo.id = 'localVideo_' +
  7787. APP.RTC.getStreamID(stream.getOriginalStream());
  7788. if (!RTCBrowserType.isIExplorer()) {
  7789. localVideo.autoplay = true;
  7790. localVideo.volume = 0; // is it required if audio is separated ?
  7791. }
  7792. localVideo.oncontextmenu = function () { return false; };
  7793. var localVideoContainer = document.getElementById('localVideoWrapper');
  7794. localVideoContainer.appendChild(localVideo);
  7795. var localVideoSelector = $('#' + localVideo.id);
  7796. // Add click handler to both video and video wrapper elements in case
  7797. // there's no video.
  7798. // onclick has to be used with Temasys plugin
  7799. localVideo.onclick = localVideoClick;
  7800. if (this.flipX) {
  7801. localVideoSelector.addClass("flipVideoX");
  7802. }
  7803. // Attach WebRTC stream
  7804. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7805. // Add stream ended handler
  7806. stream.getOriginalStream().onended = function () {
  7807. // We have to re-select after attach when Temasys plugin is used,
  7808. // because <video> element is replaced with <object>
  7809. localVideo = $('#' + localVideo.id)[0];
  7810. localVideoContainer.removeChild(localVideo);
  7811. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7812. };
  7813. }
  7814. LocalVideo.prototype.joined = function (jid) {
  7815. this.peerJid = jid;
  7816. this.resourceJid = Strophe.getResourceFromJid(jid);
  7817. }
  7818. module.exports = LocalVideo;
  7819. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7820. var ConnectionIndicator = require("./ConnectionIndicator");
  7821. var SmallVideo = require("./SmallVideo");
  7822. var AudioLevels = require("../audio_levels/AudioLevels");
  7823. var LargeVideo = require("./LargeVideo");
  7824. var Avatar = require("../avatar/Avatar");
  7825. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7826. function RemoteVideo(peerJid, VideoLayout)
  7827. {
  7828. this.peerJid = peerJid;
  7829. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7830. this.videoSpanId = 'participant_' + this.resourceJid;
  7831. this.VideoLayout = VideoLayout;
  7832. this.addRemoteVideoContainer();
  7833. this.connectionIndicator = new ConnectionIndicator(
  7834. this, this.peerJid);
  7835. this.setDisplayName();
  7836. var nickfield = document.createElement('span');
  7837. nickfield.className = "nick";
  7838. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7839. this.container.appendChild(nickfield);
  7840. this.flipX = false;
  7841. this.isLocal = false;
  7842. }
  7843. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7844. RemoteVideo.prototype.constructor = RemoteVideo;
  7845. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7846. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7847. if (APP.xmpp.isModerator())
  7848. this.addRemoteVideoMenu();
  7849. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7850. return this.container;
  7851. };
  7852. /**
  7853. * Adds the remote video menu element for the given <tt>jid</tt> in the
  7854. * given <tt>parentElement</tt>.
  7855. *
  7856. * @param jid the jid indicating the video for which we're adding a menu.
  7857. * @param parentElement the parent element where this menu will be added
  7858. */
  7859. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  7860. var spanElement = document.createElement('span');
  7861. spanElement.className = 'remotevideomenu';
  7862. this.container.appendChild(spanElement);
  7863. var menuElement = document.createElement('i');
  7864. menuElement.className = 'fa fa-angle-down';
  7865. menuElement.title = 'Remote user controls';
  7866. spanElement.appendChild(menuElement);
  7867. var popupmenuElement = document.createElement('ul');
  7868. popupmenuElement.className = 'popupmenu';
  7869. popupmenuElement.id
  7870. = 'remote_popupmenu_' + this.resourceJid;
  7871. spanElement.appendChild(popupmenuElement);
  7872. var muteMenuItem = document.createElement('li');
  7873. var muteLinkItem = document.createElement('a');
  7874. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  7875. if (!this.isMuted) {
  7876. muteLinkItem.innerHTML = mutedIndicator +
  7877. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7878. muteLinkItem.className = 'mutelink';
  7879. }
  7880. else {
  7881. muteLinkItem.innerHTML = mutedIndicator +
  7882. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7883. muteLinkItem.className = 'mutelink disabled';
  7884. }
  7885. var self = this;
  7886. muteLinkItem.onclick = function(){
  7887. if ($(this).attr('disabled') != undefined) {
  7888. event.preventDefault();
  7889. }
  7890. var isMute = self.isMuted == true;
  7891. APP.xmpp.setMute(self.peerJid, !isMute);
  7892. popupmenuElement.setAttribute('style', 'display:none;');
  7893. if (isMute) {
  7894. this.innerHTML = mutedIndicator +
  7895. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7896. this.className = 'mutelink disabled';
  7897. }
  7898. else {
  7899. this.innerHTML = mutedIndicator +
  7900. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7901. this.className = 'mutelink';
  7902. }
  7903. };
  7904. muteMenuItem.appendChild(muteLinkItem);
  7905. popupmenuElement.appendChild(muteMenuItem);
  7906. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  7907. var ejectMenuItem = document.createElement('li');
  7908. var ejectLinkItem = document.createElement('a');
  7909. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  7910. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  7911. ejectLinkItem.onclick = function(){
  7912. APP.xmpp.eject(self.peerJid);
  7913. popupmenuElement.setAttribute('style', 'display:none;');
  7914. };
  7915. ejectMenuItem.appendChild(ejectLinkItem);
  7916. popupmenuElement.appendChild(ejectMenuItem);
  7917. var paddingSpan = document.createElement('span');
  7918. paddingSpan.className = 'popupmenuPadding';
  7919. popupmenuElement.appendChild(paddingSpan);
  7920. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  7921. }
  7922. /**
  7923. * Removes the remote stream element corresponding to the given stream and
  7924. * parent container.
  7925. *
  7926. * @param stream the stream
  7927. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  7928. * @param container
  7929. */
  7930. RemoteVideo.prototype.removeRemoteStreamElement = function (stream, isVideo, id) {
  7931. if (!this.container)
  7932. return false;
  7933. var select = null;
  7934. if (isVideo) {
  7935. select = $('#' + id);
  7936. }
  7937. else
  7938. select = $('#' + this.videoSpanId + '>audio');
  7939. // Mark video as removed to cancel waiting loop(if video is removed
  7940. // before has started)
  7941. select.removed = true;
  7942. select.remove();
  7943. var audioCount = $('#' + this.videoSpanId + '>audio').length;
  7944. var videoCount = $('#' + this.videoSpanId + '>' + APP.RTC.getVideoElementName()).length;
  7945. if (!audioCount && !videoCount) {
  7946. console.log("Remove whole user", this.videoSpanId);
  7947. if(this.connectionIndicator)
  7948. this.connectionIndicator.remove();
  7949. // Remove whole container
  7950. if (this.container.parentNode)
  7951. this.container.parentNode.removeChild(this.container);
  7952. this.VideoLayout.resizeThumbnails();
  7953. }
  7954. if (isVideo)
  7955. this.VideoLayout.updateRemovedVideo(this.resourceJid);
  7956. };
  7957. RemoteVideo.prototype.waitForPlayback = function (stream) {
  7958. var isVideo = stream.getVideoTracks().length > 0;
  7959. if (!isVideo || stream.id === 'mixedmslabel') {
  7960. return;
  7961. }
  7962. var self = this;
  7963. var sel = this.VideoLayout.getPeerVideoSel(this.resourceJid);
  7964. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  7965. // when video playback starts
  7966. var onPlayingHandler = function () {
  7967. // FIXME: why do i have to do this for FF?
  7968. if (RTCBrowserType.isFirefox()) {
  7969. APP.RTC.attachMediaStream(sel, stream);
  7970. }
  7971. if (RTCBrowserType.isTemasysPluginUsed()) {
  7972. sel = $('#' + newElementId);
  7973. }
  7974. self.VideoLayout.videoactive(sel, self.resourceJid);
  7975. sel[0].onplaying = null;
  7976. if (RTCBrowserType.isTemasysPluginUsed()) {
  7977. // 'currentTime' is used to check if the video has started
  7978. // and the value is not set by the plugin, so we do it
  7979. sel[0].currentTime = 1;
  7980. }
  7981. };
  7982. sel[0].onplaying = onPlayingHandler;
  7983. };
  7984. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  7985. if (!this.container)
  7986. return;
  7987. var self = this;
  7988. var isVideo = stream.getVideoTracks().length > 0;
  7989. var streamElement = SmallVideo.createStreamElement(sid, stream);
  7990. var newElementId = streamElement.id;
  7991. this.container.appendChild(streamElement);
  7992. var sel = $('#' + newElementId);
  7993. sel.hide();
  7994. // If the container is currently visible we attach the stream.
  7995. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  7996. this.waitForPlayback(stream);
  7997. APP.RTC.attachMediaStream(sel, stream);
  7998. }
  7999. stream.onended = function () {
  8000. console.log('stream ended', this);
  8001. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8002. };
  8003. // Name of video element name is different for IE/Safari
  8004. var videoElem = APP.RTC.getVideoElementName();
  8005. // Add click handler.
  8006. var onClickHandler = function (event) {
  8007. /*
  8008. * FIXME It turns out that videoThumb may not exist (if there is
  8009. * no actual video).
  8010. */
  8011. var videoThumb = $('#' + self.videoSpanId + '>' + videoElem).get(0);
  8012. if (videoThumb) {
  8013. self.VideoLayout.handleVideoThumbClicked(
  8014. false,
  8015. self.resourceJid);
  8016. }
  8017. // On IE we need to populate this handler on video <object>
  8018. // and it does not give event instance as an argument,
  8019. // so we check here for methods.
  8020. if (event.stopPropagation && event.preventDefault) {
  8021. event.stopPropagation();
  8022. event.preventDefault();
  8023. }
  8024. return false;
  8025. };
  8026. this.container.onclick = onClickHandler;
  8027. // reselect
  8028. if (RTCBrowserType.isTemasysPluginUsed())
  8029. sel = $('#' + newElementId);
  8030. sel[0].onclick = onClickHandler;
  8031. //FIXME
  8032. // Add hover handler
  8033. $(this.container).hover(
  8034. function() {
  8035. self.showDisplayName(true);
  8036. },
  8037. function() {
  8038. var videoSrc = null;
  8039. var videoSelector = $('#' + self.videoSpanId + '>' + videoElem);
  8040. if (videoSelector && videoSelector.length > 0) {
  8041. videoSrc = APP.RTC.getVideoSrc(videoSelector.get(0));
  8042. }
  8043. // If the video has been "pinned" by the user we want to
  8044. // keep the display name on place.
  8045. if (!LargeVideo.isLargeVideoVisible()
  8046. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  8047. self.showDisplayName(false);
  8048. }
  8049. );
  8050. },
  8051. /**
  8052. * Show/hide peer container for the given resourceJid.
  8053. */
  8054. RemoteVideo.prototype.showPeerContainer = function (state) {
  8055. if (!this.container)
  8056. return;
  8057. var isHide = state === 'hide';
  8058. var resizeThumbnails = false;
  8059. if (!isHide) {
  8060. if (!$(this.container).is(':visible')) {
  8061. resizeThumbnails = true;
  8062. $(this.container).show();
  8063. }
  8064. this.showAvatar(state !== 'show');
  8065. }
  8066. else if ($(this.container).is(':visible') && isHide)
  8067. {
  8068. resizeThumbnails = true;
  8069. $(this.container).hide();
  8070. if(this.connectionIndicator)
  8071. this.connectionIndicator.hide();
  8072. }
  8073. if (resizeThumbnails) {
  8074. this.VideoLayout.resizeThumbnails();
  8075. }
  8076. // We want to be able to pin a participant from the contact list, even
  8077. // if he's not in the lastN set!
  8078. // ContactList.setClickable(resourceJid, !isHide);
  8079. };
  8080. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8081. if(this.connectionIndicator)
  8082. this.connectionIndicator.remove();
  8083. }
  8084. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8085. if(this.connectionIndicator)
  8086. this.connectionIndicator.hide();
  8087. }
  8088. /**
  8089. * Updates the remote video menu.
  8090. *
  8091. * @param jid the jid indicating the video for which we're adding a menu.
  8092. * @param isMuted indicates the current mute state
  8093. */
  8094. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8095. var muteMenuItem
  8096. = $('#remote_popupmenu_'
  8097. + this.resourceJid
  8098. + '>li>a.mutelink');
  8099. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8100. if (muteMenuItem.length) {
  8101. var muteLink = muteMenuItem.get(0);
  8102. if (isMuted === 'true') {
  8103. muteLink.innerHTML = mutedIndicator + ' Muted';
  8104. muteLink.className = 'mutelink disabled';
  8105. }
  8106. else {
  8107. muteLink.innerHTML = mutedIndicator + ' Mute';
  8108. muteLink.className = 'mutelink';
  8109. }
  8110. }
  8111. }
  8112. /**
  8113. * Sets the display name for the given video span id.
  8114. */
  8115. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8116. if (!this.container) {
  8117. console.warn(
  8118. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  8119. return;
  8120. }
  8121. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8122. // If we already have a display name for this video.
  8123. if (nameSpan.length > 0) {
  8124. if (displayName && displayName.length > 0)
  8125. {
  8126. $('#' + this.videoSpanId + '_name').html(displayName);
  8127. }
  8128. else if (key && key.length > 0)
  8129. {
  8130. var nameHtml = APP.translation.generateTranslationHTML(key);
  8131. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8132. }
  8133. else
  8134. $('#' + this.videoSpanId + '_name').text(
  8135. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8136. } else {
  8137. nameSpan = document.createElement('span');
  8138. nameSpan.className = 'displayname';
  8139. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8140. if (displayName && displayName.length > 0) {
  8141. nameSpan.innerText = displayName;
  8142. }
  8143. else
  8144. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8145. nameSpan.id = this.videoSpanId + '_name';
  8146. }
  8147. }
  8148. /**
  8149. * Removes remote video menu element from video element identified by
  8150. * given <tt>videoElementId</tt>.
  8151. *
  8152. * @param videoElementId the id of local or remote video element.
  8153. */
  8154. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8155. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8156. if (menuSpan.length) {
  8157. menuSpan.remove();
  8158. }
  8159. }
  8160. RemoteVideo.createContainer = function (spanId) {
  8161. var container = document.createElement('span');
  8162. container.id = spanId;
  8163. container.className = 'videocontainer';
  8164. var remotes = document.getElementById('remoteVideos');
  8165. return remotes.appendChild(container);
  8166. };
  8167. module.exports = RemoteVideo;
  8168. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8169. var UIUtil = require("../util/UIUtil");
  8170. var LargeVideo = require("./LargeVideo");
  8171. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8172. function SmallVideo(){
  8173. this.isMuted = false;
  8174. this.hasAvatar = false;
  8175. }
  8176. function setVisibility(selector, show) {
  8177. if (selector && selector.length > 0) {
  8178. selector.css("visibility", show ? "visible" : "hidden");
  8179. }
  8180. }
  8181. SmallVideo.prototype.showDisplayName = function(isShow) {
  8182. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8183. if (isShow) {
  8184. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8185. nameSpan.setAttribute("style", "display:inline-block;");
  8186. }
  8187. else {
  8188. if (nameSpan)
  8189. nameSpan.setAttribute("style", "display:none;");
  8190. }
  8191. };
  8192. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8193. if(!this.container)
  8194. return;
  8195. $("#" + this.videoSpanId + " > .noMic").remove();
  8196. $("#" + this.videoSpanId + " > .noVideo").remove();
  8197. if(!devices.audio)
  8198. {
  8199. this.container.appendChild(
  8200. document.createElement("div")).setAttribute("class","noMic");
  8201. }
  8202. if(!devices.video)
  8203. {
  8204. this.container.appendChild(
  8205. document.createElement("div")).setAttribute("class","noVideo");
  8206. }
  8207. if(!devices.audio && !devices.video)
  8208. {
  8209. $("#" + this.videoSpanId + " > .noMic").css("background-position", "75%");
  8210. $("#" + this.videoSpanId + " > .noVideo").css("background-position", "25%");
  8211. $("#" + this.videoSpanId + " > .noVideo").css("background-color", "transparent");
  8212. }
  8213. }
  8214. /**
  8215. * Shows the presence status message for the given video.
  8216. */
  8217. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8218. if (!this.container) {
  8219. // No container
  8220. return;
  8221. }
  8222. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8223. if (!statusSpan.length) {
  8224. //Add status span
  8225. statusSpan = document.createElement('span');
  8226. statusSpan.className = 'status';
  8227. statusSpan.id = this.videoSpanId + '_status';
  8228. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8229. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8230. }
  8231. // Display status
  8232. if (statusMsg && statusMsg.length) {
  8233. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8234. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8235. }
  8236. else {
  8237. // Hide
  8238. statusSpan.get(0).setAttribute("style", "display:none;");
  8239. }
  8240. };
  8241. /**
  8242. * Creates an audio or video stream element.
  8243. */
  8244. SmallVideo.createStreamElement = function (sid, stream) {
  8245. var isVideo = stream.getVideoTracks().length > 0;
  8246. var element = isVideo
  8247. ? document.createElement('video')
  8248. : document.createElement('audio');
  8249. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  8250. + sid + '_' + APP.RTC.getStreamID(stream);
  8251. element.id = id;
  8252. if (!RTCBrowserType.isIExplorer()) {
  8253. element.autoplay = true;
  8254. }
  8255. element.oncontextmenu = function () { return false; };
  8256. return element;
  8257. };
  8258. /**
  8259. * Updates the data for the indicator
  8260. * @param id the id of the indicator
  8261. * @param percent the percent for connection quality
  8262. * @param object the data
  8263. */
  8264. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8265. if(this.connectionIndicator)
  8266. this.connectionIndicator.updateConnectionQuality(percent, object);
  8267. }
  8268. SmallVideo.prototype.hideIndicator = function () {
  8269. if(this.connectionIndicator)
  8270. this.connectionIndicator.hideIndicator();
  8271. }
  8272. /**
  8273. * Shows audio muted indicator over small videos.
  8274. * @param {string} isMuted
  8275. */
  8276. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8277. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8278. if (!isMuted) {
  8279. if (audioMutedSpan.length > 0) {
  8280. audioMutedSpan.popover('hide');
  8281. audioMutedSpan.remove();
  8282. }
  8283. }
  8284. else {
  8285. if(audioMutedSpan.length == 0 ) {
  8286. audioMutedSpan = document.createElement('span');
  8287. audioMutedSpan.className = 'audioMuted';
  8288. UIUtil.setTooltip(audioMutedSpan,
  8289. "videothumbnail.mute",
  8290. "top");
  8291. this.container.appendChild(audioMutedSpan);
  8292. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8293. var mutedIndicator = document.createElement('i');
  8294. mutedIndicator.className = 'icon-mic-disabled';
  8295. audioMutedSpan.appendChild(mutedIndicator);
  8296. }
  8297. this.updateIconPositions();
  8298. }
  8299. this.isMuted = isMuted;
  8300. };
  8301. /**
  8302. * Shows video muted indicator over small videos.
  8303. */
  8304. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8305. this.showAvatar(isMuted);
  8306. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8307. if (isMuted === false) {
  8308. if (videoMutedSpan.length > 0) {
  8309. videoMutedSpan.remove();
  8310. }
  8311. }
  8312. else {
  8313. if(videoMutedSpan.length == 0) {
  8314. videoMutedSpan = document.createElement('span');
  8315. videoMutedSpan.className = 'videoMuted';
  8316. this.container.appendChild(videoMutedSpan);
  8317. var mutedIndicator = document.createElement('i');
  8318. mutedIndicator.className = 'icon-camera-disabled';
  8319. UIUtil.setTooltip(mutedIndicator,
  8320. "videothumbnail.videomute",
  8321. "top");
  8322. videoMutedSpan.appendChild(mutedIndicator);
  8323. //translate texts for muted indicator
  8324. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8325. }
  8326. this.updateIconPositions();
  8327. }
  8328. };
  8329. SmallVideo.prototype.enableDominantSpeaker = function (isEnable)
  8330. {
  8331. var displayName = this.resourceJid;
  8332. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8333. if (nameSpan.length > 0)
  8334. displayName = nameSpan.html();
  8335. console.log("UI enable dominant speaker",
  8336. displayName,
  8337. this.resourceJid,
  8338. isEnable);
  8339. if (!this.container) {
  8340. return;
  8341. }
  8342. var video = $('#' + this.videoSpanId + '>' + APP.RTC.getVideoElementName());
  8343. if (video && video.length > 0) {
  8344. if (isEnable) {
  8345. this.showDisplayName(LargeVideo.isLargeVideoOnTop());
  8346. if (!this.container.classList.contains("dominantspeaker"))
  8347. this.container.classList.add("dominantspeaker");
  8348. }
  8349. else {
  8350. this.showDisplayName(false);
  8351. if (this.container.classList.contains("dominantspeaker"))
  8352. this.container.classList.remove("dominantspeaker");
  8353. }
  8354. }
  8355. this.showAvatar();
  8356. };
  8357. SmallVideo.prototype.updateIconPositions = function () {
  8358. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8359. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8360. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8361. if(connectionIndicator.length > 0
  8362. && connectionIndicator[0].style.display != "none") {
  8363. audioMutedSpan.css({right: "23px"});
  8364. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8365. }
  8366. else
  8367. {
  8368. audioMutedSpan.css({right: "0px"});
  8369. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8370. }
  8371. }
  8372. /**
  8373. * Creates the element indicating the moderator(owner) of the conference.
  8374. *
  8375. * @param parentElement the parent element where the owner indicator will
  8376. * be added
  8377. */
  8378. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8379. // Show moderator indicator
  8380. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8381. if (!indicatorSpan || indicatorSpan.length === 0) {
  8382. indicatorSpan = document.createElement('span');
  8383. indicatorSpan.className = 'focusindicator';
  8384. this.container.appendChild(indicatorSpan);
  8385. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8386. }
  8387. if (indicatorSpan.children().length !== 0)
  8388. return;
  8389. var moderatorIndicator = document.createElement('i');
  8390. moderatorIndicator.className = 'fa fa-star';
  8391. indicatorSpan[0].appendChild(moderatorIndicator);
  8392. UIUtil.setTooltip(indicatorSpan[0],
  8393. "videothumbnail.moderator",
  8394. "top");
  8395. //translates text in focus indicators
  8396. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8397. }
  8398. SmallVideo.prototype.getSrc = function () {
  8399. var videoElement = APP.RTC.getVideoElementName();
  8400. return APP.RTC.getVideoSrc(
  8401. $('#' + this.videoSpanId).find(videoElement).get(0));
  8402. },
  8403. SmallVideo.prototype.focus = function(isFocused)
  8404. {
  8405. if(!isFocused) {
  8406. this.container.classList.remove("videoContainerFocused");
  8407. }
  8408. else
  8409. {
  8410. this.container.classList.add("videoContainerFocused");
  8411. }
  8412. }
  8413. SmallVideo.prototype.hasVideo = function () {
  8414. return $("#" + this.videoSpanId).find(
  8415. APP.RTC.getVideoElementName()).length !== 0;
  8416. }
  8417. /**
  8418. * Hides or shows the user's avatar
  8419. * @param show whether we should show the avatar or not
  8420. * video because there is no dominant speaker and no focused speaker
  8421. */
  8422. SmallVideo.prototype.showAvatar = function (show) {
  8423. if (!this.hasAvatar)
  8424. return;
  8425. var videoElem = APP.RTC.getVideoElementName();
  8426. var video = $('#' + this.videoSpanId).find(videoElem);
  8427. var avatar = $('#avatar_' + this.resourceJid);
  8428. if (show === undefined || show === null) {
  8429. if (!this.isLocal &&
  8430. !this.VideoLayout.isInLastN(this.resourceJid)) {
  8431. show = true;
  8432. }
  8433. else
  8434. {
  8435. show = APP.RTC.isVideoMuted(this.peerJid);
  8436. }
  8437. }
  8438. if (LargeVideo.showAvatar(this.resourceJid, show))
  8439. {
  8440. setVisibility(avatar, false);
  8441. setVisibility(video, false);
  8442. } else {
  8443. if (video && video.length > 0) {
  8444. setVisibility(video, !show);
  8445. }
  8446. setVisibility(avatar, show);
  8447. }
  8448. };
  8449. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8450. var thumbnail = $('#' + this.videoSpanId);
  8451. var avatar = $('#avatar_' + this.resourceJid);
  8452. this.hasAvatar = true;
  8453. // set the avatar in the thumbnail
  8454. if (avatar && avatar.length > 0) {
  8455. avatar[0].src = thumbUrl;
  8456. } else {
  8457. if (thumbnail && thumbnail.length > 0) {
  8458. avatar = document.createElement('img');
  8459. avatar.id = 'avatar_' + this.resourceJid;
  8460. avatar.className = 'userAvatar';
  8461. avatar.src = thumbUrl;
  8462. thumbnail.append(avatar);
  8463. }
  8464. }
  8465. }
  8466. module.exports = SmallVideo;
  8467. },{"../../RTC/RTCBrowserType":8,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8468. var AudioLevels = require("../audio_levels/AudioLevels");
  8469. var Avatar = require("../avatar/Avatar");
  8470. var ContactList = require("../side_pannels/contactlist/ContactList");
  8471. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8472. var UIEvents = require("../../../service/UI/UIEvents");
  8473. var RTC = require("../../RTC/RTC");
  8474. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8475. var RemoteVideo = require("./RemoteVideo");
  8476. var LargeVideo = require("./LargeVideo");
  8477. var LocalVideo = require("./LocalVideo");
  8478. var remoteVideos = {};
  8479. var localVideoThumbnail = null;
  8480. var currentDominantSpeaker = null;
  8481. var lastNCount = config.channelLastN;
  8482. var localLastNCount = config.channelLastN;
  8483. var localLastNSet = [];
  8484. var lastNEndpointsCache = [];
  8485. var lastNPickupJid = null;
  8486. var eventEmitter = null;
  8487. /**
  8488. * Currently focused video jid
  8489. * @type {String}
  8490. */
  8491. var focusedVideoResourceJid = null;
  8492. var VideoLayout = (function (my) {
  8493. my.init = function (emitter) {
  8494. eventEmitter = emitter;
  8495. localVideoThumbnail = new LocalVideo(VideoLayout);
  8496. VideoLayout.resizeLargeVideoContainer();
  8497. LargeVideo.init(VideoLayout, emitter);
  8498. };
  8499. my.isInLastN = function(resource) {
  8500. return lastNCount < 0 // lastN is disabled, return true
  8501. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  8502. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  8503. };
  8504. my.changeLocalStream = function (stream, isMuted) {
  8505. VideoLayout.changeLocalVideo(stream, isMuted);
  8506. };
  8507. my.changeLocalAudio = function(stream, isMuted) {
  8508. if (isMuted)
  8509. APP.UI.setAudioMuted(true, true);
  8510. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8511. var localAudio = document.getElementById('localAudio');
  8512. // Writing volume not allowed in IE
  8513. if (!RTCBrowserType.isIExplorer()) {
  8514. localAudio.autoplay = true;
  8515. localAudio.volume = 0;
  8516. }
  8517. };
  8518. my.changeLocalVideo = function(stream, isMuted) {
  8519. // Set default display name.
  8520. localVideoThumbnail.setDisplayName();
  8521. localVideoThumbnail.createConnectionIndicator();
  8522. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8523. localVideoThumbnail.changeVideo(stream, isMuted);
  8524. LargeVideo.updateLargeVideo(
  8525. APP.xmpp.myResource(),
  8526. /* force update only before conference starts */
  8527. !APP.xmpp.isConferenceInProgress());
  8528. };
  8529. my.mucJoined = function () {
  8530. var myResourceJid = APP.xmpp.myResource();
  8531. localVideoThumbnail.joined(APP.xmpp.myJid());
  8532. if (!LargeVideo.getResourceJid())
  8533. LargeVideo.updateLargeVideo(myResourceJid, true);
  8534. };
  8535. /**
  8536. * Adds or removes icons for not available camera and microphone.
  8537. * @param resourceJid the jid of user
  8538. * @param devices available devices
  8539. */
  8540. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8541. if(!devices)
  8542. return;
  8543. if(!resourceJid)
  8544. {
  8545. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8546. }
  8547. else
  8548. {
  8549. if(remoteVideos[resourceJid])
  8550. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8551. }
  8552. }
  8553. /**
  8554. * Checks if removed video is currently displayed and tries to display
  8555. * another one instead.
  8556. * @param removedVideoSrc src stream identifier of the video.
  8557. */
  8558. my.updateRemovedVideo = function(resourceJid) {
  8559. var videoElem = RTC.getVideoElementName();
  8560. if (resourceJid === LargeVideo.getResourceJid()) {
  8561. // this is currently displayed as large
  8562. // pick the last visible video in the row
  8563. // if nobody else is left, this picks the local video
  8564. var pick
  8565. = $('#remoteVideos>' +
  8566. 'span[id!="mixedstream"]:visible:last>' + videoElem).get(0);
  8567. if (!pick) {
  8568. console.info("Last visible video no longer exists");
  8569. pick = $('#remoteVideos>' +
  8570. 'span[id!="mixedstream"]>' + videoElem).get(0);
  8571. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  8572. // Try local video
  8573. console.info("Fallback to local video...");
  8574. pick = $('#remoteVideos>span>span>' + videoElem).get(0);
  8575. }
  8576. }
  8577. // mute if localvideo
  8578. if (pick) {
  8579. var container = pick.parentNode;
  8580. } else {
  8581. console.warn("Failed to elect large video");
  8582. container = $('#remoteVideos>span[id!="mixedstream"]:visible:last').get(0);
  8583. }
  8584. var jid = null;
  8585. if(container)
  8586. {
  8587. if(container.id == "localVideoWrapper")
  8588. {
  8589. jid = APP.xmpp.myResource();
  8590. }
  8591. else
  8592. {
  8593. jid = VideoLayout.getPeerContainerResourceJid(container);
  8594. }
  8595. }
  8596. else
  8597. return;
  8598. LargeVideo.updateLargeVideo(jid);
  8599. }
  8600. };
  8601. my.onRemoteStreamAdded = function (stream) {
  8602. if (stream.peerjid) {
  8603. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8604. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8605. remoteVideos[resourceJid].addRemoteStreamElement(
  8606. stream.sid,
  8607. stream.getOriginalStream(),
  8608. stream.ssrc);
  8609. }
  8610. };
  8611. my.getLargeVideoJid = function () {
  8612. return LargeVideo.getResourceJid();
  8613. };
  8614. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8615. resourceJid) {
  8616. if(focusedVideoResourceJid) {
  8617. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8618. if(oldSmallVideo)
  8619. oldSmallVideo.focus(false);
  8620. }
  8621. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8622. // Unlock current focused.
  8623. if (focusedVideoResourceJid === resourceJid)
  8624. {
  8625. focusedVideoResourceJid = null;
  8626. // Enable the currently set dominant speaker.
  8627. if (currentDominantSpeaker) {
  8628. if(smallVideo && smallVideo.hasVideo())
  8629. {
  8630. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8631. }
  8632. }
  8633. if (!noPinnedEndpointChangedEvent) {
  8634. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8635. }
  8636. return;
  8637. }
  8638. // Lock new video
  8639. focusedVideoResourceJid = resourceJid;
  8640. // Update focused/pinned interface.
  8641. if (resourceJid)
  8642. {
  8643. if(smallVideo)
  8644. smallVideo.focus(true);
  8645. if (!noPinnedEndpointChangedEvent) {
  8646. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8647. }
  8648. }
  8649. if (LargeVideo.getResourceJid() === resourceJid &&
  8650. LargeVideo.isLargeVideoOnTop()) {
  8651. return;
  8652. }
  8653. // Triggers a "video.selected" event. The "false" parameter indicates
  8654. // this isn't a prezi.
  8655. $(document).trigger("video.selected", [false]);
  8656. LargeVideo.updateLargeVideo(resourceJid);
  8657. // Writing volume not allowed in IE
  8658. if (!RTCBrowserType.isIExplorer()) {
  8659. $('audio').each(function (idx, el) {
  8660. el.volume = 0;
  8661. el.volume = 1;
  8662. });
  8663. }
  8664. };
  8665. /**
  8666. * Checks if container for participant identified by given peerJid exists
  8667. * in the document and creates it eventually.
  8668. *
  8669. * @param peerJid peer Jid to check.
  8670. * @param userId user email or id for setting the avatar
  8671. *
  8672. * @return Returns <tt>true</tt> if the peer container exists,
  8673. * <tt>false</tt> - otherwise
  8674. */
  8675. my.ensurePeerContainerExists = function(peerJid, userId) {
  8676. ContactList.ensureAddContact(peerJid, userId);
  8677. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8678. if(!remoteVideos[resourceJid])
  8679. {
  8680. remoteVideos[resourceJid] = new RemoteVideo(peerJid, VideoLayout);
  8681. Avatar.setUserAvatar(peerJid, userId);
  8682. // In case this is not currently in the last n we don't show it.
  8683. if (localLastNCount
  8684. && localLastNCount > 0
  8685. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  8686. remoteVideos[resourceJid].showPeerContainer('hide');
  8687. }
  8688. else
  8689. VideoLayout.resizeThumbnails();
  8690. }
  8691. };
  8692. my.inputDisplayNameHandler = function (name) {
  8693. localVideoThumbnail.inputDisplayNameHandler(name);
  8694. };
  8695. my.videoactive = function (videoelem, resourceJid) {
  8696. videoelem.show();
  8697. VideoLayout.resizeThumbnails();
  8698. // Update the large video to the last added video only if there's no
  8699. // current dominant, focused speaker or prezi playing or update it to
  8700. // the current dominant speaker.
  8701. if ((!focusedVideoResourceJid &&
  8702. !currentDominantSpeaker &&
  8703. !require("../prezi/Prezi").isPresentationVisible()) ||
  8704. (resourceJid &&
  8705. currentDominantSpeaker === resourceJid)) {
  8706. LargeVideo.updateLargeVideo(resourceJid, true);
  8707. }
  8708. }
  8709. /**
  8710. * Shows the presence status message for the given video.
  8711. */
  8712. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8713. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8714. };
  8715. /**
  8716. * Shows a visual indicator for the moderator of the conference.
  8717. */
  8718. my.showModeratorIndicator = function () {
  8719. var isModerator = APP.xmpp.isModerator();
  8720. if (isModerator) {
  8721. localVideoThumbnail.createModeratorIndicatorElement();
  8722. }
  8723. var members = APP.xmpp.getMembers();
  8724. Object.keys(members).forEach(function (jid) {
  8725. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8726. // Skip server side focus
  8727. return;
  8728. }
  8729. var resourceJid = Strophe.getResourceFromJid(jid);
  8730. var member = members[jid];
  8731. if (member.role === 'moderator') {
  8732. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8733. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8734. } else if (isModerator) {
  8735. // We are moderator, but user is not - add menu
  8736. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8737. remoteVideos[resourceJid].addRemoteVideoMenu();
  8738. }
  8739. }
  8740. });
  8741. };
  8742. /*
  8743. * Shows or hides the audio muted indicator over the local thumbnail video.
  8744. * @param {boolean} isMuted
  8745. */
  8746. my.showLocalAudioIndicator = function(isMuted) {
  8747. localVideoThumbnail.showAudioIndicator(isMuted);
  8748. };
  8749. /**
  8750. * Resizes the large video container.
  8751. */
  8752. my.resizeLargeVideoContainer = function () {
  8753. LargeVideo.resize();
  8754. VideoLayout.resizeThumbnails();
  8755. LargeVideo.position();
  8756. };
  8757. /**
  8758. * Resizes thumbnails.
  8759. */
  8760. my.resizeThumbnails = function(animate) {
  8761. var videoSpaceWidth = $('#remoteVideos').width();
  8762. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8763. var width = thumbnailSize[0];
  8764. var height = thumbnailSize[1];
  8765. $('.userAvatar').css('left', (width - height) / 2);
  8766. if(animate)
  8767. {
  8768. $('#remoteVideos').animate({
  8769. height: height
  8770. },
  8771. {
  8772. queue: false,
  8773. duration: 500
  8774. });
  8775. $('#remoteVideos>span').animate({
  8776. height: height,
  8777. width: width
  8778. },
  8779. {
  8780. queue: false,
  8781. duration: 500,
  8782. complete: function () {
  8783. $(document).trigger(
  8784. "remotevideo.resized",
  8785. [width,
  8786. height]);
  8787. }
  8788. });
  8789. }
  8790. else
  8791. {
  8792. // size videos so that while keeping AR and max height, we have a
  8793. // nice fit
  8794. $('#remoteVideos').height(height);
  8795. $('#remoteVideos>span').width(width);
  8796. $('#remoteVideos>span').height(height);
  8797. $(document).trigger("remotevideo.resized", [width, height]);
  8798. }
  8799. };
  8800. /**
  8801. * Calculates the thumbnail size.
  8802. *
  8803. * @param videoSpaceWidth the width of the video space
  8804. */
  8805. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8806. // Calculate the available height, which is the inner window height minus
  8807. // 39px for the header minus 2px for the delimiter lines on the top and
  8808. // bottom of the large video, minus the 36px space inside the remoteVideos
  8809. // container used for highlighting shadow.
  8810. var availableHeight = 100;
  8811. var numvids = $('#remoteVideos>span:visible').length;
  8812. if (localLastNCount && localLastNCount > 0) {
  8813. numvids = Math.min(localLastNCount + 1, numvids);
  8814. }
  8815. // Remove the 3px borders arround videos and border around the remote
  8816. // videos area and the 4 pixels between the local video and the others
  8817. //TODO: Find out where the 4 pixels come from and remove them
  8818. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8819. var availableWidth = availableWinWidth / numvids;
  8820. var aspectRatio = 16.0 / 9.0;
  8821. var maxHeight = Math.min(160, availableHeight);
  8822. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  8823. if (availableHeight < availableWidth / aspectRatio) {
  8824. availableWidth = Math.floor(availableHeight * aspectRatio);
  8825. }
  8826. return [availableWidth, availableHeight];
  8827. };
  8828. /**
  8829. * Returns the corresponding resource jid to the given peer container
  8830. * DOM element.
  8831. *
  8832. * @return the corresponding resource jid to the given peer container
  8833. * DOM element
  8834. */
  8835. my.getPeerContainerResourceJid = function (containerElement) {
  8836. var i = containerElement.id.indexOf('participant_');
  8837. if (i >= 0)
  8838. return containerElement.id.substring(i + 12);
  8839. };
  8840. my.getPeerVideoSel = function (peerResourceJid) {
  8841. return $('#participant_' + peerResourceJid +
  8842. '>' + APP.RTC.getVideoElementName());
  8843. };
  8844. /**
  8845. * On contact list item clicked.
  8846. */
  8847. $(ContactList).bind('contactclicked', function(event, jid) {
  8848. if (!jid) {
  8849. return;
  8850. }
  8851. if (jid == APP.xmpp.myJid()) {
  8852. $("#localVideoContainer").click();
  8853. return;
  8854. }
  8855. var resource = Strophe.getResourceFromJid(jid);
  8856. var videoSel = VideoLayout.getPeerVideoSel(resource);
  8857. if (videoSel.length > 0) {
  8858. var videoThumb = videoSel[0];
  8859. // It is not always the case that a videoThumb exists (if there is
  8860. // no actual video).
  8861. if (RTC.getVideoSrc(videoThumb)) {
  8862. // We have a video src, great! Let's update the large video
  8863. // now.
  8864. VideoLayout.handleVideoThumbClicked(
  8865. false,
  8866. Strophe.getResourceFromJid(jid));
  8867. } else {
  8868. // If we don't have a video src for jid, there's absolutely
  8869. // no point in calling handleVideoThumbClicked; Quite
  8870. // simply, it won't work because it needs an src to attach
  8871. // to the large video.
  8872. //
  8873. // Instead, we trigger the pinned endpoint changed event to
  8874. // let the bridge adjust its lastN set for myjid and store
  8875. // the pinned user in the lastNPickupJid variable to be
  8876. // picked up later by the lastN changed event handler.
  8877. lastNPickupJid = jid;
  8878. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  8879. Strophe.getResourceFromJid(jid));
  8880. }
  8881. }
  8882. });
  8883. /**
  8884. * On audio muted event.
  8885. */
  8886. my.onAudioMute = function (jid, isMuted) {
  8887. var resourceJid = Strophe.getResourceFromJid(jid);
  8888. if (resourceJid === APP.xmpp.myResource()) {
  8889. localVideoThumbnail.showAudioIndicator(isMuted);
  8890. } else {
  8891. VideoLayout.ensurePeerContainerExists(jid);
  8892. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  8893. if (APP.xmpp.isModerator()) {
  8894. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  8895. }
  8896. }
  8897. };
  8898. /**
  8899. * On video muted event.
  8900. */
  8901. my.onVideoMute = function (jid, value) {
  8902. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, value))
  8903. return;
  8904. if (jid === APP.xmpp.myJid()) {
  8905. localVideoThumbnail.showVideoIndicator(value);
  8906. } else {
  8907. var resource = Strophe.getResourceFromJid(jid);
  8908. VideoLayout.ensurePeerContainerExists(jid);
  8909. remoteVideos[resource].showVideoIndicator(value);
  8910. var el = VideoLayout.getPeerVideoSel(resource);
  8911. if (!value)
  8912. el.show();
  8913. else
  8914. el.hide();
  8915. }
  8916. };
  8917. /**
  8918. * Display name changed.
  8919. */
  8920. my.onDisplayNameChanged =
  8921. function (jid, displayName, status) {
  8922. if (jid === 'localVideoContainer'
  8923. || jid === APP.xmpp.myJid()) {
  8924. localVideoThumbnail.setDisplayName(displayName);
  8925. } else {
  8926. VideoLayout.ensurePeerContainerExists(jid);
  8927. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  8928. displayName,
  8929. status);
  8930. }
  8931. };
  8932. /**
  8933. * On dominant speaker changed event.
  8934. */
  8935. my.onDominantSpeakerChanged = function (resourceJid) {
  8936. // We ignore local user events.
  8937. if (resourceJid === APP.xmpp.myResource())
  8938. return;
  8939. var members = APP.xmpp.getMembers();
  8940. // Update the current dominant speaker.
  8941. if (resourceJid !== currentDominantSpeaker) {
  8942. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  8943. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  8944. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  8945. !members[currentJID].displayName)) {
  8946. remoteVideos[resourceJid].setDisplayName(null);
  8947. }
  8948. if(resourceJid && (!members || !members[newJID] ||
  8949. !members[newJID].displayName)) {
  8950. remoteVideos[resourceJid].setDisplayName(null,
  8951. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  8952. }
  8953. currentDominantSpeaker = resourceJid;
  8954. } else {
  8955. return;
  8956. }
  8957. // Obtain container for new dominant speaker.
  8958. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  8959. // Local video will not have container found, but that's ok
  8960. // since we don't want to switch to local video.
  8961. if (!focusedVideoResourceJid && videoSel.length)
  8962. {
  8963. // Update the large video if the video source is already available,
  8964. // otherwise wait for the "videoactive.jingle" event.
  8965. if (videoSel[0].currentTime > 0) {
  8966. LargeVideo.updateLargeVideo(resourceJid);
  8967. }
  8968. }
  8969. };
  8970. /**
  8971. * On last N change event.
  8972. *
  8973. * @param lastNEndpoints the list of last N endpoints
  8974. * @param endpointsEnteringLastN the list currently entering last N
  8975. * endpoints
  8976. */
  8977. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  8978. endpointsEnteringLastN,
  8979. stream) {
  8980. if (lastNCount !== lastNEndpoints.length)
  8981. lastNCount = lastNEndpoints.length;
  8982. lastNEndpointsCache = lastNEndpoints;
  8983. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  8984. //
  8985. // If LastN drops to, say, 2, because of adaptivity, then E should see
  8986. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  8987. // so E sees them. C is only in E's local LastN set.
  8988. //
  8989. // If F starts talking and LastN = 3, then E should see thumbnails for
  8990. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  8991. // enters E's local LastN ejecting C.
  8992. // Increase the local LastN set size, if necessary.
  8993. if (lastNCount > localLastNCount) {
  8994. localLastNCount = lastNCount;
  8995. }
  8996. // Update the local LastN set preserving the order in which the
  8997. // endpoints appeared in the LastN/local LastN set.
  8998. var nextLocalLastNSet = lastNEndpoints.slice(0);
  8999. for (var i = 0; i < localLastNSet.length; i++) {
  9000. if (nextLocalLastNSet.length >= localLastNCount) {
  9001. break;
  9002. }
  9003. var resourceJid = localLastNSet[i];
  9004. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9005. nextLocalLastNSet.push(resourceJid);
  9006. }
  9007. }
  9008. localLastNSet = nextLocalLastNSet;
  9009. var updateLargeVideo = false;
  9010. // Handle LastN/local LastN changes.
  9011. $('#remoteVideos>span').each(function( index, element ) {
  9012. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9013. var isReceived = true;
  9014. if (resourceJid
  9015. && lastNEndpoints.indexOf(resourceJid) < 0
  9016. && localLastNSet.indexOf(resourceJid) < 0) {
  9017. console.log("Remove from last N", resourceJid);
  9018. remoteVideos[resourceJid].showPeerContainer('hide');
  9019. isReceived = false;
  9020. } else if (resourceJid
  9021. && $('#participant_' + resourceJid).is(':visible')
  9022. && lastNEndpoints.indexOf(resourceJid) < 0
  9023. && localLastNSet.indexOf(resourceJid) >= 0) {
  9024. remoteVideos[resourceJid].showPeerContainer('avatar');
  9025. isReceived = false;
  9026. }
  9027. if (!isReceived) {
  9028. // resourceJid has dropped out of the server side lastN set, so
  9029. // it is no longer being received. If resourceJid was being
  9030. // displayed in the large video we have to switch to another
  9031. // user.
  9032. if (!updateLargeVideo && resourceJid === LargeVideo.getResourceJid()) {
  9033. updateLargeVideo = true;
  9034. }
  9035. }
  9036. });
  9037. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9038. endpointsEnteringLastN = lastNEndpoints;
  9039. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9040. endpointsEnteringLastN.forEach(function (resourceJid) {
  9041. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9042. remoteVideos[resourceJid].showPeerContainer('show');
  9043. if (!isVisible) {
  9044. console.log("Add to last N", resourceJid);
  9045. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9046. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9047. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9048. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9049. if (lastNPickupJid == mediaStream.peerjid) {
  9050. // Clean up the lastN pickup jid.
  9051. lastNPickupJid = null;
  9052. // Don't fire the events again, they've already
  9053. // been fired in the contact list click handler.
  9054. VideoLayout.handleVideoThumbClicked(
  9055. false,
  9056. Strophe.getResourceFromJid(mediaStream.peerjid));
  9057. updateLargeVideo = false;
  9058. }
  9059. remoteVideos[resourceJid].waitForPlayback(mediaStream.stream);
  9060. }
  9061. });
  9062. }
  9063. // The endpoint that was being shown in the large video has dropped out
  9064. // of the lastN set and there was no lastN pickup jid. We need to update
  9065. // the large video now.
  9066. if (updateLargeVideo) {
  9067. var resource, container, src;
  9068. var myResource
  9069. = APP.xmpp.myResource();
  9070. // Find out which endpoint to show in the large video.
  9071. for (var i = 0; i < lastNEndpoints.length; i++) {
  9072. resource = lastNEndpoints[i];
  9073. if (!resource || resource === myResource)
  9074. continue;
  9075. // videoSrcToSsrc needs to be update for this call to succeed.
  9076. LargeVideo.updateLargeVideo(resource);
  9077. break;
  9078. }
  9079. }
  9080. };
  9081. /**
  9082. * Updates local stats
  9083. * @param percent
  9084. * @param object
  9085. */
  9086. my.updateLocalConnectionStats = function (percent, object) {
  9087. var resolution = null;
  9088. if(object.resolution !== null)
  9089. {
  9090. resolution = object.resolution;
  9091. object.resolution = resolution[APP.xmpp.myJid()];
  9092. delete resolution[APP.xmpp.myJid()];
  9093. }
  9094. localVideoThumbnail.updateStatsIndicator(percent, object);
  9095. for(var jid in resolution)
  9096. {
  9097. if(resolution[jid] === null)
  9098. continue;
  9099. var resourceJid = Strophe.getResourceFromJid(jid);
  9100. if(remoteVideos[resourceJid] && remoteVideos[resourceJid].connectionIndicator)
  9101. {
  9102. remoteVideos[resourceJid].connectionIndicator.updateResolution(resolution[jid]);
  9103. }
  9104. }
  9105. };
  9106. /**
  9107. * Updates remote stats.
  9108. * @param jid the jid associated with the stats
  9109. * @param percent the connection quality percent
  9110. * @param object the stats data
  9111. */
  9112. my.updateConnectionStats = function (jid, percent, object) {
  9113. var resourceJid = Strophe.getResourceFromJid(jid);
  9114. if(remoteVideos[resourceJid])
  9115. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9116. };
  9117. /**
  9118. * Removes the connection
  9119. * @param jid
  9120. */
  9121. my.removeConnectionIndicator = function (jid) {
  9122. remoteVideos[Strophe.getResourceFromJid(jid)].removeConnectionIndicator();
  9123. };
  9124. /**
  9125. * Hides the connection indicator
  9126. * @param jid
  9127. */
  9128. my.hideConnectionIndicator = function (jid) {
  9129. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9130. };
  9131. /**
  9132. * Hides all the indicators
  9133. */
  9134. my.onStatsStop = function () {
  9135. for(var video in remoteVideos)
  9136. {
  9137. remoteVideos[video].hideIndicator();
  9138. }
  9139. localVideoThumbnail.hideIndicator();
  9140. };
  9141. my.participantLeft = function (jid) {
  9142. // Unlock large video
  9143. var resourceJid = Strophe.getResourceFromJid(jid);
  9144. if (focusedVideoResourceJid === resourceJid)
  9145. {
  9146. console.info("Focused video owner has left the conference");
  9147. focusedVideoResourceJid = null;
  9148. }
  9149. };
  9150. my.onVideoTypeChanged = function (jid) {
  9151. LargeVideo.onVideoTypeChanged(jid);
  9152. };
  9153. my.showMore = function (jid) {
  9154. if(APP.xmpp.myJid = jid)
  9155. {
  9156. localVideoThumbnail.connectionIndicator.showMore();
  9157. }
  9158. else
  9159. {
  9160. remoteVideos[Strophe.getResourceFromJid(jid)].connectionIndicator.showMore();
  9161. }
  9162. };
  9163. my.addPreziContainer = function (id) {
  9164. return RemoteVideo.createContainer(id);
  9165. };
  9166. my.setLargeVideoVisible = function (isVisible) {
  9167. LargeVideo.setLargeVideoVisible(isVisible);
  9168. if(!isVisible && focusedVideoResourceJid)
  9169. {
  9170. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9171. if(smallVideo)
  9172. smallVideo.focus(false);
  9173. smallVideo.showAvatar();
  9174. focusedVideoResourceJid = null;
  9175. }
  9176. };
  9177. /**
  9178. * Resizes the video area
  9179. * @param completeFunction a function to be called when the video space is resized
  9180. */
  9181. my.resizeVideoArea = function(isVisible, completeFunction) {
  9182. LargeVideo.resizeVideoAreaAnimated(isVisible, completeFunction);
  9183. VideoLayout.resizeThumbnails(true);
  9184. };
  9185. my.getSmallVideo = function (resourceJid) {
  9186. if(resourceJid == APP.xmpp.myResource())
  9187. {
  9188. return localVideoThumbnail;
  9189. }
  9190. else
  9191. {
  9192. if(!remoteVideos[resourceJid])
  9193. return null;
  9194. return remoteVideos[resourceJid];
  9195. }
  9196. };
  9197. my.userAvatarChanged = function(resourceJid, thumbUrl)
  9198. {
  9199. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9200. if(smallVideo)
  9201. smallVideo.avatarChanged(thumbUrl);
  9202. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9203. };
  9204. return my;
  9205. }(VideoLayout || {}));
  9206. module.exports = VideoLayout;
  9207. },{"../../../service/RTC/MediaStreamTypes":102,"../../../service/UI/UIEvents":106,"../../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){
  9208. //var nouns = [
  9209. //];
  9210. var pluralNouns = [
  9211. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9212. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9213. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9214. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9215. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9216. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9217. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9218. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9219. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9220. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9221. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9222. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9223. ];
  9224. //var places = [
  9225. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9226. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9227. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9228. // "Bridge"
  9229. //];
  9230. var verbs = [
  9231. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9232. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9233. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9234. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9235. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9236. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9237. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9238. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9239. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9240. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9241. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9242. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9243. ];
  9244. var adverbs = [
  9245. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9246. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9247. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9248. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9249. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9250. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9251. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9252. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9253. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9254. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9255. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9256. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9257. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9258. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9259. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9260. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9261. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9262. ];
  9263. var adjectives = [
  9264. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9265. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9266. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9267. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9268. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9269. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9270. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9271. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9272. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9273. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9274. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9275. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9276. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9277. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9278. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9279. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9280. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9281. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9282. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9283. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9284. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9285. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9286. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9287. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9288. "Zealous"
  9289. ];
  9290. //var pronouns = [
  9291. //];
  9292. //var conjunctions = [
  9293. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9294. //];
  9295. /*
  9296. * Maps a string (category name) to the array of words from that category.
  9297. */
  9298. var CATEGORIES =
  9299. {
  9300. //"_NOUN_": nouns,
  9301. "_PLURALNOUN_": pluralNouns,
  9302. //"_PLACE_": places,
  9303. "_VERB_": verbs,
  9304. "_ADVERB_": adverbs,
  9305. "_ADJECTIVE_": adjectives
  9306. //"_PRONOUN_": pronouns,
  9307. //"_CONJUNCTION_": conjunctions,
  9308. };
  9309. var PATTERNS = [
  9310. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9311. // BeautifulFungiOrSpaghetti
  9312. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9313. // AmazinglyScaryToy
  9314. //"_ADVERB__ADJECTIVE__NOUN_",
  9315. // NeitherTrashNorRifle
  9316. //"Neither_NOUN_Nor_NOUN_",
  9317. //"Either_NOUN_Or_NOUN_",
  9318. // EitherCopulateOrInvestigate
  9319. //"Either_VERB_Or_VERB_",
  9320. //"Neither_VERB_Nor_VERB_",
  9321. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9322. //"The_ADVERB__ADJECTIVE__NOUN_",
  9323. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9324. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9325. // WolvesComputeBadly
  9326. //"_PLURALNOUN__VERB__ADVERB_",
  9327. // UniteFacilitateAndMerge
  9328. //"_VERB__VERB_And_VERB_",
  9329. //NastyWitchesAtThePub
  9330. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9331. ];
  9332. /*
  9333. * Returns a random element from the array 'arr'
  9334. */
  9335. function randomElement(arr)
  9336. {
  9337. return arr[Math.floor(Math.random() * arr.length)];
  9338. }
  9339. /*
  9340. * Returns true if the string 's' contains one of the
  9341. * template strings.
  9342. */
  9343. function hasTemplate(s)
  9344. {
  9345. for (var template in CATEGORIES){
  9346. if (s.indexOf(template) >= 0){
  9347. return true;
  9348. }
  9349. }
  9350. }
  9351. /**
  9352. * Generates new room name.
  9353. */
  9354. var RoomNameGenerator = {
  9355. generateRoomWithoutSeparator: function()
  9356. {
  9357. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  9358. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  9359. var name = randomElement(PATTERNS);
  9360. var word;
  9361. while (hasTemplate(name)){
  9362. for (var template in CATEGORIES){
  9363. word = randomElement(CATEGORIES[template]);
  9364. name = name.replace(template, word);
  9365. }
  9366. }
  9367. return name;
  9368. }
  9369. }
  9370. module.exports = RoomNameGenerator;
  9371. },{}],41:[function(require,module,exports){
  9372. var animateTimeout, updateTimeout;
  9373. var RoomNameGenerator = require("./RoomnameGenerator");
  9374. function enter_room()
  9375. {
  9376. var val = $("#enter_room_field").val();
  9377. if(!val) {
  9378. val = $("#enter_room_field").attr("room_name");
  9379. }
  9380. if (val) {
  9381. window.location.pathname = "/" + val;
  9382. }
  9383. }
  9384. function animate(word) {
  9385. var currentVal = $("#enter_room_field").attr("placeholder");
  9386. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9387. animateTimeout = setTimeout(function() {
  9388. animate(word.substring(1, word.length))
  9389. }, 70);
  9390. }
  9391. function update_roomname()
  9392. {
  9393. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9394. $("#enter_room_field").attr("room_name", word);
  9395. $("#enter_room_field").attr("placeholder", "");
  9396. clearTimeout(animateTimeout);
  9397. animate(word);
  9398. updateTimeout = setTimeout(update_roomname, 10000);
  9399. }
  9400. function setupWelcomePage()
  9401. {
  9402. $("#videoconference_page").hide();
  9403. $("#domain_name").text(
  9404. window.location.protocol + "//" + window.location.host + "/");
  9405. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9406. var leftWatermarkDiv
  9407. = $("#welcome_page_header div[class='watermark leftwatermark']");
  9408. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  9409. {
  9410. leftWatermarkDiv.css({display: 'block'});
  9411. leftWatermarkDiv.parent().get(0).href
  9412. = interfaceConfig.JITSI_WATERMARK_LINK;
  9413. }
  9414. }
  9415. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9416. var rightWatermarkDiv
  9417. = $("#welcome_page_header div[class='watermark rightwatermark']");
  9418. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9419. rightWatermarkDiv.css({display: 'block'});
  9420. rightWatermarkDiv.parent().get(0).href
  9421. = interfaceConfig.BRAND_WATERMARK_LINK;
  9422. rightWatermarkDiv.get(0).style.backgroundImage
  9423. = "url(images/rightwatermark.png)";
  9424. }
  9425. }
  9426. if (interfaceConfig.SHOW_POWERED_BY) {
  9427. $("#welcome_page_header>a[class='poweredby']")
  9428. .css({display: 'block'});
  9429. }
  9430. $("#enter_room_button").click(function()
  9431. {
  9432. enter_room();
  9433. });
  9434. $("#enter_room_field").keydown(function (event) {
  9435. if (event.keyCode === 13 /* enter */) {
  9436. enter_room();
  9437. }
  9438. });
  9439. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  9440. var updateTimeout;
  9441. var animateTimeout;
  9442. $("#reload_roomname").click(function () {
  9443. clearTimeout(updateTimeout);
  9444. clearTimeout(animateTimeout);
  9445. update_roomname();
  9446. });
  9447. $("#reload_roomname").show();
  9448. update_roomname();
  9449. }
  9450. $("#disable_welcome").click(function () {
  9451. window.localStorage.welcomePageDisabled
  9452. = $("#disable_welcome").is(":checked");
  9453. });
  9454. }
  9455. module.exports = setupWelcomePage;
  9456. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9457. var params = {};
  9458. function getConfigParamsFromUrl() {
  9459. if(!location.hash)
  9460. return {};
  9461. var hash = location.hash.substr(1);
  9462. var result = {};
  9463. hash.split("&").forEach(function(part) {
  9464. var item = part.split("=");
  9465. result[item[0]] = JSON.parse(
  9466. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9467. });
  9468. return result;
  9469. }
  9470. params = getConfigParamsFromUrl();
  9471. var URLProcessor = {
  9472. setConfigParametersFromUrl: function () {
  9473. for(var k in params)
  9474. {
  9475. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9476. continue;
  9477. var v = params[k];
  9478. var confKey = k.substr(7);
  9479. if(config[confKey] && typeof config[confKey] !== typeof v)
  9480. {
  9481. console.warn("The type of " + k +
  9482. " is wrong. That parameter won't be updated in config.js.");
  9483. continue;
  9484. }
  9485. config[confKey] = v;
  9486. }
  9487. }
  9488. };
  9489. module.exports = URLProcessor;
  9490. },{}],43:[function(require,module,exports){
  9491. var EventEmitter = require("events");
  9492. var eventEmitter = new EventEmitter();
  9493. var CQEvents = require("../../service/connectionquality/CQEvents");
  9494. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9495. /**
  9496. * local stats
  9497. * @type {{}}
  9498. */
  9499. var stats = {};
  9500. /**
  9501. * remote stats
  9502. * @type {{}}
  9503. */
  9504. var remoteStats = {};
  9505. /**
  9506. * Interval for sending statistics to other participants
  9507. * @type {null}
  9508. */
  9509. var sendIntervalId = null;
  9510. /**
  9511. * Start statistics sending.
  9512. */
  9513. function startSendingStats() {
  9514. sendStats();
  9515. sendIntervalId = setInterval(sendStats, 10000);
  9516. }
  9517. /**
  9518. * Sends statistics to other participants
  9519. */
  9520. function sendStats() {
  9521. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9522. }
  9523. /**
  9524. * Converts statistics to format for sending through XMPP
  9525. * @param stats the statistics
  9526. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9527. */
  9528. function convertToMUCStats(stats) {
  9529. return {
  9530. "bitrate_download": stats.bitrate.download,
  9531. "bitrate_upload": stats.bitrate.upload,
  9532. "packetLoss_total": stats.packetLoss.total,
  9533. "packetLoss_download": stats.packetLoss.download,
  9534. "packetLoss_upload": stats.packetLoss.upload
  9535. };
  9536. }
  9537. /**
  9538. * Converts statitistics to format used by VideoLayout
  9539. * @param stats
  9540. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9541. */
  9542. function parseMUCStats(stats) {
  9543. return {
  9544. bitrate: {
  9545. download: stats.bitrate_download,
  9546. upload: stats.bitrate_upload
  9547. },
  9548. packetLoss: {
  9549. total: stats.packetLoss_total,
  9550. download: stats.packetLoss_download,
  9551. upload: stats.packetLoss_upload
  9552. }
  9553. };
  9554. }
  9555. var ConnectionQuality = {
  9556. init: function () {
  9557. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9558. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9559. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9560. },
  9561. /**
  9562. * Updates the local statistics
  9563. * @param data new statistics
  9564. */
  9565. updateLocalStats: function (data) {
  9566. stats = data;
  9567. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9568. if (sendIntervalId == null) {
  9569. startSendingStats();
  9570. }
  9571. },
  9572. /**
  9573. * Updates remote statistics
  9574. * @param jid the jid associated with the statistics
  9575. * @param data the statistics
  9576. */
  9577. updateRemoteStats: function (jid, data) {
  9578. if (data == null || data.packetLoss_total == null) {
  9579. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9580. return;
  9581. }
  9582. remoteStats[jid] = parseMUCStats(data);
  9583. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9584. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9585. },
  9586. /**
  9587. * Stops statistics sending.
  9588. */
  9589. stopSendingStats: function () {
  9590. clearInterval(sendIntervalId);
  9591. sendIntervalId = null;
  9592. //notify UI about stopping statistics gathering
  9593. eventEmitter.emit(CQEvents.STOP);
  9594. },
  9595. /**
  9596. * Returns the local statistics.
  9597. */
  9598. getStats: function () {
  9599. return stats;
  9600. },
  9601. addListener: function (type, listener) {
  9602. eventEmitter.on(type, listener);
  9603. }
  9604. };
  9605. module.exports = ConnectionQuality;
  9606. },{"../../service/connectionquality/CQEvents":108,"../../service/xmpp/XMPPEvents":112,"events":113}],44:[function(require,module,exports){
  9607. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9608. getUserMediaWithConstraints */
  9609. /**
  9610. * Indicates that desktop stream is currently in use(for toggle purpose).
  9611. * @type {boolean}
  9612. */
  9613. var isUsingScreenStream = false;
  9614. /**
  9615. * Indicates that switch stream operation is in progress and prevent from
  9616. * triggering new events.
  9617. * @type {boolean}
  9618. */
  9619. var switchInProgress = false;
  9620. /**
  9621. * Method used to get screen sharing stream.
  9622. *
  9623. * @type {function (stream_callback, failure_callback}
  9624. */
  9625. var obtainDesktopStream = null;
  9626. /**
  9627. * Indicates whether desktop sharing extension is installed.
  9628. * @type {boolean}
  9629. */
  9630. var extInstalled = false;
  9631. /**
  9632. * Indicates whether update of desktop sharing extension is required.
  9633. * @type {boolean}
  9634. */
  9635. var extUpdateRequired = false;
  9636. var AdapterJS = require("../RTC/adapter.screenshare");
  9637. var EventEmitter = require("events");
  9638. var eventEmitter = new EventEmitter();
  9639. var DesktopSharingEventTypes
  9640. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9641. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9642. var RTCEvents = require("../../service/RTC/RTCEvents");
  9643. /**
  9644. * Method obtains desktop stream from WebRTC 'screen' source.
  9645. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9646. */
  9647. function obtainWebRTCScreen(streamCallback, failCallback) {
  9648. APP.RTC.getUserMediaWithConstraints(
  9649. ['screen'],
  9650. streamCallback,
  9651. failCallback
  9652. );
  9653. }
  9654. /**
  9655. * Constructs inline install URL for Chrome desktop streaming extension.
  9656. * The 'chromeExtensionId' must be defined in config.js.
  9657. * @returns {string}
  9658. */
  9659. function getWebStoreInstallUrl()
  9660. {
  9661. return "https://chrome.google.com/webstore/detail/" +
  9662. config.chromeExtensionId;
  9663. }
  9664. /**
  9665. * Checks whether extension update is required.
  9666. * @param minVersion minimal required version
  9667. * @param extVersion current extension version
  9668. * @returns {boolean}
  9669. */
  9670. function isUpdateRequired(minVersion, extVersion)
  9671. {
  9672. try
  9673. {
  9674. var s1 = minVersion.split('.');
  9675. var s2 = extVersion.split('.');
  9676. var len = Math.max(s1.length, s2.length);
  9677. for (var i = 0; i < len; i++)
  9678. {
  9679. var n1 = 0,
  9680. n2 = 0;
  9681. if (i < s1.length)
  9682. n1 = parseInt(s1[i]);
  9683. if (i < s2.length)
  9684. n2 = parseInt(s2[i]);
  9685. if (isNaN(n1) || isNaN(n2))
  9686. {
  9687. return true;
  9688. }
  9689. else if (n1 !== n2)
  9690. {
  9691. return n1 > n2;
  9692. }
  9693. }
  9694. // will happen if boths version has identical numbers in
  9695. // their components (even if one of them is longer, has more components)
  9696. return false;
  9697. }
  9698. catch (e)
  9699. {
  9700. console.error("Failed to parse extension version", e);
  9701. APP.UI.messageHandler.showError("dialog.error",
  9702. "dialog.detectext");
  9703. return true;
  9704. }
  9705. }
  9706. function checkChromeExtInstalled(callback) {
  9707. if (!chrome.runtime) {
  9708. // No API, so no extension for sure
  9709. callback(false, false);
  9710. return;
  9711. }
  9712. chrome.runtime.sendMessage(
  9713. config.chromeExtensionId,
  9714. { getVersion: true },
  9715. function (response) {
  9716. if (!response || !response.version) {
  9717. // Communication failure - assume that no endpoint exists
  9718. console.warn(
  9719. "Extension not installed?: ", chrome.runtime.lastError);
  9720. callback(false, false);
  9721. return;
  9722. }
  9723. // Check installed extension version
  9724. var extVersion = response.version;
  9725. console.log('Extension version is: ' + extVersion);
  9726. var updateRequired
  9727. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  9728. callback(!updateRequired, updateRequired);
  9729. }
  9730. );
  9731. }
  9732. function doGetStreamFromExtension(streamCallback, failCallback) {
  9733. // Sends 'getStream' msg to the extension.
  9734. // Extension id must be defined in the config.
  9735. chrome.runtime.sendMessage(
  9736. config.chromeExtensionId,
  9737. { getStream: true, sources: config.desktopSharingSources },
  9738. function (response) {
  9739. if (!response) {
  9740. failCallback(chrome.runtime.lastError);
  9741. return;
  9742. }
  9743. console.log("Response from extension: " + response);
  9744. if (response.streamId) {
  9745. APP.RTC.getUserMediaWithConstraints(
  9746. ['desktop'],
  9747. function (stream) {
  9748. streamCallback(stream);
  9749. },
  9750. failCallback,
  9751. null, null, null,
  9752. response.streamId);
  9753. } else {
  9754. failCallback("Extension failed to get the stream");
  9755. }
  9756. }
  9757. );
  9758. }
  9759. /**
  9760. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  9761. * stream for returned stream token.
  9762. */
  9763. function obtainScreenFromExtension(streamCallback, failCallback) {
  9764. if (extInstalled) {
  9765. doGetStreamFromExtension(streamCallback, failCallback);
  9766. } else {
  9767. if (extUpdateRequired) {
  9768. alert(
  9769. 'Jitsi Desktop Streamer requires update. ' +
  9770. 'Changes will take effect after next Chrome restart.');
  9771. }
  9772. chrome.webstore.install(
  9773. getWebStoreInstallUrl(),
  9774. function (arg) {
  9775. console.log("Extension installed successfully", arg);
  9776. extInstalled = true;
  9777. // We need to give a moment for the endpoint to become available
  9778. window.setTimeout(function () {
  9779. doGetStreamFromExtension(streamCallback, failCallback);
  9780. }, 500);
  9781. },
  9782. function (arg) {
  9783. console.log("Failed to install the extension", arg);
  9784. failCallback(arg);
  9785. APP.UI.messageHandler.showError("dialog.error",
  9786. "dialog.failtoinstall");
  9787. }
  9788. );
  9789. }
  9790. }
  9791. /**
  9792. * Call this method to toggle desktop sharing feature.
  9793. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  9794. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  9795. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  9796. * enabled), pass any other string or nothing in order to disable this
  9797. * feature completely.
  9798. */
  9799. function setDesktopSharing(method) {
  9800. obtainDesktopStream = null;
  9801. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  9802. // care about 'method' parameter
  9803. if (RTCBrowserType.isTemasysPluginUsed()) {
  9804. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  9805. console.info("Screensharing not supported by this plugin version");
  9806. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  9807. console.info(
  9808. "Screensharing not available with Temasys plugin on this site");
  9809. } else {
  9810. obtainDesktopStream = obtainWebRTCScreen;
  9811. console.info("Using Temasys plugin for desktop sharing");
  9812. }
  9813. } else if (RTCBrowserType.isChrome()) {
  9814. if (method == "ext") {
  9815. if (RTCBrowserType.getChromeVersion() >= 34) {
  9816. obtainDesktopStream = obtainScreenFromExtension;
  9817. console.info("Using Chrome extension for desktop sharing");
  9818. initChromeExtension();
  9819. } else {
  9820. console.info("Chrome extension not supported until ver 34");
  9821. }
  9822. } else if (method == "webrtc") {
  9823. obtainDesktopStream = obtainWebRTCScreen;
  9824. console.info("Using Chrome WebRTC for desktop sharing");
  9825. }
  9826. }
  9827. if (!obtainDesktopStream) {
  9828. console.info("Desktop sharing disabled");
  9829. }
  9830. }
  9831. /**
  9832. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  9833. * config.js to support inline installs. Host site must be selected as main
  9834. * website of published extension.
  9835. */
  9836. function initInlineInstalls()
  9837. {
  9838. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  9839. }
  9840. function initChromeExtension() {
  9841. // Initialize Chrome extension inline installs
  9842. initInlineInstalls();
  9843. // Check if extension is installed
  9844. checkChromeExtInstalled(function (installed, updateRequired) {
  9845. extInstalled = installed;
  9846. extUpdateRequired = updateRequired;
  9847. console.info(
  9848. "Chrome extension installed: " + extInstalled +
  9849. " updateRequired: " + extUpdateRequired);
  9850. });
  9851. }
  9852. function getVideoStreamFailed(error) {
  9853. console.error("Failed to obtain the stream to switch to", error);
  9854. switchInProgress = false;
  9855. isUsingScreenStream = false;
  9856. newStreamCreated(null);
  9857. }
  9858. function getDesktopStreamFailed(error) {
  9859. console.error("Failed to obtain the stream to switch to", error);
  9860. switchInProgress = false;
  9861. }
  9862. function streamSwitchDone() {
  9863. switchInProgress = false;
  9864. eventEmitter.emit(
  9865. DesktopSharingEventTypes.SWITCHING_DONE,
  9866. isUsingScreenStream);
  9867. }
  9868. function newStreamCreated(stream)
  9869. {
  9870. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  9871. stream, isUsingScreenStream, streamSwitchDone);
  9872. }
  9873. function onEndedHandler(stream) {
  9874. if (!switchInProgress && isUsingScreenStream) {
  9875. APP.desktopsharing.toggleScreenSharing();
  9876. }
  9877. //FIXME: to be verified
  9878. if (stream.removeEventListener) {
  9879. stream.removeEventListener('ended', onEndedHandler);
  9880. } else {
  9881. stream.detachEvent('ended', onEndedHandler);
  9882. }
  9883. }
  9884. // Called when RTC finishes initialization
  9885. function onWebRtcReady() {
  9886. setDesktopSharing(config.desktopSharing);
  9887. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  9888. }
  9889. module.exports = {
  9890. isUsingScreenStream: function () {
  9891. return isUsingScreenStream;
  9892. },
  9893. /**
  9894. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  9895. * and enabled.
  9896. */
  9897. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  9898. init: function () {
  9899. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  9900. },
  9901. addListener: function (listener, type)
  9902. {
  9903. eventEmitter.on(type, listener);
  9904. },
  9905. removeListener: function (listener, type) {
  9906. eventEmitter.removeListener(type, listener);
  9907. },
  9908. /*
  9909. * Toggles screen sharing.
  9910. */
  9911. toggleScreenSharing: function () {
  9912. if (switchInProgress || !obtainDesktopStream) {
  9913. console.warn("Switch in progress or no method defined");
  9914. return;
  9915. }
  9916. switchInProgress = true;
  9917. if (!isUsingScreenStream)
  9918. {
  9919. // Switch to desktop stream
  9920. obtainDesktopStream(
  9921. function (stream) {
  9922. // We now use screen stream
  9923. isUsingScreenStream = true;
  9924. // Hook 'ended' event to restore camera
  9925. // when screen stream stops
  9926. //FIXME: to be verified
  9927. if (stream.addEventListener) {
  9928. stream.addEventListener('ended', function () {
  9929. onEndedHandler(stream);
  9930. });
  9931. } else {
  9932. stream.attachEvent('ended', function () {
  9933. onEndedHandler(stream);
  9934. });
  9935. }
  9936. newStreamCreated(stream);
  9937. },
  9938. getDesktopStreamFailed);
  9939. } else {
  9940. // Disable screen stream
  9941. APP.RTC.getUserMediaWithConstraints(
  9942. ['video'],
  9943. function (stream) {
  9944. // We are now using camera stream
  9945. isUsingScreenStream = false;
  9946. newStreamCreated(stream);
  9947. },
  9948. getVideoStreamFailed, config.resolution || '360'
  9949. );
  9950. }
  9951. }
  9952. };
  9953. },{"../../service/RTC/RTCEvents":103,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":113}],45:[function(require,module,exports){
  9954. //maps keycode to character, id of popover for given function and function
  9955. var shortcuts = {
  9956. 67: {
  9957. character: "C",
  9958. id: "toggleChatPopover",
  9959. function: APP.UI.toggleChat
  9960. },
  9961. 70: {
  9962. character: "F",
  9963. id: "filmstripPopover",
  9964. function: APP.UI.toggleFilmStrip
  9965. },
  9966. 77: {
  9967. character: "M",
  9968. id: "mutePopover",
  9969. function: APP.UI.toggleAudio
  9970. },
  9971. 84: {
  9972. character: "T",
  9973. function: function() {
  9974. if(!APP.RTC.localAudio.isMuted()) {
  9975. APP.UI.toggleAudio();
  9976. }
  9977. }
  9978. },
  9979. 86: {
  9980. character: "V",
  9981. id: "toggleVideoPopover",
  9982. function: APP.UI.toggleVideo
  9983. }
  9984. };
  9985. var KeyboardShortcut = {
  9986. init: function () {
  9987. window.onkeyup = function(e) {
  9988. var keycode = e.which;
  9989. if(!($(":focus").is("input[type=text]") ||
  9990. $(":focus").is("input[type=password]") ||
  9991. $(":focus").is("textarea"))) {
  9992. if (typeof shortcuts[keycode] === "object") {
  9993. shortcuts[keycode].function();
  9994. }
  9995. else if (keycode >= "0".charCodeAt(0) &&
  9996. keycode <= "9".charCodeAt(0)) {
  9997. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  9998. }
  9999. //esc while the smileys are visible hides them
  10000. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10001. APP.UI.toggleSmileys();
  10002. }
  10003. };
  10004. window.onkeydown = function(e) {
  10005. if(!($(":focus").is("input[type=text]") ||
  10006. $(":focus").is("input[type=password]") ||
  10007. $(":focus").is("textarea"))) {
  10008. if(e.which === "T".charCodeAt(0)) {
  10009. if(APP.RTC.localAudio.isMuted()) {
  10010. APP.UI.toggleAudio();
  10011. }
  10012. }
  10013. }
  10014. };
  10015. var self = this;
  10016. $('body').popover({ selector: '[data-toggle=popover]',
  10017. trigger: 'click hover',
  10018. content: function() {
  10019. return this.getAttribute("content") +
  10020. self.getShortcut(this.getAttribute("shortcut"));
  10021. }
  10022. });
  10023. },
  10024. /**
  10025. *
  10026. * @param id indicates the popover associated with the shortcut
  10027. * @returns {string} the keyboard shortcut used for the id given
  10028. */
  10029. getShortcut: function (id) {
  10030. for (var keycode in shortcuts) {
  10031. if (shortcuts.hasOwnProperty(keycode)) {
  10032. if (shortcuts[keycode].id === id) {
  10033. return " (" + shortcuts[keycode].character + ")";
  10034. }
  10035. }
  10036. }
  10037. return "";
  10038. }
  10039. };
  10040. module.exports = KeyboardShortcut;
  10041. },{}],46:[function(require,module,exports){
  10042. /* global APP */
  10043. /**
  10044. * This module is meant to (eventually) contain and manage all information
  10045. * about members/participants of the conference, so that other modules don't
  10046. * have to do it on their own, and so that other modules can access members'
  10047. * information from a single place.
  10048. *
  10049. * Currently this module only manages information about the support of jingle
  10050. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10051. * be added as needed.
  10052. */
  10053. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10054. var Events = require("../../service/members/Events");
  10055. var EventEmitter = require("events");
  10056. var eventEmitter = new EventEmitter();
  10057. /**
  10058. * The actual container.
  10059. */
  10060. var members = {};
  10061. /**
  10062. * There is at least one member that supports DTMF (i.e. is jigasi).
  10063. */
  10064. var atLeastOneDtmf = false;
  10065. function registerListeners() {
  10066. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10067. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10068. }
  10069. /**
  10070. * Handles a new member joining the MUC.
  10071. */
  10072. function onMucMemberJoined(jid, id, displayName) {
  10073. var member = {
  10074. displayName: displayName
  10075. };
  10076. APP.xmpp.getConnection().disco.info(
  10077. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10078. members[jid] = member;
  10079. }
  10080. /**
  10081. * Handles a member leaving the MUC.
  10082. */
  10083. function onMucMemberLeft(jid) {
  10084. delete members[jid];
  10085. updateAtLeastOneDtmf();
  10086. }
  10087. /**
  10088. * Handles the reception of a disco#info packet from a particular JID.
  10089. * @param jid the JID sending the packet.
  10090. * @param iq the packet.
  10091. */
  10092. function onDiscoInfoReceived(jid, iq) {
  10093. if (!members[jid])
  10094. return;
  10095. var supportsDtmf
  10096. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10097. updateDtmf(jid, supportsDtmf);
  10098. }
  10099. /**
  10100. * Updates the 'supportsDtmf' field for a member.
  10101. * @param jid the jid of the member.
  10102. * @param newValue the new value for the 'supportsDtmf' field.
  10103. */
  10104. function updateDtmf(jid, newValue) {
  10105. var oldValue = members[jid].supportsDtmf;
  10106. members[jid].supportsDtmf = newValue;
  10107. if (newValue != oldValue) {
  10108. updateAtLeastOneDtmf();
  10109. }
  10110. }
  10111. /**
  10112. * Checks each member's 'supportsDtmf' field and updates
  10113. * 'atLastOneSupportsDtmf'.
  10114. */
  10115. function updateAtLeastOneDtmf(){
  10116. var newAtLeastOneDtmf = false;
  10117. for (var key in members) {
  10118. if (typeof members[key].supportsDtmf !== 'undefined'
  10119. && members[key].supportsDtmf) {
  10120. newAtLeastOneDtmf= true;
  10121. break;
  10122. }
  10123. }
  10124. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10125. atLeastOneDtmf = newAtLeastOneDtmf;
  10126. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10127. }
  10128. }
  10129. /**
  10130. * Exported interface.
  10131. */
  10132. var Members = {
  10133. start: function(){
  10134. registerListeners();
  10135. },
  10136. addListener: function(type, listener)
  10137. {
  10138. eventEmitter.on(type, listener);
  10139. },
  10140. removeListener: function (type, listener) {
  10141. eventEmitter.removeListener(type, listener);
  10142. },
  10143. size: function () {
  10144. return Object.keys(members).length;
  10145. },
  10146. getMembers: function () {
  10147. return members;
  10148. }
  10149. };
  10150. module.exports = Members;
  10151. },{"../../service/members/Events":110,"../../service/xmpp/XMPPEvents":112,"events":113}],47:[function(require,module,exports){
  10152. var email = '';
  10153. var displayName = '';
  10154. var userId;
  10155. var language = null;
  10156. function supportsLocalStorage() {
  10157. try {
  10158. return 'localStorage' in window && window.localStorage !== null;
  10159. } catch (e) {
  10160. console.log("localstorage is not supported");
  10161. return false;
  10162. }
  10163. }
  10164. function generateUniqueId() {
  10165. function _p8() {
  10166. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10167. }
  10168. return _p8() + _p8() + _p8() + _p8();
  10169. }
  10170. if (supportsLocalStorage()) {
  10171. if (!window.localStorage.jitsiMeetId) {
  10172. window.localStorage.jitsiMeetId = generateUniqueId();
  10173. console.log("generated id", window.localStorage.jitsiMeetId);
  10174. }
  10175. userId = window.localStorage.jitsiMeetId || '';
  10176. email = window.localStorage.email || '';
  10177. displayName = window.localStorage.displayname || '';
  10178. language = window.localStorage.language;
  10179. } else {
  10180. console.log("local storage is not supported");
  10181. userId = generateUniqueId();
  10182. }
  10183. var Settings =
  10184. {
  10185. setDisplayName: function (newDisplayName) {
  10186. displayName = newDisplayName;
  10187. window.localStorage.displayname = displayName;
  10188. return displayName;
  10189. },
  10190. setEmail: function (newEmail)
  10191. {
  10192. email = newEmail;
  10193. window.localStorage.email = newEmail;
  10194. return email;
  10195. },
  10196. getSettings: function () {
  10197. return {
  10198. email: email,
  10199. displayName: displayName,
  10200. uid: userId,
  10201. language: language
  10202. };
  10203. },
  10204. setLanguage: function (lang) {
  10205. language = lang;
  10206. window.localStorage.language = lang;
  10207. }
  10208. };
  10209. module.exports = Settings;
  10210. },{}],48:[function(require,module,exports){
  10211. var callStats = null;
  10212. function initCallback (err, msg) {
  10213. console.log("Initializing Status: err="+err+" msg="+msg);
  10214. }
  10215. var CallStats = {
  10216. init: function (jingleSession) {
  10217. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10218. return;
  10219. callStats = new callstats($,io,jsSHA);
  10220. this.session = jingleSession;
  10221. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10222. this.userID = APP.xmpp.myResource();
  10223. var roomJid = APP.UI.getRoomName();
  10224. this.confID = roomJid? Strophe.getNodeFromJid(roomJid) : null;
  10225. //userID is generated or given by the origin server
  10226. callStats.initialize(config.callStatsID,
  10227. config.callStatsSecret,
  10228. this.userID,
  10229. initCallback);
  10230. var usage = callStats.fabricUsage.unbundled;
  10231. if(config.useBundle)
  10232. usage = callStats.fabricUsage.multiplex;
  10233. callStats.addNewFabric(this.peerconnection,
  10234. Strophe.getResourceFromJid(jingleSession.peerjid),
  10235. usage,
  10236. this.confID,
  10237. this.pcCallback.bind(this));
  10238. },
  10239. pcCallback: function (err, msg) {
  10240. if(!callStats)
  10241. return;
  10242. console.log("Monitoring status: "+ err + " msg: " + msg);
  10243. callStats.sendFabricEvent(this.peerconnection,
  10244. callStats.fabricEvent.fabricSetup, this.confID);
  10245. },
  10246. sendMuteEvent: function (mute, type) {
  10247. if(!callStats)
  10248. return;
  10249. var event = null;
  10250. if(type === "video")
  10251. {
  10252. event = (mute? callStats.fabricEvent.videoPause :
  10253. callStats.fabricEvent.videoResume);
  10254. }
  10255. else
  10256. {
  10257. event = (mute? callStats.fabricEvent.audioMute :
  10258. callStats.fabricEvent.audioUnmute);
  10259. }
  10260. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10261. },
  10262. sendTerminateEvent: function () {
  10263. if(!callStats)
  10264. return;
  10265. callStats.sendFabricEvent(this.peerconnection,
  10266. callStats.fabricEvent.fabricTerminated, this.confID);
  10267. },
  10268. sendSetupFailedEvent: function () {
  10269. if(!callStats)
  10270. return;
  10271. callStats.sendFabricEvent(this.peerconnection,
  10272. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10273. }
  10274. };
  10275. module.exports = CallStats;
  10276. },{}],49:[function(require,module,exports){
  10277. /**
  10278. * Provides statistics for the local stream.
  10279. */
  10280. /**
  10281. * Size of the webaudio analizer buffer.
  10282. * @type {number}
  10283. */
  10284. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  10285. /**
  10286. * Value of the webaudio analizer smoothing time parameter.
  10287. * @type {number}
  10288. */
  10289. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  10290. /**
  10291. * Converts time domain data array to audio level.
  10292. * @param array the time domain data array.
  10293. * @returns {number} the audio level
  10294. */
  10295. function timeDomainDataToAudioLevel(samples) {
  10296. var maxVolume = 0;
  10297. var length = samples.length;
  10298. for (var i = 0; i < length; i++) {
  10299. if (maxVolume < samples[i])
  10300. maxVolume = samples[i];
  10301. }
  10302. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10303. };
  10304. /**
  10305. * Animates audio level change
  10306. * @param newLevel the new audio level
  10307. * @param lastLevel the last audio level
  10308. * @returns {Number} the audio level to be set
  10309. */
  10310. function animateLevel(newLevel, lastLevel)
  10311. {
  10312. var value = 0;
  10313. var diff = lastLevel - newLevel;
  10314. if(diff > 0.2)
  10315. {
  10316. value = lastLevel - 0.2;
  10317. }
  10318. else if(diff < -0.4)
  10319. {
  10320. value = lastLevel + 0.4;
  10321. }
  10322. else
  10323. {
  10324. value = newLevel;
  10325. }
  10326. return parseFloat(value.toFixed(3));
  10327. }
  10328. /**
  10329. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10330. *
  10331. * @param stream the local stream
  10332. * @param interval stats refresh interval given in ms.
  10333. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  10334. * update.
  10335. * @constructor
  10336. */
  10337. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10338. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10339. this.stream = stream;
  10340. this.intervalId = null;
  10341. this.intervalMilis = interval;
  10342. this.eventEmitter = eventEmitter;
  10343. this.audioLevel = 0;
  10344. this.statisticsService = statisticsService;
  10345. }
  10346. /**
  10347. * Starts the collecting the statistics.
  10348. */
  10349. LocalStatsCollector.prototype.start = function () {
  10350. if (config.disableAudioLevels || !window.AudioContext)
  10351. return;
  10352. var context = new AudioContext();
  10353. var analyser = context.createAnalyser();
  10354. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  10355. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  10356. var source = context.createMediaStreamSource(this.stream);
  10357. source.connect(analyser);
  10358. var self = this;
  10359. this.intervalId = setInterval(
  10360. function () {
  10361. var array = new Uint8Array(analyser.frequencyBinCount);
  10362. analyser.getByteTimeDomainData(array);
  10363. var audioLevel = timeDomainDataToAudioLevel(array);
  10364. if(audioLevel != self.audioLevel) {
  10365. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10366. self.eventEmitter.emit(
  10367. "statistics.audioLevel",
  10368. self.statisticsService.LOCAL_JID,
  10369. self.audioLevel);
  10370. }
  10371. },
  10372. this.intervalMilis
  10373. );
  10374. };
  10375. /**
  10376. * Stops collecting the statistics.
  10377. */
  10378. LocalStatsCollector.prototype.stop = function () {
  10379. if (this.intervalId) {
  10380. clearInterval(this.intervalId);
  10381. this.intervalId = null;
  10382. }
  10383. };
  10384. module.exports = LocalStatsCollector;
  10385. },{}],50:[function(require,module,exports){
  10386. /* global ssrc2jid */
  10387. /* jshint -W117 */
  10388. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10389. /**
  10390. * Calculates packet lost percent using the number of lost packets and the
  10391. * number of all packet.
  10392. * @param lostPackets the number of lost packets
  10393. * @param totalPackets the number of all packets.
  10394. * @returns {number} packet loss percent
  10395. */
  10396. function calculatePacketLoss(lostPackets, totalPackets) {
  10397. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10398. return 0;
  10399. return Math.round((lostPackets/totalPackets)*100);
  10400. }
  10401. function getStatValue(item, name) {
  10402. var browserType = RTCBrowserType.getBrowserType();
  10403. if (!keyMap[browserType][name])
  10404. throw "The property isn't supported!";
  10405. var key = keyMap[browserType][name];
  10406. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10407. item.stat(key) : item[key];
  10408. }
  10409. /**
  10410. * Peer statistics data holder.
  10411. * @constructor
  10412. */
  10413. function PeerStats()
  10414. {
  10415. this.ssrc2Loss = {};
  10416. this.ssrc2AudioLevel = {};
  10417. this.ssrc2bitrate = {};
  10418. this.ssrc2resolution = {};
  10419. }
  10420. /**
  10421. * The bandwidth
  10422. * @type {{}}
  10423. */
  10424. PeerStats.bandwidth = {};
  10425. /**
  10426. * The bit rate
  10427. * @type {{}}
  10428. */
  10429. PeerStats.bitrate = {};
  10430. /**
  10431. * The packet loss rate
  10432. * @type {{}}
  10433. */
  10434. PeerStats.packetLoss = null;
  10435. /**
  10436. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10437. * represented by this instance.
  10438. * @param ssrc audio or video RTP stream SSRC.
  10439. * @param lossRate new packet loss rate value to be set.
  10440. */
  10441. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10442. {
  10443. this.ssrc2Loss[ssrc] = lossRate;
  10444. };
  10445. /**
  10446. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10447. * represented by this instance.
  10448. * @param ssrc audio or video RTP stream SSRC.
  10449. * @param resolution new resolution value to be set.
  10450. */
  10451. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10452. {
  10453. if(resolution === null && this.ssrc2resolution[ssrc])
  10454. {
  10455. delete this.ssrc2resolution[ssrc];
  10456. }
  10457. else if(resolution !== null)
  10458. this.ssrc2resolution[ssrc] = resolution;
  10459. };
  10460. /**
  10461. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10462. * represented by this instance.
  10463. * @param ssrc audio or video RTP stream SSRC.
  10464. * @param bitrate new bitrate value to be set.
  10465. */
  10466. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10467. {
  10468. if(this.ssrc2bitrate[ssrc])
  10469. {
  10470. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10471. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10472. }
  10473. else {
  10474. this.ssrc2bitrate[ssrc] = bitrate;
  10475. }
  10476. };
  10477. /**
  10478. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10479. * the stream which belongs to the peer represented by this instance.
  10480. * @param ssrc RTP stream SSRC for which current audio level value will be
  10481. * updated.
  10482. * @param audioLevel the new audio level value to be set. Value is truncated to
  10483. * fit the range from 0 to 1.
  10484. */
  10485. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10486. {
  10487. // Range limit 0 - 1
  10488. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10489. };
  10490. function formatAudioLevel(audioLevel) {
  10491. return Math.min(Math.max(audioLevel, 0), 1);
  10492. }
  10493. /**
  10494. * Array with the transport information.
  10495. * @type {Array}
  10496. */
  10497. PeerStats.transport = [];
  10498. /**
  10499. * <tt>StatsCollector</tt> registers for stats updates of given
  10500. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10501. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10502. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10503. * instance as an event source.
  10504. *
  10505. * @param peerconnection webRTC peer connection object.
  10506. * @param interval stats refresh interval given in ms.
  10507. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10508. * called on stats update.
  10509. * @constructor
  10510. */
  10511. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10512. {
  10513. this.peerconnection = peerconnection;
  10514. this.baselineAudioLevelsReport = null;
  10515. this.currentAudioLevelsReport = null;
  10516. this.currentStatsReport = null;
  10517. this.baselineStatsReport = null;
  10518. this.audioLevelsIntervalId = null;
  10519. this.eventEmitter = eventEmitter;
  10520. /**
  10521. * Gather PeerConnection stats once every this many milliseconds.
  10522. */
  10523. this.GATHER_INTERVAL = 15000;
  10524. /**
  10525. * Log stats via the focus once every this many milliseconds.
  10526. */
  10527. this.LOG_INTERVAL = 60000;
  10528. /**
  10529. * Gather stats and store them in this.statsToBeLogged.
  10530. */
  10531. this.gatherStatsIntervalId = null;
  10532. /**
  10533. * Send the stats already saved in this.statsToBeLogged to be logged via
  10534. * the focus.
  10535. */
  10536. this.logStatsIntervalId = null;
  10537. /**
  10538. * Stores the statistics which will be send to the focus to be logged.
  10539. */
  10540. this.statsToBeLogged =
  10541. {
  10542. timestamps: [],
  10543. stats: {}
  10544. };
  10545. // Updates stats interval
  10546. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10547. this.statsIntervalId = null;
  10548. this.statsIntervalMilis = statsInterval;
  10549. // Map of jids to PeerStats
  10550. this.jid2stats = {};
  10551. }
  10552. module.exports = StatsCollector;
  10553. /**
  10554. * Stops stats updates.
  10555. */
  10556. StatsCollector.prototype.stop = function () {
  10557. if (this.audioLevelsIntervalId) {
  10558. clearInterval(this.audioLevelsIntervalId);
  10559. this.audioLevelsIntervalId = null;
  10560. }
  10561. if (this.statsIntervalId)
  10562. {
  10563. clearInterval(this.statsIntervalId);
  10564. this.statsIntervalId = null;
  10565. }
  10566. if(this.logStatsIntervalId)
  10567. {
  10568. clearInterval(this.logStatsIntervalId);
  10569. this.logStatsIntervalId = null;
  10570. }
  10571. if(this.gatherStatsIntervalId)
  10572. {
  10573. clearInterval(this.gatherStatsIntervalId);
  10574. this.gatherStatsIntervalId = null;
  10575. }
  10576. };
  10577. /**
  10578. * Callback passed to <tt>getStats</tt> method.
  10579. * @param error an error that occurred on <tt>getStats</tt> call.
  10580. */
  10581. StatsCollector.prototype.errorCallback = function (error)
  10582. {
  10583. console.error("Get stats error", error);
  10584. this.stop();
  10585. };
  10586. /**
  10587. * Starts stats updates.
  10588. */
  10589. StatsCollector.prototype.start = function ()
  10590. {
  10591. var self = this;
  10592. if(!config.disableAudioLevels) {
  10593. this.audioLevelsIntervalId = setInterval(
  10594. function () {
  10595. // Interval updates
  10596. self.peerconnection.getStats(
  10597. function (report) {
  10598. var results = null;
  10599. if (!report || !report.result ||
  10600. typeof report.result != 'function') {
  10601. results = report;
  10602. }
  10603. else {
  10604. results = report.result();
  10605. }
  10606. //console.error("Got interval report", results);
  10607. self.currentAudioLevelsReport = results;
  10608. self.processAudioLevelReport();
  10609. self.baselineAudioLevelsReport =
  10610. self.currentAudioLevelsReport;
  10611. },
  10612. self.errorCallback
  10613. );
  10614. },
  10615. self.audioLevelsIntervalMilis
  10616. );
  10617. }
  10618. if(!config.disableStats && !navigator.mozGetUserMedia) {
  10619. this.statsIntervalId = setInterval(
  10620. function () {
  10621. // Interval updates
  10622. self.peerconnection.getStats(
  10623. function (report) {
  10624. var results = null;
  10625. if (!report || !report.result ||
  10626. typeof report.result != 'function') {
  10627. //firefox
  10628. results = report;
  10629. }
  10630. else {
  10631. //chrome
  10632. results = report.result();
  10633. }
  10634. //console.error("Got interval report", results);
  10635. self.currentStatsReport = results;
  10636. try {
  10637. self.processStatsReport();
  10638. }
  10639. catch (e) {
  10640. console.error("Unsupported key:" + e, e);
  10641. }
  10642. self.baselineStatsReport = self.currentStatsReport;
  10643. },
  10644. self.errorCallback
  10645. );
  10646. },
  10647. self.statsIntervalMilis
  10648. );
  10649. }
  10650. if (config.logStats && !navigator.mozGetUserMedia) {
  10651. this.gatherStatsIntervalId = setInterval(
  10652. function () {
  10653. self.peerconnection.getStats(
  10654. function (report) {
  10655. self.addStatsToBeLogged(report.result());
  10656. },
  10657. function () {
  10658. }
  10659. );
  10660. },
  10661. this.GATHER_INTERVAL
  10662. );
  10663. this.logStatsIntervalId = setInterval(
  10664. function() { self.logStats(); },
  10665. this.LOG_INTERVAL);
  10666. }
  10667. };
  10668. /**
  10669. * Checks whether a certain record should be included in the logged statistics.
  10670. */
  10671. function acceptStat(reportId, reportType, statName) {
  10672. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10673. return false;
  10674. if (reportType == "ssrc") {
  10675. if (statName == "googTrackId" ||
  10676. statName == "transportId" ||
  10677. statName == "ssrc")
  10678. return false;
  10679. }
  10680. return true;
  10681. }
  10682. /**
  10683. * Checks whether a certain record should be included in the logged statistics.
  10684. */
  10685. function acceptReport(id, type) {
  10686. if (id.substring(0, 15) == "googCertificate" ||
  10687. id.substring(0, 9) == "googTrack" ||
  10688. id.substring(0, 20) == "googLibjingleSession")
  10689. return false;
  10690. if (type == "googComponent")
  10691. return false;
  10692. return true;
  10693. }
  10694. /**
  10695. * Converts the stats to the format used for logging, and saves the data in
  10696. * this.statsToBeLogged.
  10697. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10698. */
  10699. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10700. var self = this;
  10701. var num_records = this.statsToBeLogged.timestamps.length;
  10702. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10703. reports.map(function (report) {
  10704. if (!acceptReport(report.id, report.type))
  10705. return;
  10706. var stat = self.statsToBeLogged.stats[report.id];
  10707. if (!stat) {
  10708. stat = self.statsToBeLogged.stats[report.id] = {};
  10709. }
  10710. stat.type = report.type;
  10711. report.names().map(function (name) {
  10712. if (!acceptStat(report.id, report.type, name))
  10713. return;
  10714. var values = stat[name];
  10715. if (!values) {
  10716. values = stat[name] = [];
  10717. }
  10718. while (values.length < num_records) {
  10719. values.push(null);
  10720. }
  10721. values.push(report.stat(name));
  10722. });
  10723. });
  10724. };
  10725. StatsCollector.prototype.logStats = function () {
  10726. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10727. return;
  10728. // Reset the stats
  10729. this.statsToBeLogged.stats = {};
  10730. this.statsToBeLogged.timestamps = [];
  10731. };
  10732. var keyMap = {};
  10733. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10734. "ssrc": "ssrc",
  10735. "packetsReceived": "packetsReceived",
  10736. "packetsLost": "packetsLost",
  10737. "packetsSent": "packetsSent",
  10738. "bytesReceived": "bytesReceived",
  10739. "bytesSent": "bytesSent"
  10740. };
  10741. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10742. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10743. "sendBandwidth": "googAvailableSendBandwidth",
  10744. "remoteAddress": "googRemoteAddress",
  10745. "transportType": "googTransportType",
  10746. "localAddress": "googLocalAddress",
  10747. "activeConnection": "googActiveConnection",
  10748. "ssrc": "ssrc",
  10749. "packetsReceived": "packetsReceived",
  10750. "packetsSent": "packetsSent",
  10751. "packetsLost": "packetsLost",
  10752. "bytesReceived": "bytesReceived",
  10753. "bytesSent": "bytesSent",
  10754. "googFrameHeightReceived": "googFrameHeightReceived",
  10755. "googFrameWidthReceived": "googFrameWidthReceived",
  10756. "googFrameHeightSent": "googFrameHeightSent",
  10757. "googFrameWidthSent": "googFrameWidthSent",
  10758. "audioInputLevel": "audioInputLevel",
  10759. "audioOutputLevel": "audioOutputLevel"
  10760. };
  10761. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  10762. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  10763. /**
  10764. * Stats processing logic.
  10765. */
  10766. StatsCollector.prototype.processStatsReport = function () {
  10767. if (!this.baselineStatsReport) {
  10768. return;
  10769. }
  10770. for (var idx in this.currentStatsReport) {
  10771. var now = this.currentStatsReport[idx];
  10772. try {
  10773. if (getStatValue(now, 'receiveBandwidth') ||
  10774. getStatValue(now, 'sendBandwidth')) {
  10775. PeerStats.bandwidth = {
  10776. "download": Math.round(
  10777. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10778. "upload": Math.round(
  10779. (getStatValue(now, 'sendBandwidth')) / 1000)
  10780. };
  10781. }
  10782. }
  10783. catch(e){/*not supported*/}
  10784. if(now.type == 'googCandidatePair')
  10785. {
  10786. var ip, type, localIP, active;
  10787. try {
  10788. ip = getStatValue(now, 'remoteAddress');
  10789. type = getStatValue(now, "transportType");
  10790. localIP = getStatValue(now, "localAddress");
  10791. active = getStatValue(now, "activeConnection");
  10792. }
  10793. catch(e){/*not supported*/}
  10794. if(!ip || !type || !localIP || active != "true")
  10795. continue;
  10796. var addressSaved = false;
  10797. for(var i = 0; i < PeerStats.transport.length; i++)
  10798. {
  10799. if(PeerStats.transport[i].ip == ip &&
  10800. PeerStats.transport[i].type == type &&
  10801. PeerStats.transport[i].localip == localIP)
  10802. {
  10803. addressSaved = true;
  10804. }
  10805. }
  10806. if(addressSaved)
  10807. continue;
  10808. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10809. continue;
  10810. }
  10811. if(now.type == "candidatepair")
  10812. {
  10813. if(now.state == "succeeded")
  10814. continue;
  10815. var local = this.currentStatsReport[now.localCandidateId];
  10816. var remote = this.currentStatsReport[now.remoteCandidateId];
  10817. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10818. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10819. }
  10820. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10821. now.type != "inboundrtp") {
  10822. continue;
  10823. }
  10824. var before = this.baselineStatsReport[idx];
  10825. if (!before) {
  10826. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10827. continue;
  10828. }
  10829. var ssrc = getStatValue(now, 'ssrc');
  10830. if(!ssrc)
  10831. continue;
  10832. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10833. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10834. console.warn("No jid for ssrc: " + ssrc);
  10835. continue;
  10836. }
  10837. var jidStats = this.jid2stats[jid];
  10838. if (!jidStats) {
  10839. jidStats = new PeerStats();
  10840. this.jid2stats[jid] = jidStats;
  10841. }
  10842. var isDownloadStream = true;
  10843. var key = 'packetsReceived';
  10844. if (!getStatValue(now, key))
  10845. {
  10846. isDownloadStream = false;
  10847. key = 'packetsSent';
  10848. if (!getStatValue(now, key))
  10849. {
  10850. console.warn("No packetsReceived nor packetSent stat found");
  10851. continue;
  10852. }
  10853. }
  10854. var packetsNow = getStatValue(now, key);
  10855. if(!packetsNow || packetsNow < 0)
  10856. packetsNow = 0;
  10857. var packetsBefore = getStatValue(before, key);
  10858. if(!packetsBefore || packetsBefore < 0)
  10859. packetsBefore = 0;
  10860. var packetRate = packetsNow - packetsBefore;
  10861. if(!packetRate || packetRate < 0)
  10862. packetRate = 0;
  10863. var currentLoss = getStatValue(now, 'packetsLost');
  10864. if(!currentLoss || currentLoss < 0)
  10865. currentLoss = 0;
  10866. var previousLoss = getStatValue(before, 'packetsLost');
  10867. if(!previousLoss || previousLoss < 0)
  10868. previousLoss = 0;
  10869. var lossRate = currentLoss - previousLoss;
  10870. if(!lossRate || lossRate < 0)
  10871. lossRate = 0;
  10872. var packetsTotal = (packetRate + lossRate);
  10873. jidStats.setSsrcLoss(ssrc,
  10874. {"packetsTotal": packetsTotal,
  10875. "packetsLost": lossRate,
  10876. "isDownloadStream": isDownloadStream});
  10877. var bytesReceived = 0, bytesSent = 0;
  10878. if(getStatValue(now, "bytesReceived"))
  10879. {
  10880. bytesReceived = getStatValue(now, "bytesReceived") -
  10881. getStatValue(before, "bytesReceived");
  10882. }
  10883. if(getStatValue(now, "bytesSent"))
  10884. {
  10885. bytesSent = getStatValue(now, "bytesSent") -
  10886. getStatValue(before, "bytesSent");
  10887. }
  10888. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10889. if(bytesReceived <= 0 || time <= 0)
  10890. {
  10891. bytesReceived = 0;
  10892. }
  10893. else
  10894. {
  10895. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10896. }
  10897. if(bytesSent <= 0 || time <= 0)
  10898. {
  10899. bytesSent = 0;
  10900. }
  10901. else
  10902. {
  10903. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10904. }
  10905. jidStats.setSsrcBitrate(ssrc, {
  10906. "download": bytesReceived,
  10907. "upload": bytesSent});
  10908. var resolution = {height: null, width: null};
  10909. try {
  10910. if (getStatValue(now, "googFrameHeightReceived") &&
  10911. getStatValue(now, "googFrameWidthReceived")) {
  10912. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10913. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10914. }
  10915. else if (getStatValue(now, "googFrameHeightSent") &&
  10916. getStatValue(now, "googFrameWidthSent")) {
  10917. resolution.height = getStatValue(now, "googFrameHeightSent");
  10918. resolution.width = getStatValue(now, "googFrameWidthSent");
  10919. }
  10920. }
  10921. catch(e){/*not supported*/}
  10922. if(resolution.height && resolution.width)
  10923. {
  10924. jidStats.setSsrcResolution(ssrc, resolution);
  10925. }
  10926. else
  10927. {
  10928. jidStats.setSsrcResolution(ssrc, null);
  10929. }
  10930. }
  10931. var self = this;
  10932. // Jid stats
  10933. var totalPackets = {download: 0, upload: 0};
  10934. var lostPackets = {download: 0, upload: 0};
  10935. var bitrateDownload = 0;
  10936. var bitrateUpload = 0;
  10937. var resolutions = {};
  10938. Object.keys(this.jid2stats).forEach(
  10939. function (jid)
  10940. {
  10941. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10942. function (ssrc)
  10943. {
  10944. var type = "upload";
  10945. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10946. type = "download";
  10947. totalPackets[type] +=
  10948. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10949. lostPackets[type] +=
  10950. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10951. }
  10952. );
  10953. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10954. function (ssrc) {
  10955. bitrateDownload +=
  10956. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10957. bitrateUpload +=
  10958. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10959. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10960. }
  10961. );
  10962. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10963. }
  10964. );
  10965. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10966. PeerStats.packetLoss = {
  10967. total:
  10968. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10969. totalPackets.download + totalPackets.upload),
  10970. download:
  10971. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10972. upload:
  10973. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10974. };
  10975. this.eventEmitter.emit("statistics.connectionstats",
  10976. {
  10977. "bitrate": PeerStats.bitrate,
  10978. "packetLoss": PeerStats.packetLoss,
  10979. "bandwidth": PeerStats.bandwidth,
  10980. "resolution": resolutions,
  10981. "transport": PeerStats.transport
  10982. });
  10983. PeerStats.transport = [];
  10984. };
  10985. /**
  10986. * Stats processing logic.
  10987. */
  10988. StatsCollector.prototype.processAudioLevelReport = function ()
  10989. {
  10990. if (!this.baselineAudioLevelsReport)
  10991. {
  10992. return;
  10993. }
  10994. for (var idx in this.currentAudioLevelsReport)
  10995. {
  10996. var now = this.currentAudioLevelsReport[idx];
  10997. if (now.type != 'ssrc')
  10998. {
  10999. continue;
  11000. }
  11001. var before = this.baselineAudioLevelsReport[idx];
  11002. if (!before)
  11003. {
  11004. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11005. continue;
  11006. }
  11007. var ssrc = getStatValue(now, 'ssrc');
  11008. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11009. if (!jid)
  11010. {
  11011. if((Date.now() - now.timestamp) < 3000)
  11012. console.warn("No jid for ssrc: " + ssrc);
  11013. continue;
  11014. }
  11015. var jidStats = this.jid2stats[jid];
  11016. if (!jidStats)
  11017. {
  11018. jidStats = new PeerStats();
  11019. this.jid2stats[jid] = jidStats;
  11020. }
  11021. // Audio level
  11022. var audioLevel = null;
  11023. try {
  11024. audioLevel = getStatValue(now, 'audioInputLevel');
  11025. if (!audioLevel)
  11026. audioLevel = getStatValue(now, 'audioOutputLevel');
  11027. }
  11028. catch(e) {/*not supported*/
  11029. console.warn("Audio Levels are not available in the statistics.");
  11030. clearInterval(this.audioLevelsIntervalId);
  11031. return;
  11032. }
  11033. if (audioLevel)
  11034. {
  11035. // TODO: can't find specs about what this value really is,
  11036. // but it seems to vary between 0 and around 32k.
  11037. audioLevel = audioLevel / 32767;
  11038. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11039. if(jid != APP.xmpp.myJid())
  11040. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11041. }
  11042. }
  11043. };
  11044. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11045. /**
  11046. * Created by hristo on 8/4/14.
  11047. */
  11048. var LocalStats = require("./LocalStatsCollector.js");
  11049. var RTPStats = require("./RTPStatsCollector.js");
  11050. var EventEmitter = require("events");
  11051. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11052. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11053. var CallStats = require("./CallStats");
  11054. var RTCEvents = require("../../service/RTC/RTCEvents");
  11055. var eventEmitter = new EventEmitter();
  11056. var localStats = null;
  11057. var rtpStats = null;
  11058. function stopLocal()
  11059. {
  11060. if(localStats)
  11061. {
  11062. localStats.stop();
  11063. localStats = null;
  11064. }
  11065. }
  11066. function stopRemote()
  11067. {
  11068. if(rtpStats)
  11069. {
  11070. rtpStats.stop();
  11071. eventEmitter.emit("statistics.stop");
  11072. rtpStats = null;
  11073. }
  11074. }
  11075. function startRemoteStats (peerconnection) {
  11076. if(rtpStats)
  11077. {
  11078. rtpStats.stop();
  11079. rtpStats = null;
  11080. }
  11081. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11082. rtpStats.start();
  11083. }
  11084. function onStreamCreated(stream)
  11085. {
  11086. if(stream.getOriginalStream().getAudioTracks().length === 0)
  11087. return;
  11088. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11089. eventEmitter);
  11090. localStats.start();
  11091. }
  11092. function onDisposeConference(onUnload) {
  11093. CallStats.sendTerminateEvent();
  11094. stopRemote();
  11095. if(onUnload) {
  11096. stopLocal();
  11097. eventEmitter.removeAllListeners();
  11098. }
  11099. }
  11100. var statistics =
  11101. {
  11102. /**
  11103. * Indicates that this audio level is for local jid.
  11104. * @type {string}
  11105. */
  11106. LOCAL_JID: 'local',
  11107. addAudioLevelListener: function(listener)
  11108. {
  11109. eventEmitter.on("statistics.audioLevel", listener);
  11110. },
  11111. removeAudioLevelListener: function(listener)
  11112. {
  11113. eventEmitter.removeListener("statistics.audioLevel", listener);
  11114. },
  11115. addConnectionStatsListener: function(listener)
  11116. {
  11117. eventEmitter.on("statistics.connectionstats", listener);
  11118. },
  11119. removeConnectionStatsListener: function(listener)
  11120. {
  11121. eventEmitter.removeListener("statistics.connectionstats", listener);
  11122. },
  11123. addRemoteStatsStopListener: function(listener)
  11124. {
  11125. eventEmitter.on("statistics.stop", listener);
  11126. },
  11127. removeRemoteStatsStopListener: function(listener)
  11128. {
  11129. eventEmitter.removeListener("statistics.stop", listener);
  11130. },
  11131. stop: function () {
  11132. stopLocal();
  11133. stopRemote();
  11134. if(eventEmitter)
  11135. {
  11136. eventEmitter.removeAllListeners();
  11137. }
  11138. },
  11139. stopRemoteStatistics: function()
  11140. {
  11141. stopRemote();
  11142. },
  11143. start: function () {
  11144. APP.RTC.addStreamListener(onStreamCreated,
  11145. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11146. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11147. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11148. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11149. startRemoteStats(event.peerconnection);
  11150. // CallStats.init(event);
  11151. });
  11152. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11153. CallStats.init(session);
  11154. })
  11155. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11156. CallStats.sendMuteEvent(mute, "audio");
  11157. });
  11158. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11159. CallStats.sendSetupFailedEvent();
  11160. })
  11161. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11162. CallStats.sendMuteEvent(mute, "video");
  11163. });
  11164. }
  11165. };
  11166. module.exports = statistics;
  11167. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes.js":105,"../../service/xmpp/XMPPEvents":112,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":113}],52:[function(require,module,exports){
  11168. var i18n = require("i18next-client");
  11169. var languages = require("../../service/translation/languages");
  11170. var Settings = require("../settings/Settings");
  11171. var DEFAULT_LANG = languages.EN;
  11172. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11173. return value.replace("__app__", interfaceConfig.APP_NAME);
  11174. });
  11175. var defaultOptions = {
  11176. detectLngQS: "lang",
  11177. useCookie: false,
  11178. fallbackLng: DEFAULT_LANG,
  11179. load: "unspecific",
  11180. resGetPath: 'lang/__ns__-__lng__.json',
  11181. ns: {
  11182. namespaces: ['main', 'languages'],
  11183. defaultNs: 'main'
  11184. },
  11185. lngWhitelist : languages.getLanguages(),
  11186. fallbackOnNull: true,
  11187. fallbackOnEmpty: true,
  11188. useDataAttrOptions: true,
  11189. defaultValueFromContent: false,
  11190. app: interfaceConfig.APP_NAME,
  11191. getAsync: false,
  11192. defaultValueFromContent: false,
  11193. customLoad: function(lng, ns, options, done) {
  11194. var resPath = "lang/__ns__-__lng__.json";
  11195. if(lng === languages.EN)
  11196. resPath = "lang/__ns__.json";
  11197. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11198. i18n.functions.ajax({
  11199. url: url,
  11200. success: function(data, status, xhr) {
  11201. i18n.functions.log('loaded: ' + url);
  11202. done(null, data);
  11203. },
  11204. error : function(xhr, status, error) {
  11205. if ((status && status == 200) ||
  11206. (xhr && xhr.status && xhr.status == 200)) {
  11207. // file loaded but invalid json, stop waste time !
  11208. i18n.functions.error('There is a typo in: ' + url);
  11209. } else if ((status && status == 404) ||
  11210. (xhr && xhr.status && xhr.status == 404)) {
  11211. i18n.functions.log('Does not exist: ' + url);
  11212. } else {
  11213. var theStatus = status ? status :
  11214. ((xhr && xhr.status) ? xhr.status : null);
  11215. i18n.functions.log(theStatus + ' when loading ' + url);
  11216. }
  11217. done(error, {});
  11218. },
  11219. dataType: "json",
  11220. async : options.getAsync
  11221. });
  11222. }
  11223. // options for caching
  11224. // useLocalStorage: true,
  11225. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11226. };
  11227. function initCompleted(t)
  11228. {
  11229. $("[data-i18n]").i18n();
  11230. }
  11231. function checkForParameter() {
  11232. var query = window.location.search.substring(1);
  11233. var vars = query.split("&");
  11234. for (var i=0;i<vars.length;i++) {
  11235. var pair = vars[i].split("=");
  11236. if(pair[0] == "lang")
  11237. {
  11238. return pair[1];
  11239. }
  11240. }
  11241. return null;
  11242. }
  11243. module.exports = {
  11244. init: function (lang) {
  11245. var options = defaultOptions;
  11246. if(!lang)
  11247. {
  11248. lang = checkForParameter();
  11249. if(!lang)
  11250. {
  11251. var settings = Settings.getSettings();
  11252. if(settings)
  11253. lang = settings.language;
  11254. if(!lang && config.defaultLanguage)
  11255. {
  11256. lang = config.defaultLanguage;
  11257. }
  11258. }
  11259. }
  11260. if(lang) {
  11261. options.lng = lang;
  11262. }
  11263. i18n.init(options, initCompleted);
  11264. },
  11265. translateString: function (key, options) {
  11266. return i18n.t(key, options);
  11267. },
  11268. setLanguage: function (lang) {
  11269. if(!lang)
  11270. lang = DEFAULT_LANG;
  11271. i18n.setLng(lang, defaultOptions, initCompleted);
  11272. },
  11273. getCurrentLanguage: function () {
  11274. return i18n.lng();
  11275. },
  11276. translateElement: function (selector) {
  11277. selector.i18n();
  11278. },
  11279. generateTranslationHTML: function (key, options) {
  11280. var str = "<span data-i18n=\"" + key + "\"";
  11281. if(options)
  11282. {
  11283. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11284. }
  11285. str += ">";
  11286. str += this.translateString(key, options);
  11287. str += "</span>";
  11288. return str;
  11289. }
  11290. };
  11291. },{"../../service/translation/languages":111,"../settings/Settings":47,"i18next-client":68}],53:[function(require,module,exports){
  11292. /* jshint -W117 */
  11293. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11294. var SDPDiffer = require("./SDPDiffer");
  11295. var SDPUtil = require("./SDPUtil");
  11296. var SDP = require("./SDP");
  11297. var async = require("async");
  11298. var transform = require("sdp-transform");
  11299. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11300. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11301. // Jingle stuff
  11302. function JingleSession(me, sid, connection, service, eventEmitter) {
  11303. this.me = me;
  11304. this.sid = sid;
  11305. this.connection = connection;
  11306. this.initiator = null;
  11307. this.responder = null;
  11308. this.isInitiator = null;
  11309. this.peerjid = null;
  11310. this.state = null;
  11311. this.localSDP = null;
  11312. this.remoteSDP = null;
  11313. this.relayedStreams = [];
  11314. this.startTime = null;
  11315. this.stopTime = null;
  11316. this.media_constraints = null;
  11317. this.pc_constraints = null;
  11318. this.ice_config = {};
  11319. this.drip_container = [];
  11320. this.service = service;
  11321. this.usetrickle = true;
  11322. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11323. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11324. this.hadstuncandidate = false;
  11325. this.hadturncandidate = false;
  11326. this.lasticecandidate = false;
  11327. this.statsinterval = null;
  11328. this.reason = null;
  11329. this.addssrc = [];
  11330. this.removessrc = [];
  11331. this.pendingop = null;
  11332. this.switchstreams = false;
  11333. this.wait = true;
  11334. this.localStreamsSSRC = null;
  11335. this.ssrcOwners = {};
  11336. this.ssrcVideoTypes = {};
  11337. this.eventEmitter = eventEmitter;
  11338. /**
  11339. * The indicator which determines whether the (local) video has been muted
  11340. * in response to a user command in contrast to an automatic decision made
  11341. * by the application logic.
  11342. */
  11343. this.videoMuteByUser = false;
  11344. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11345. // We start with the queue paused. We resume it when the signaling state is
  11346. // stable and the ice connection state is connected.
  11347. this.modifySourcesQueue.pause();
  11348. }
  11349. JingleSession.prototype.updateModifySourcesQueue = function() {
  11350. var signalingState = this.peerconnection.signalingState;
  11351. var iceConnectionState = this.peerconnection.iceConnectionState;
  11352. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11353. this.modifySourcesQueue.resume();
  11354. } else {
  11355. this.modifySourcesQueue.pause();
  11356. }
  11357. };
  11358. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11359. var self = this;
  11360. if (this.state !== null) {
  11361. console.error('attempt to initiate on session ' + this.sid +
  11362. 'in state ' + this.state);
  11363. return;
  11364. }
  11365. this.isInitiator = isInitiator;
  11366. this.state = 'pending';
  11367. this.initiator = isInitiator ? this.me : peerjid;
  11368. this.responder = !isInitiator ? this.me : peerjid;
  11369. this.peerjid = peerjid;
  11370. this.hadstuncandidate = false;
  11371. this.hadturncandidate = false;
  11372. this.lasticecandidate = false;
  11373. this.peerconnection
  11374. = new TraceablePeerConnection(
  11375. this.connection.jingle.ice_config,
  11376. this.connection.jingle.pc_constraints,
  11377. this);
  11378. this.peerconnection.onicecandidate = function (event) {
  11379. self.sendIceCandidate(event.candidate);
  11380. };
  11381. this.peerconnection.onaddstream = function (event) {
  11382. if (event.stream.id !== 'default') {
  11383. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  11384. self.remoteStreamAdded(event);
  11385. } else {
  11386. // This is a recvonly stream. Clients that implement Unified Plan,
  11387. // such as Firefox use recvonly "streams/channels/tracks" for
  11388. // receiving remote stream/tracks, as opposed to Plan B where there
  11389. // are only 3 channels: audio, video and data.
  11390. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11391. }
  11392. };
  11393. this.peerconnection.onremovestream = function (event) {
  11394. // Remove the stream from remoteStreams
  11395. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11396. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11397. };
  11398. this.peerconnection.onsignalingstatechange = function (event) {
  11399. if (!(self && self.peerconnection)) return;
  11400. self.updateModifySourcesQueue();
  11401. };
  11402. this.peerconnection.oniceconnectionstatechange = function (event) {
  11403. if (!(self && self.peerconnection)) return;
  11404. self.updateModifySourcesQueue();
  11405. switch (self.peerconnection.iceConnectionState) {
  11406. case 'connected':
  11407. this.startTime = new Date();
  11408. break;
  11409. case 'disconnected':
  11410. this.stopTime = new Date();
  11411. break;
  11412. case 'failed':
  11413. self.eventEmitter(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11414. break;
  11415. }
  11416. onIceConnectionStateChange(self.sid, self);
  11417. };
  11418. this.peerconnection.onnegotiationneeded = function (event) {
  11419. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11420. };
  11421. // add any local and relayed stream
  11422. APP.RTC.localStreams.forEach(function(stream) {
  11423. self.peerconnection.addStream(stream.getOriginalStream());
  11424. });
  11425. this.relayedStreams.forEach(function(stream) {
  11426. self.peerconnection.addStream(stream);
  11427. });
  11428. };
  11429. function onIceConnectionStateChange(sid, session) {
  11430. switch (session.peerconnection.iceConnectionState) {
  11431. case 'checking':
  11432. session.timeChecking = (new Date()).getTime();
  11433. session.firstconnect = true;
  11434. break;
  11435. case 'completed': // on caller side
  11436. case 'connected':
  11437. if (session.firstconnect) {
  11438. session.firstconnect = false;
  11439. var metadata = {};
  11440. metadata.setupTime
  11441. = (new Date()).getTime() - session.timeChecking;
  11442. session.peerconnection.getStats(function (res) {
  11443. if(res && res.result) {
  11444. res.result().forEach(function (report) {
  11445. if (report.type == 'googCandidatePair' &&
  11446. report.stat('googActiveConnection') == 'true') {
  11447. metadata.localCandidateType
  11448. = report.stat('googLocalCandidateType');
  11449. metadata.remoteCandidateType
  11450. = report.stat('googRemoteCandidateType');
  11451. // log pair as well so we can get nice pie
  11452. // charts
  11453. metadata.candidatePair
  11454. = report.stat('googLocalCandidateType') +
  11455. ';' +
  11456. report.stat('googRemoteCandidateType');
  11457. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11458. {
  11459. metadata.ipv6 = true;
  11460. }
  11461. }
  11462. });
  11463. }
  11464. });
  11465. }
  11466. break;
  11467. }
  11468. }
  11469. JingleSession.prototype.getVideoType = function () {
  11470. return APP.desktopsharing.isUsingScreenStream() ? 'screen' : 'camera';
  11471. };
  11472. JingleSession.prototype.accept = function () {
  11473. this.state = 'active';
  11474. var pranswer = this.peerconnection.localDescription;
  11475. if (!pranswer || pranswer.type != 'pranswer') {
  11476. return;
  11477. }
  11478. console.log('going from pranswer to answer');
  11479. if (this.usetrickle) {
  11480. // remove candidates already sent from session-accept
  11481. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11482. for (var i = 0; i < lines.length; i++) {
  11483. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11484. }
  11485. }
  11486. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11487. // FIXME: change any inactive to sendrecv or whatever they were originally
  11488. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11489. }
  11490. var prsdp = new SDP(pranswer.sdp);
  11491. var accept = $iq({to: this.peerjid,
  11492. type: 'set'})
  11493. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11494. action: 'session-accept',
  11495. initiator: this.initiator,
  11496. responder: this.responder,
  11497. sid: this.sid });
  11498. // FIXME why do we generate session-accept in 3 different places ?
  11499. prsdp.toJingle(
  11500. accept,
  11501. this.initiator == this.me ? 'initiator' : 'responder',
  11502. this.localStreamsSSRC,
  11503. self.getVideoType());
  11504. var sdp = this.peerconnection.localDescription.sdp;
  11505. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11506. // FIXME: change any inactive to sendrecv or whatever they were originally
  11507. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11508. }
  11509. var self = this;
  11510. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11511. function () {
  11512. //console.log('setLocalDescription success');
  11513. self.setLocalDescription();
  11514. self.connection.sendIQ(accept,
  11515. function () {
  11516. var ack = {};
  11517. ack.source = 'answer';
  11518. $(document).trigger('ack.jingle', [self.sid, ack]);
  11519. },
  11520. function (stanza) {
  11521. var error = ($(stanza).find('error').length) ? {
  11522. code: $(stanza).find('error').attr('code'),
  11523. reason: $(stanza).find('error :first')[0].tagName
  11524. }:{};
  11525. error.source = 'answer';
  11526. JingleSession.onJingleError(self.sid, error);
  11527. },
  11528. 10000);
  11529. },
  11530. function (e) {
  11531. console.error('setLocalDescription failed', e);
  11532. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11533. }
  11534. );
  11535. };
  11536. JingleSession.prototype.terminate = function (reason) {
  11537. this.state = 'ended';
  11538. this.reason = reason;
  11539. this.peerconnection.close();
  11540. if (this.statsinterval !== null) {
  11541. window.clearInterval(this.statsinterval);
  11542. this.statsinterval = null;
  11543. }
  11544. };
  11545. JingleSession.prototype.active = function () {
  11546. return this.state == 'active';
  11547. };
  11548. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11549. var self = this;
  11550. if (candidate && !this.lasticecandidate) {
  11551. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11552. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11553. if (!(ice && jcand)) {
  11554. console.error('failed to get ice && jcand');
  11555. return;
  11556. }
  11557. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11558. if (jcand.type === 'srflx') {
  11559. this.hadstuncandidate = true;
  11560. } else if (jcand.type === 'relay') {
  11561. this.hadturncandidate = true;
  11562. }
  11563. if (this.usetrickle) {
  11564. if (this.usedrip) {
  11565. if (this.drip_container.length === 0) {
  11566. // start 20ms callout
  11567. window.setTimeout(function () {
  11568. if (self.drip_container.length === 0) return;
  11569. self.sendIceCandidates(self.drip_container);
  11570. self.drip_container = [];
  11571. }, 20);
  11572. }
  11573. this.drip_container.push(candidate);
  11574. return;
  11575. } else {
  11576. self.sendIceCandidate([candidate]);
  11577. }
  11578. }
  11579. } else {
  11580. //console.log('sendIceCandidate: last candidate.');
  11581. if (!this.usetrickle) {
  11582. //console.log('should send full offer now...');
  11583. //FIXME why do we generate session-accept in 3 different places ?
  11584. var init = $iq({to: this.peerjid,
  11585. type: 'set'})
  11586. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11587. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11588. initiator: this.initiator,
  11589. sid: this.sid});
  11590. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11591. var self = this;
  11592. var sendJingle = function (ssrc) {
  11593. if(!ssrc)
  11594. ssrc = {};
  11595. self.localSDP.toJingle(
  11596. init,
  11597. self.initiator == self.me ? 'initiator' : 'responder',
  11598. ssrc,
  11599. self.getVideoType());
  11600. self.connection.sendIQ(init,
  11601. function () {
  11602. //console.log('session initiate ack');
  11603. var ack = {};
  11604. ack.source = 'offer';
  11605. $(document).trigger('ack.jingle', [self.sid, ack]);
  11606. },
  11607. function (stanza) {
  11608. self.state = 'error';
  11609. self.peerconnection.close();
  11610. var error = ($(stanza).find('error').length) ? {
  11611. code: $(stanza).find('error').attr('code'),
  11612. reason: $(stanza).find('error :first')[0].tagName,
  11613. }:{};
  11614. error.source = 'offer';
  11615. JingleSession.onJingleError(self.sid, error);
  11616. },
  11617. 10000);
  11618. }
  11619. sendJingle();
  11620. }
  11621. this.lasticecandidate = true;
  11622. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11623. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11624. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11625. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11626. }
  11627. }
  11628. };
  11629. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11630. console.log('sendIceCandidates', candidates);
  11631. var cand = $iq({to: this.peerjid, type: 'set'})
  11632. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11633. action: 'transport-info',
  11634. initiator: this.initiator,
  11635. sid: this.sid});
  11636. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11637. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11638. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11639. if (cands.length > 0) {
  11640. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11641. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11642. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11643. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11644. }).c('transport', ice);
  11645. for (var i = 0; i < cands.length; i++) {
  11646. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11647. }
  11648. // add fingerprint
  11649. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11650. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11651. tmp.required = true;
  11652. cand.c(
  11653. 'fingerprint',
  11654. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11655. .t(tmp.fingerprint);
  11656. delete tmp.fingerprint;
  11657. cand.attrs(tmp);
  11658. cand.up();
  11659. }
  11660. cand.up(); // transport
  11661. cand.up(); // content
  11662. }
  11663. }
  11664. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11665. //console.log('was this the last candidate', this.lasticecandidate);
  11666. this.connection.sendIQ(cand,
  11667. function () {
  11668. var ack = {};
  11669. ack.source = 'transportinfo';
  11670. $(document).trigger('ack.jingle', [this.sid, ack]);
  11671. },
  11672. function (stanza) {
  11673. var error = ($(stanza).find('error').length) ? {
  11674. code: $(stanza).find('error').attr('code'),
  11675. reason: $(stanza).find('error :first')[0].tagName,
  11676. }:{};
  11677. error.source = 'transportinfo';
  11678. JingleSession.onJingleError(this.sid, error);
  11679. },
  11680. 10000);
  11681. };
  11682. JingleSession.prototype.sendOffer = function () {
  11683. //console.log('sendOffer...');
  11684. var self = this;
  11685. this.peerconnection.createOffer(function (sdp) {
  11686. self.createdOffer(sdp);
  11687. },
  11688. function (e) {
  11689. console.error('createOffer failed', e);
  11690. },
  11691. this.media_constraints
  11692. );
  11693. };
  11694. // FIXME createdOffer is never used in jitsi-meet
  11695. JingleSession.prototype.createdOffer = function (sdp) {
  11696. //console.log('createdOffer', sdp);
  11697. var self = this;
  11698. this.localSDP = new SDP(sdp.sdp);
  11699. //this.localSDP.mangle();
  11700. var sendJingle = function () {
  11701. var init = $iq({to: this.peerjid,
  11702. type: 'set'})
  11703. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11704. action: 'session-initiate',
  11705. initiator: this.initiator,
  11706. sid: this.sid});
  11707. self.localSDP.toJingle(
  11708. init,
  11709. this.initiator == this.me ? 'initiator' : 'responder',
  11710. this.localStreamsSSRC,
  11711. self.getVideoType());
  11712. self.connection.sendIQ(init,
  11713. function () {
  11714. var ack = {};
  11715. ack.source = 'offer';
  11716. $(document).trigger('ack.jingle', [self.sid, ack]);
  11717. },
  11718. function (stanza) {
  11719. self.state = 'error';
  11720. self.peerconnection.close();
  11721. var error = ($(stanza).find('error').length) ? {
  11722. code: $(stanza).find('error').attr('code'),
  11723. reason: $(stanza).find('error :first')[0].tagName,
  11724. }:{};
  11725. error.source = 'offer';
  11726. JingleSession.onJingleError(self.sid, error);
  11727. },
  11728. 10000);
  11729. }
  11730. sdp.sdp = this.localSDP.raw;
  11731. this.peerconnection.setLocalDescription(sdp,
  11732. function () {
  11733. if(self.usetrickle)
  11734. {
  11735. sendJingle();
  11736. }
  11737. self.setLocalDescription();
  11738. //console.log('setLocalDescription success');
  11739. },
  11740. function (e) {
  11741. console.error('setLocalDescription failed', e);
  11742. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11743. }
  11744. );
  11745. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11746. for (var i = 0; i < cands.length; i++) {
  11747. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11748. if (cand.type == 'srflx') {
  11749. this.hadstuncandidate = true;
  11750. } else if (cand.type == 'relay') {
  11751. this.hadturncandidate = true;
  11752. }
  11753. }
  11754. };
  11755. JingleSession.prototype.readSsrcInfo = function (contents) {
  11756. var self = this;
  11757. $(contents).each(function (idx, content) {
  11758. var name = $(content).attr('name');
  11759. var mediaType = this.getAttribute('name');
  11760. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11761. ssrcs.each(function () {
  11762. var ssrc = this.getAttribute('ssrc');
  11763. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  11764. function () {
  11765. var owner = this.getAttribute('owner');
  11766. var videoType = this.getAttribute('video-type');
  11767. self.ssrcOwners[ssrc] = owner;
  11768. self.ssrcVideoTypes[ssrc] = videoType;
  11769. }
  11770. );
  11771. });
  11772. });
  11773. };
  11774. JingleSession.prototype.getSsrcOwner = function (ssrc) {
  11775. return this.ssrcOwners[ssrc];
  11776. };
  11777. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11778. //console.log('setting remote description... ', desctype);
  11779. this.remoteSDP = new SDP('');
  11780. this.remoteSDP.fromJingle(elem);
  11781. this.readSsrcInfo($(elem).find(">content"));
  11782. if (this.peerconnection.remoteDescription !== null) {
  11783. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11784. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11785. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11786. for (var i = 0; i < pranswer.media.length; i++) {
  11787. // make sure we have ice ufrag and pwd
  11788. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11789. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11790. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11791. } else {
  11792. console.warn('no ice ufrag?');
  11793. }
  11794. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11795. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11796. } else {
  11797. console.warn('no ice pwd?');
  11798. }
  11799. }
  11800. // copy over candidates
  11801. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11802. for (var j = 0; j < lines.length; j++) {
  11803. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11804. }
  11805. }
  11806. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11807. }
  11808. }
  11809. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11810. this.peerconnection.setRemoteDescription(remotedesc,
  11811. function () {
  11812. //console.log('setRemoteDescription success');
  11813. },
  11814. function (e) {
  11815. console.error('setRemoteDescription error', e);
  11816. JingleSession.onJingleFatalError(self, e);
  11817. }
  11818. );
  11819. };
  11820. JingleSession.prototype.addIceCandidate = function (elem) {
  11821. var self = this;
  11822. if (this.peerconnection.signalingState == 'closed') {
  11823. return;
  11824. }
  11825. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11826. console.log('trickle ice candidate arriving before session accept...');
  11827. // create a PRANSWER for setRemoteDescription
  11828. if (!this.remoteSDP) {
  11829. var cobbled = 'v=0\r\n' +
  11830. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11831. 's=-\r\n' +
  11832. 't=0 0\r\n';
  11833. // first, take some things from the local description
  11834. for (var i = 0; i < this.localSDP.media.length; i++) {
  11835. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11836. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11837. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11838. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11839. }
  11840. cobbled += 'a=inactive\r\n';
  11841. }
  11842. this.remoteSDP = new SDP(cobbled);
  11843. }
  11844. // then add things like ice and dtls from remote candidate
  11845. elem.each(function () {
  11846. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11847. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11848. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11849. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11850. var tmp = $(this).find('transport');
  11851. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11852. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11853. tmp = $(this).find('transport>fingerprint');
  11854. if (tmp.length) {
  11855. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11856. } else {
  11857. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11858. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11859. }
  11860. break;
  11861. }
  11862. }
  11863. }
  11864. });
  11865. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11866. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11867. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11868. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11869. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11870. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11871. }).length == this.remoteSDP.media.length;
  11872. if (iscomplete) {
  11873. console.log('setting pranswer');
  11874. try {
  11875. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11876. function() {
  11877. },
  11878. function(e) {
  11879. console.log('setRemoteDescription pranswer failed', e.toString());
  11880. });
  11881. } catch (e) {
  11882. console.error('setting pranswer failed', e);
  11883. }
  11884. } else {
  11885. //console.log('not yet setting pranswer');
  11886. }
  11887. }
  11888. // operate on each content element
  11889. elem.each(function () {
  11890. // would love to deactivate this, but firefox still requires it
  11891. var idx = -1;
  11892. var i;
  11893. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11894. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11895. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11896. idx = i;
  11897. break;
  11898. }
  11899. }
  11900. if (idx == -1) { // fall back to localdescription
  11901. for (i = 0; i < self.localSDP.media.length; i++) {
  11902. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11903. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11904. idx = i;
  11905. break;
  11906. }
  11907. }
  11908. }
  11909. var name = $(this).attr('name');
  11910. // TODO: check ice-pwd and ice-ufrag?
  11911. $(this).find('transport>candidate').each(function () {
  11912. var line, candidate;
  11913. line = SDPUtil.candidateFromJingle(this);
  11914. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11915. sdpMid: name,
  11916. candidate: line});
  11917. try {
  11918. self.peerconnection.addIceCandidate(candidate);
  11919. } catch (e) {
  11920. console.error('addIceCandidate failed', e.toString(), line);
  11921. }
  11922. });
  11923. });
  11924. };
  11925. JingleSession.prototype.sendAnswer = function (provisional) {
  11926. //console.log('createAnswer', provisional);
  11927. var self = this;
  11928. this.peerconnection.createAnswer(
  11929. function (sdp) {
  11930. self.createdAnswer(sdp, provisional);
  11931. },
  11932. function (e) {
  11933. console.error('createAnswer failed', e);
  11934. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11935. },
  11936. this.media_constraints
  11937. );
  11938. };
  11939. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11940. //console.log('createAnswer callback');
  11941. var self = this;
  11942. this.localSDP = new SDP(sdp.sdp);
  11943. //this.localSDP.mangle();
  11944. this.usepranswer = provisional === true;
  11945. if (this.usetrickle) {
  11946. if (this.usepranswer) {
  11947. sdp.type = 'pranswer';
  11948. for (var i = 0; i < this.localSDP.media.length; i++) {
  11949. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11950. }
  11951. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11952. }
  11953. }
  11954. var self = this;
  11955. var sendJingle = function (ssrcs) {
  11956. // FIXME why do we generate session-accept in 3 different places ?
  11957. var accept = $iq({to: self.peerjid,
  11958. type: 'set'})
  11959. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11960. action: 'session-accept',
  11961. initiator: self.initiator,
  11962. responder: self.responder,
  11963. sid: self.sid });
  11964. self.localSDP.toJingle(
  11965. accept,
  11966. self.initiator == self.me ? 'initiator' : 'responder',
  11967. ssrcs,
  11968. self.getVideoType());
  11969. self.connection.sendIQ(accept,
  11970. function () {
  11971. var ack = {};
  11972. ack.source = 'answer';
  11973. $(document).trigger('ack.jingle', [self.sid, ack]);
  11974. },
  11975. function (stanza) {
  11976. var error = ($(stanza).find('error').length) ? {
  11977. code: $(stanza).find('error').attr('code'),
  11978. reason: $(stanza).find('error :first')[0].tagName,
  11979. }:{};
  11980. error.source = 'answer';
  11981. JingleSession.onJingleError(self.sid, error);
  11982. },
  11983. 10000);
  11984. }
  11985. sdp.sdp = this.localSDP.raw;
  11986. this.peerconnection.setLocalDescription(sdp,
  11987. function () {
  11988. //console.log('setLocalDescription success');
  11989. if (self.usetrickle && !self.usepranswer) {
  11990. sendJingle();
  11991. }
  11992. self.setLocalDescription();
  11993. },
  11994. function (e) {
  11995. console.error('setLocalDescription failed', e);
  11996. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11997. }
  11998. );
  11999. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12000. for (var j = 0; j < cands.length; j++) {
  12001. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12002. if (cand.type == 'srflx') {
  12003. this.hadstuncandidate = true;
  12004. } else if (cand.type == 'relay') {
  12005. this.hadturncandidate = true;
  12006. }
  12007. }
  12008. };
  12009. JingleSession.prototype.sendTerminate = function (reason, text) {
  12010. var self = this,
  12011. term = $iq({to: this.peerjid,
  12012. type: 'set'})
  12013. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12014. action: 'session-terminate',
  12015. initiator: this.initiator,
  12016. sid: this.sid})
  12017. .c('reason')
  12018. .c(reason || 'success');
  12019. if (text) {
  12020. term.up().c('text').t(text);
  12021. }
  12022. this.connection.sendIQ(term,
  12023. function () {
  12024. self.peerconnection.close();
  12025. self.peerconnection = null;
  12026. self.terminate();
  12027. var ack = {};
  12028. ack.source = 'terminate';
  12029. $(document).trigger('ack.jingle', [self.sid, ack]);
  12030. },
  12031. function (stanza) {
  12032. var error = ($(stanza).find('error').length) ? {
  12033. code: $(stanza).find('error').attr('code'),
  12034. reason: $(stanza).find('error :first')[0].tagName,
  12035. }:{};
  12036. $(document).trigger('ack.jingle', [self.sid, error]);
  12037. },
  12038. 10000);
  12039. if (this.statsinterval !== null) {
  12040. window.clearInterval(this.statsinterval);
  12041. this.statsinterval = null;
  12042. }
  12043. };
  12044. JingleSession.prototype.addSource = function (elem, fromJid) {
  12045. var self = this;
  12046. // FIXME: dirty waiting
  12047. if (!this.peerconnection.localDescription)
  12048. {
  12049. console.warn("addSource - localDescription not ready yet")
  12050. setTimeout(function()
  12051. {
  12052. self.addSource(elem, fromJid);
  12053. },
  12054. 200
  12055. );
  12056. return;
  12057. }
  12058. console.log('addssrc', new Date().getTime());
  12059. console.log('ice', this.peerconnection.iceConnectionState);
  12060. this.readSsrcInfo(elem);
  12061. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12062. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12063. $(elem).each(function (idx, content) {
  12064. var name = $(content).attr('name');
  12065. var lines = '';
  12066. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12067. var semantics = this.getAttribute('semantics');
  12068. var ssrcs = $(this).find('>source').map(function () {
  12069. return this.getAttribute('ssrc');
  12070. }).get();
  12071. if (ssrcs.length != 0) {
  12072. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12073. }
  12074. });
  12075. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12076. tmp.each(function () {
  12077. var ssrc = $(this).attr('ssrc');
  12078. if(mySdp.containsSSRC(ssrc)){
  12079. /**
  12080. * This happens when multiple participants change their streams at the same time and
  12081. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12082. * addssrc are scheduled for update IQ. See
  12083. */
  12084. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12085. return;
  12086. }
  12087. $(this).find('>parameter').each(function () {
  12088. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12089. if ($(this).attr('value') && $(this).attr('value').length)
  12090. lines += ':' + $(this).attr('value');
  12091. lines += '\r\n';
  12092. });
  12093. });
  12094. sdp.media.forEach(function(media, idx) {
  12095. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12096. return;
  12097. sdp.media[idx] += lines;
  12098. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12099. self.addssrc[idx] += lines;
  12100. });
  12101. sdp.raw = sdp.session + sdp.media.join('');
  12102. });
  12103. this.modifySourcesQueue.push(function() {
  12104. // When a source is added and if this is FF, a new channel is allocated
  12105. // for receiving the added source. We need to diffuse the SSRC of this
  12106. // new recvonly channel to the rest of the peers.
  12107. console.log('modify sources done');
  12108. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12109. console.log("SDPs", mySdp, newSdp);
  12110. self.notifyMySSRCUpdate(mySdp, newSdp);
  12111. });
  12112. };
  12113. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12114. var self = this;
  12115. // FIXME: dirty waiting
  12116. if (!this.peerconnection.localDescription)
  12117. {
  12118. console.warn("removeSource - localDescription not ready yet")
  12119. setTimeout(function()
  12120. {
  12121. self.removeSource(elem, fromJid);
  12122. },
  12123. 200
  12124. );
  12125. return;
  12126. }
  12127. console.log('removessrc', new Date().getTime());
  12128. console.log('ice', this.peerconnection.iceConnectionState);
  12129. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12130. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12131. $(elem).each(function (idx, content) {
  12132. var name = $(content).attr('name');
  12133. var lines = '';
  12134. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12135. var semantics = this.getAttribute('semantics');
  12136. var ssrcs = $(this).find('>source').map(function () {
  12137. return this.getAttribute('ssrc');
  12138. }).get();
  12139. if (ssrcs.length != 0) {
  12140. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12141. }
  12142. });
  12143. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12144. tmp.each(function () {
  12145. var ssrc = $(this).attr('ssrc');
  12146. // This should never happen, but can be useful for bug detection
  12147. if(mySdp.containsSSRC(ssrc)){
  12148. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12149. return;
  12150. }
  12151. $(this).find('>parameter').each(function () {
  12152. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12153. if ($(this).attr('value') && $(this).attr('value').length)
  12154. lines += ':' + $(this).attr('value');
  12155. lines += '\r\n';
  12156. });
  12157. });
  12158. sdp.media.forEach(function(media, idx) {
  12159. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12160. return;
  12161. sdp.media[idx] += lines;
  12162. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12163. self.removessrc[idx] += lines;
  12164. });
  12165. sdp.raw = sdp.session + sdp.media.join('');
  12166. });
  12167. this.modifySourcesQueue.push(function() {
  12168. // When a source is removed and if this is FF, the recvonly channel that
  12169. // receives the remote stream is deactivated . We need to diffuse the
  12170. // recvonly SSRC removal to the rest of the peers.
  12171. console.log('modify sources done');
  12172. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12173. console.log("SDPs", mySdp, newSdp);
  12174. self.notifyMySSRCUpdate(mySdp, newSdp);
  12175. });
  12176. };
  12177. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12178. var self = this;
  12179. if (this.peerconnection.signalingState == 'closed') return;
  12180. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12181. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12182. this.setLocalDescription();
  12183. if(successCallback){
  12184. successCallback();
  12185. }
  12186. queueCallback();
  12187. return;
  12188. }
  12189. // Reset switch streams flag
  12190. this.switchstreams = false;
  12191. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12192. // add sources
  12193. this.addssrc.forEach(function(lines, idx) {
  12194. sdp.media[idx] += lines;
  12195. });
  12196. this.addssrc = [];
  12197. // remove sources
  12198. this.removessrc.forEach(function(lines, idx) {
  12199. lines = lines.split('\r\n');
  12200. lines.pop(); // remove empty last element;
  12201. lines.forEach(function(line) {
  12202. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12203. });
  12204. });
  12205. this.removessrc = [];
  12206. sdp.raw = sdp.session + sdp.media.join('');
  12207. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12208. function() {
  12209. if(self.signalingState == 'closed') {
  12210. console.error("createAnswer attempt on closed state");
  12211. queueCallback("createAnswer attempt on closed state");
  12212. return;
  12213. }
  12214. self.peerconnection.createAnswer(
  12215. function(modifiedAnswer) {
  12216. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12217. if (self.pendingop !== null) {
  12218. var sdp = new SDP(modifiedAnswer.sdp);
  12219. if (sdp.media.length > 1) {
  12220. switch(self.pendingop) {
  12221. case 'mute':
  12222. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12223. break;
  12224. case 'unmute':
  12225. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12226. break;
  12227. }
  12228. sdp.raw = sdp.session + sdp.media.join('');
  12229. modifiedAnswer.sdp = sdp.raw;
  12230. }
  12231. self.pendingop = null;
  12232. }
  12233. // FIXME: pushing down an answer while ice connection state
  12234. // is still checking is bad...
  12235. //console.log(self.peerconnection.iceConnectionState);
  12236. // trying to work around another chrome bug
  12237. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12238. self.peerconnection.setLocalDescription(modifiedAnswer,
  12239. function() {
  12240. //console.log('modified setLocalDescription ok');
  12241. self.setLocalDescription();
  12242. if(successCallback){
  12243. successCallback();
  12244. }
  12245. queueCallback();
  12246. },
  12247. function(error) {
  12248. console.error('modified setLocalDescription failed', error);
  12249. queueCallback(error);
  12250. }
  12251. );
  12252. },
  12253. function(error) {
  12254. console.error('modified answer failed', error);
  12255. queueCallback(error);
  12256. }
  12257. );
  12258. },
  12259. function(error) {
  12260. console.error('modify failed', error);
  12261. queueCallback(error);
  12262. }
  12263. );
  12264. };
  12265. /**
  12266. * Switches video streams.
  12267. * @param new_stream new stream that will be used as video of this session.
  12268. * @param oldStream old video stream of this session.
  12269. * @param success_callback callback executed after successful stream switch.
  12270. */
  12271. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12272. var self = this;
  12273. // Remember SDP to figure out added/removed SSRCs
  12274. var oldSdp = null;
  12275. if(self.peerconnection) {
  12276. if(self.peerconnection.localDescription) {
  12277. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12278. }
  12279. self.peerconnection.removeStream(oldStream, true);
  12280. if(new_stream)
  12281. self.peerconnection.addStream(new_stream);
  12282. }
  12283. // Conference is not active
  12284. if(!oldSdp || !self.peerconnection) {
  12285. success_callback();
  12286. return;
  12287. }
  12288. self.switchstreams = true;
  12289. self.modifySourcesQueue.push(function() {
  12290. console.log('modify sources done');
  12291. success_callback();
  12292. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12293. console.log("SDPs", oldSdp, newSdp);
  12294. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12295. });
  12296. };
  12297. /**
  12298. * Figures out added/removed ssrcs and send update IQs.
  12299. * @param old_sdp SDP object for old description.
  12300. * @param new_sdp SDP object for new description.
  12301. */
  12302. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12303. if (!(this.peerconnection.signalingState == 'stable' &&
  12304. this.peerconnection.iceConnectionState == 'connected')){
  12305. console.log("Too early to send updates");
  12306. return;
  12307. }
  12308. // send source-remove IQ.
  12309. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12310. var remove = $iq({to: this.peerjid, type: 'set'})
  12311. .c('jingle', {
  12312. xmlns: 'urn:xmpp:jingle:1',
  12313. action: 'source-remove',
  12314. initiator: this.initiator,
  12315. sid: this.sid
  12316. }
  12317. );
  12318. var removed = sdpDiffer.toJingle(remove);
  12319. if (removed) {
  12320. this.connection.sendIQ(remove,
  12321. function (res) {
  12322. console.info('got remove result', res);
  12323. },
  12324. function (err) {
  12325. console.error('got remove error', err);
  12326. }
  12327. );
  12328. } else {
  12329. console.log('removal not necessary');
  12330. }
  12331. // send source-add IQ.
  12332. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12333. var add = $iq({to: this.peerjid, type: 'set'})
  12334. .c('jingle', {
  12335. xmlns: 'urn:xmpp:jingle:1',
  12336. action: 'source-add',
  12337. initiator: this.initiator,
  12338. sid: this.sid
  12339. }
  12340. );
  12341. var added = sdpDiffer.toJingle(add, this.getVideoType());
  12342. if (added) {
  12343. this.connection.sendIQ(add,
  12344. function (res) {
  12345. console.info('got add result', res);
  12346. },
  12347. function (err) {
  12348. console.error('got add error', err);
  12349. }
  12350. );
  12351. } else {
  12352. console.log('addition not necessary');
  12353. }
  12354. };
  12355. /**
  12356. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12357. *
  12358. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12359. * tracks; otherwise, <tt>false</tt>
  12360. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12361. * tracks have been enabled/disabled. The function may, optionally, return
  12362. * another function which is to be invoked after the whole mute/unmute operation
  12363. * has completed successfully.
  12364. * @param options an object which specifies optional arguments such as the
  12365. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12366. * specifies whether the method was initiated in response to a user command (in
  12367. * contrast to an automatic decision made by the application logic)
  12368. */
  12369. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12370. var byUser;
  12371. if (options) {
  12372. byUser = options.byUser;
  12373. if (typeof byUser === 'undefined') {
  12374. byUser = true;
  12375. }
  12376. } else {
  12377. byUser = true;
  12378. }
  12379. // The user's command to mute the (local) video takes precedence over any
  12380. // automatic decision made by the application logic.
  12381. if (byUser) {
  12382. this.videoMuteByUser = mute;
  12383. } else if (this.videoMuteByUser) {
  12384. return;
  12385. }
  12386. this.hardMuteVideo(mute);
  12387. var self = this;
  12388. var oldSdp = null;
  12389. if(self.peerconnection) {
  12390. if(self.peerconnection.localDescription) {
  12391. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12392. }
  12393. }
  12394. this.modifySourcesQueue.push(function() {
  12395. console.log('modify sources done');
  12396. callback(mute);
  12397. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12398. console.log("SDPs", oldSdp, newSdp);
  12399. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12400. });
  12401. };
  12402. JingleSession.prototype.hardMuteVideo = function (muted) {
  12403. this.pendingop = muted ? 'mute' : 'unmute';
  12404. };
  12405. JingleSession.prototype.sendMute = function (muted, content) {
  12406. var info = $iq({to: this.peerjid,
  12407. type: 'set'})
  12408. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12409. action: 'session-info',
  12410. initiator: this.initiator,
  12411. sid: this.sid });
  12412. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12413. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12414. if (content) {
  12415. info.attrs({'name': content});
  12416. }
  12417. this.connection.send(info);
  12418. };
  12419. JingleSession.prototype.sendRinging = function () {
  12420. var info = $iq({to: this.peerjid,
  12421. type: 'set'})
  12422. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12423. action: 'session-info',
  12424. initiator: this.initiator,
  12425. sid: this.sid });
  12426. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12427. this.connection.send(info);
  12428. };
  12429. JingleSession.prototype.getStats = function (interval) {
  12430. var self = this;
  12431. var recv = {audio: 0, video: 0};
  12432. var lost = {audio: 0, video: 0};
  12433. var lastrecv = {audio: 0, video: 0};
  12434. var lastlost = {audio: 0, video: 0};
  12435. var loss = {audio: 0, video: 0};
  12436. var delta = {audio: 0, video: 0};
  12437. this.statsinterval = window.setInterval(function () {
  12438. if (self && self.peerconnection && self.peerconnection.getStats) {
  12439. self.peerconnection.getStats(function (stats) {
  12440. var results = stats.result();
  12441. // TODO: there are so much statistics you can get from this..
  12442. for (var i = 0; i < results.length; ++i) {
  12443. if (results[i].type == 'ssrc') {
  12444. var packetsrecv = results[i].stat('packetsReceived');
  12445. var packetslost = results[i].stat('packetsLost');
  12446. if (packetsrecv && packetslost) {
  12447. packetsrecv = parseInt(packetsrecv, 10);
  12448. packetslost = parseInt(packetslost, 10);
  12449. if (results[i].stat('googFrameRateReceived')) {
  12450. lastlost.video = lost.video;
  12451. lastrecv.video = recv.video;
  12452. recv.video = packetsrecv;
  12453. lost.video = packetslost;
  12454. } else {
  12455. lastlost.audio = lost.audio;
  12456. lastrecv.audio = recv.audio;
  12457. recv.audio = packetsrecv;
  12458. lost.audio = packetslost;
  12459. }
  12460. }
  12461. }
  12462. }
  12463. delta.audio = recv.audio - lastrecv.audio;
  12464. delta.video = recv.video - lastrecv.video;
  12465. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12466. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12467. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12468. });
  12469. }
  12470. }, interval || 3000);
  12471. return this.statsinterval;
  12472. };
  12473. JingleSession.onJingleError = function (session, error)
  12474. {
  12475. console.error("Jingle error", error);
  12476. }
  12477. JingleSession.onJingleFatalError = function (session, error)
  12478. {
  12479. this.service.sessionTerminated = true;
  12480. this.connection.emuc.doLeave();
  12481. APP.UI.messageHandler.showError("dialog.sorry",
  12482. "dialog.internalError");
  12483. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12484. }
  12485. JingleSession.prototype.setLocalDescription = function () {
  12486. var self = this;
  12487. var newssrcs = [];
  12488. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12489. session.media.forEach(function (media) {
  12490. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12491. // TODO(gp) maybe exclude FID streams?
  12492. media.ssrcs.forEach(function (ssrc) {
  12493. if (ssrc.attribute !== 'cname') {
  12494. return;
  12495. }
  12496. newssrcs.push({
  12497. 'ssrc': ssrc.id,
  12498. 'type': media.type
  12499. });
  12500. });
  12501. }
  12502. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12503. {
  12504. newssrcs.push({
  12505. 'ssrc': self.localStreamsSSRC[media.type],
  12506. 'type': media.type
  12507. });
  12508. }
  12509. });
  12510. console.log('new ssrcs', newssrcs);
  12511. // Bind us as local SSRCs owner
  12512. if (newssrcs.length > 0) {
  12513. for (var i = 1; i <= newssrcs.length; i ++) {
  12514. var ssrc = newssrcs[i-1].ssrc;
  12515. var myJid = self.connection.emuc.myroomjid;
  12516. self.ssrcOwners[ssrc] = myJid;
  12517. if (newssrcs[i-1].type === 'video'){
  12518. self.ssrcVideoTypes[ssrc] = self.getVideoType();
  12519. }
  12520. }
  12521. }
  12522. }
  12523. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12524. function sendKeyframe(pc) {
  12525. console.log('sendkeyframe', pc.iceConnectionState);
  12526. if (pc.iceConnectionState !== 'connected') return; // safe...
  12527. var self = this;
  12528. pc.setRemoteDescription(
  12529. pc.remoteDescription,
  12530. function () {
  12531. pc.createAnswer(
  12532. function (modifiedAnswer) {
  12533. pc.setLocalDescription(
  12534. modifiedAnswer,
  12535. function () {
  12536. // noop
  12537. },
  12538. function (error) {
  12539. console.log('triggerKeyframe setLocalDescription failed', error);
  12540. APP.UI.messageHandler.showError();
  12541. }
  12542. );
  12543. },
  12544. function (error) {
  12545. console.log('triggerKeyframe createAnswer failed', error);
  12546. APP.UI.messageHandler.showError();
  12547. }
  12548. );
  12549. },
  12550. function (error) {
  12551. console.log('triggerKeyframe setRemoteDescription failed', error);
  12552. APP.UI.messageHandler.showError();
  12553. }
  12554. );
  12555. }
  12556. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12557. var self = this;
  12558. var thessrc;
  12559. var streamId = APP.RTC.getStreamID(data.stream);
  12560. // look up an associated JID for a stream id
  12561. if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12562. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12563. var ssrclines
  12564. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12565. ssrclines = ssrclines.filter(function (line) {
  12566. // NOTE(gp) previously we filtered on the mslabel, but that property
  12567. // is not always present.
  12568. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12569. if (RTCBrowserType.isTemasysPluginUsed()) {
  12570. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12571. } else {
  12572. return ((line.indexOf('msid:' + streamId) !== -1));
  12573. }
  12574. });
  12575. if (ssrclines.length) {
  12576. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12577. if (!self.ssrcOwners[thessrc]) {
  12578. console.error("No SSRC owner known for: " + thessrc);
  12579. return;
  12580. }
  12581. data.peerjid = self.ssrcOwners[thessrc];
  12582. data.videoType = self.ssrcVideoTypes[thessrc]
  12583. console.log('associated jid', self.ssrcOwners[thessrc],
  12584. thessrc, data.videoType);
  12585. }
  12586. }
  12587. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12588. var isVideo = data.stream.getVideoTracks().length > 0;
  12589. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12590. if (isVideo &&
  12591. data.peerjid && this.peerjid === data.peerjid &&
  12592. data.stream.getVideoTracks().length === 0 &&
  12593. APP.RTC.localVideo.getTracks().length > 0) {
  12594. window.setTimeout(function () {
  12595. sendKeyframe(self.peerconnection);
  12596. }, 3000);
  12597. }
  12598. }
  12599. module.exports = JingleSession;
  12600. },{"../../service/xmpp/XMPPEvents":112,"../RTC/RTCBrowserType":8,"./SDP":54,"./SDPDiffer":55,"./SDPUtil":56,"./TraceablePeerConnection":57,"async":67,"sdp-transform":99}],54:[function(require,module,exports){
  12601. /* jshint -W117 */
  12602. var SDPUtil = require("./SDPUtil");
  12603. // SDP STUFF
  12604. function SDP(sdp) {
  12605. this.media = sdp.split('\r\nm=');
  12606. for (var i = 1; i < this.media.length; i++) {
  12607. this.media[i] = 'm=' + this.media[i];
  12608. if (i != this.media.length - 1) {
  12609. this.media[i] += '\r\n';
  12610. }
  12611. }
  12612. this.session = this.media.shift() + '\r\n';
  12613. this.raw = this.session + this.media.join('');
  12614. }
  12615. /**
  12616. * Returns map of MediaChannel mapped per channel idx.
  12617. */
  12618. SDP.prototype.getMediaSsrcMap = function() {
  12619. var self = this;
  12620. var media_ssrcs = {};
  12621. var tmp;
  12622. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12623. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12624. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12625. var media = {
  12626. mediaindex: mediaindex,
  12627. mid: mid,
  12628. ssrcs: {},
  12629. ssrcGroups: []
  12630. };
  12631. media_ssrcs[mediaindex] = media;
  12632. tmp.forEach(function (line) {
  12633. var linessrc = line.substring(7).split(' ')[0];
  12634. // allocate new ChannelSsrc
  12635. if(!media.ssrcs[linessrc]) {
  12636. media.ssrcs[linessrc] = {
  12637. ssrc: linessrc,
  12638. lines: []
  12639. };
  12640. }
  12641. media.ssrcs[linessrc].lines.push(line);
  12642. });
  12643. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12644. tmp.forEach(function(line){
  12645. var semantics = line.substr(0, idx).substr(13);
  12646. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12647. if (ssrcs.length != 0) {
  12648. media.ssrcGroups.push({
  12649. semantics: semantics,
  12650. ssrcs: ssrcs
  12651. });
  12652. }
  12653. });
  12654. }
  12655. return media_ssrcs;
  12656. };
  12657. /**
  12658. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12659. * @param ssrc the ssrc to check.
  12660. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12661. */
  12662. SDP.prototype.containsSSRC = function(ssrc) {
  12663. var medias = this.getMediaSsrcMap();
  12664. var contains = false;
  12665. Object.keys(medias).forEach(function(mediaindex){
  12666. var media = medias[mediaindex];
  12667. //console.log("Check", channel, ssrc);
  12668. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12669. contains = true;
  12670. }
  12671. });
  12672. return contains;
  12673. };
  12674. // remove iSAC and CN from SDP
  12675. SDP.prototype.mangle = function () {
  12676. var i, j, mline, lines, rtpmap, newdesc;
  12677. for (i = 0; i < this.media.length; i++) {
  12678. lines = this.media[i].split('\r\n');
  12679. lines.pop(); // remove empty last element
  12680. mline = SDPUtil.parse_mline(lines.shift());
  12681. if (mline.media != 'audio')
  12682. continue;
  12683. newdesc = '';
  12684. mline.fmt.length = 0;
  12685. for (j = 0; j < lines.length; j++) {
  12686. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12687. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12688. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12689. continue;
  12690. mline.fmt.push(rtpmap.id);
  12691. newdesc += lines[j] + '\r\n';
  12692. } else {
  12693. newdesc += lines[j] + '\r\n';
  12694. }
  12695. }
  12696. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12697. this.media[i] += newdesc;
  12698. }
  12699. this.raw = this.session + this.media.join('');
  12700. };
  12701. // remove lines matching prefix from session section
  12702. SDP.prototype.removeSessionLines = function(prefix) {
  12703. var self = this;
  12704. var lines = SDPUtil.find_lines(this.session, prefix);
  12705. lines.forEach(function(line) {
  12706. self.session = self.session.replace(line + '\r\n', '');
  12707. });
  12708. this.raw = this.session + this.media.join('');
  12709. return lines;
  12710. }
  12711. // remove lines matching prefix from a media section specified by mediaindex
  12712. // TODO: non-numeric mediaindex could match mid
  12713. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12714. var self = this;
  12715. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12716. lines.forEach(function(line) {
  12717. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12718. });
  12719. this.raw = this.session + this.media.join('');
  12720. return lines;
  12721. }
  12722. // add content's to a jingle element
  12723. SDP.prototype.toJingle = function (elem, thecreator, ssrcs, videoType) {
  12724. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12725. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12726. var self = this;
  12727. // new bundle plan
  12728. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12729. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12730. for (i = 0; i < lines.length; i++) {
  12731. tmp = lines[i].split(' ');
  12732. var semantics = tmp.shift().substr(8);
  12733. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12734. for (j = 0; j < tmp.length; j++) {
  12735. elem.c('content', {name: tmp[j]}).up();
  12736. }
  12737. elem.up();
  12738. }
  12739. }
  12740. for (i = 0; i < this.media.length; i++) {
  12741. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12742. if (!(mline.media === 'audio' ||
  12743. mline.media === 'video' ||
  12744. mline.media === 'application'))
  12745. {
  12746. continue;
  12747. }
  12748. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12749. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12750. } else {
  12751. if(ssrcs && ssrcs[mline.media])
  12752. {
  12753. ssrc = ssrcs[mline.media];
  12754. }
  12755. else
  12756. ssrc = false;
  12757. }
  12758. elem.c('content', {creator: thecreator, name: mline.media});
  12759. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12760. // prefer identifier from a=mid if present
  12761. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12762. elem.attrs({ name: mid });
  12763. }
  12764. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12765. {
  12766. elem.c('description',
  12767. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12768. media: mline.media });
  12769. if (ssrc) {
  12770. elem.attrs({ssrc: ssrc});
  12771. }
  12772. for (j = 0; j < mline.fmt.length; j++) {
  12773. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12774. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12775. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12776. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12777. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12778. for (k = 0; k < tmp.length; k++) {
  12779. elem.c('parameter', tmp[k]).up();
  12780. }
  12781. }
  12782. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12783. elem.up();
  12784. }
  12785. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12786. elem.c('encryption', {required: 1});
  12787. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12788. crypto.forEach(function(line) {
  12789. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12790. });
  12791. elem.up(); // end of encryption
  12792. }
  12793. if (ssrc) {
  12794. // new style mapping
  12795. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12796. // FIXME: group by ssrc and support multiple different ssrcs
  12797. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12798. if(ssrclines.length > 0) {
  12799. ssrclines.forEach(function (line) {
  12800. idx = line.indexOf(' ');
  12801. var linessrc = line.substr(0, idx).substr(7);
  12802. if (linessrc != ssrc) {
  12803. elem.up();
  12804. ssrc = linessrc;
  12805. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12806. }
  12807. var kv = line.substr(idx + 1);
  12808. elem.c('parameter');
  12809. if (kv.indexOf(':') == -1) {
  12810. elem.attrs({ name: kv });
  12811. } else {
  12812. var k = kv.split(':', 2)[0];
  12813. elem.attrs({ name: k });
  12814. var v = kv.split(':', 2)[1];
  12815. v = SDPUtil.filter_special_chars(v);
  12816. elem.attrs({ value: v });
  12817. }
  12818. elem.up();
  12819. });
  12820. }
  12821. else
  12822. {
  12823. elem.up();
  12824. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12825. elem.c('parameter');
  12826. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12827. elem.up();
  12828. var msid = null;
  12829. if(mline.media == "audio")
  12830. {
  12831. msid = APP.RTC.localAudio.getId();
  12832. }
  12833. else
  12834. {
  12835. msid = APP.RTC.localVideo.getId();
  12836. }
  12837. if(msid != null)
  12838. {
  12839. msid = SDPUtil.filter_special_chars(msid);
  12840. elem.c('parameter');
  12841. elem.attrs({name: "msid", value:msid});
  12842. elem.up();
  12843. elem.c('parameter');
  12844. elem.attrs({name: "mslabel", value:msid});
  12845. elem.up();
  12846. elem.c('parameter');
  12847. elem.attrs({name: "label", value:msid});
  12848. elem.up();
  12849. }
  12850. }
  12851. // Video type
  12852. if (videoType && mline.media == "video") {
  12853. elem.c('ssrc-info',
  12854. {
  12855. xmlns: 'http://jitsi.org/jitmeet',
  12856. 'video-type': videoType
  12857. }).up();
  12858. }
  12859. elem.up();
  12860. // XEP-0339 handle ssrc-group attributes
  12861. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12862. ssrc_group_lines.forEach(function(line) {
  12863. idx = line.indexOf(' ');
  12864. var semantics = line.substr(0, idx).substr(13);
  12865. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12866. if (ssrcs.length != 0) {
  12867. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12868. ssrcs.forEach(function(ssrc) {
  12869. elem.c('source', { ssrc: ssrc })
  12870. .up();
  12871. });
  12872. elem.up();
  12873. }
  12874. });
  12875. }
  12876. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12877. elem.c('rtcp-mux').up();
  12878. }
  12879. // XEP-0293 -- map a=rtcp-fb:*
  12880. this.RtcpFbToJingle(i, elem, '*');
  12881. // XEP-0294
  12882. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12883. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12884. for (j = 0; j < lines.length; j++) {
  12885. tmp = SDPUtil.parse_extmap(lines[j]);
  12886. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12887. uri: tmp.uri,
  12888. id: tmp.value });
  12889. if (tmp.hasOwnProperty('direction')) {
  12890. switch (tmp.direction) {
  12891. case 'sendonly':
  12892. elem.attrs({senders: 'responder'});
  12893. break;
  12894. case 'recvonly':
  12895. elem.attrs({senders: 'initiator'});
  12896. break;
  12897. case 'sendrecv':
  12898. elem.attrs({senders: 'both'});
  12899. break;
  12900. case 'inactive':
  12901. elem.attrs({senders: 'none'});
  12902. break;
  12903. }
  12904. }
  12905. // TODO: handle params
  12906. elem.up();
  12907. }
  12908. }
  12909. elem.up(); // end of description
  12910. }
  12911. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12912. this.TransportToJingle(i, elem);
  12913. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12914. elem.attrs({senders: 'both'});
  12915. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12916. elem.attrs({senders: 'initiator'});
  12917. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12918. elem.attrs({senders: 'responder'});
  12919. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12920. elem.attrs({senders: 'none'});
  12921. }
  12922. if (mline.port == '0') {
  12923. // estos hack to reject an m-line
  12924. elem.attrs({senders: 'rejected'});
  12925. }
  12926. elem.up(); // end of content
  12927. }
  12928. elem.up();
  12929. return elem;
  12930. };
  12931. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12932. var i = mediaindex;
  12933. var tmp;
  12934. var self = this;
  12935. elem.c('transport');
  12936. // XEP-0343 DTLS/SCTP
  12937. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12938. {
  12939. var sctpmap = SDPUtil.find_line(
  12940. this.media[i], 'a=sctpmap:', self.session);
  12941. if (sctpmap)
  12942. {
  12943. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12944. elem.c('sctpmap',
  12945. {
  12946. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12947. number: sctpAttrs[0], /* SCTP port */
  12948. protocol: sctpAttrs[1], /* protocol */
  12949. });
  12950. // Optional stream count attribute
  12951. if (sctpAttrs.length > 2)
  12952. elem.attrs({ streams: sctpAttrs[2]});
  12953. elem.up();
  12954. }
  12955. }
  12956. // XEP-0320
  12957. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12958. fingerprints.forEach(function(line) {
  12959. tmp = SDPUtil.parse_fingerprint(line);
  12960. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12961. elem.c('fingerprint').t(tmp.fingerprint);
  12962. delete tmp.fingerprint;
  12963. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12964. if (line) {
  12965. tmp.setup = line.substr(8);
  12966. }
  12967. elem.attrs(tmp);
  12968. elem.up(); // end of fingerprint
  12969. });
  12970. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12971. if (tmp) {
  12972. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12973. elem.attrs(tmp);
  12974. // XEP-0176
  12975. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12976. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12977. lines.forEach(function (line) {
  12978. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12979. });
  12980. }
  12981. }
  12982. elem.up(); // end of transport
  12983. }
  12984. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12985. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12986. lines.forEach(function (line) {
  12987. var tmp = SDPUtil.parse_rtcpfb(line);
  12988. if (tmp.type == 'trr-int') {
  12989. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12990. elem.up();
  12991. } else {
  12992. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12993. if (tmp.params.length > 0) {
  12994. elem.attrs({'subtype': tmp.params[0]});
  12995. }
  12996. elem.up();
  12997. }
  12998. });
  12999. };
  13000. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13001. var media = '';
  13002. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13003. if (tmp.length) {
  13004. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13005. if (tmp.attr('value')) {
  13006. media += tmp.attr('value');
  13007. } else {
  13008. media += '0';
  13009. }
  13010. media += '\r\n';
  13011. }
  13012. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13013. tmp.each(function () {
  13014. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13015. if ($(this).attr('subtype')) {
  13016. media += ' ' + $(this).attr('subtype');
  13017. }
  13018. media += '\r\n';
  13019. });
  13020. return media;
  13021. };
  13022. // construct an SDP from a jingle stanza
  13023. SDP.prototype.fromJingle = function (jingle) {
  13024. var self = this;
  13025. this.raw = 'v=0\r\n' +
  13026. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13027. 's=-\r\n' +
  13028. 't=0 0\r\n';
  13029. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13030. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13031. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13032. var contents = $(group).find('>content').map(function (idx, content) {
  13033. return content.getAttribute('name');
  13034. }).get();
  13035. if (contents.length > 0) {
  13036. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13037. }
  13038. });
  13039. }
  13040. this.session = this.raw;
  13041. jingle.find('>content').each(function () {
  13042. var m = self.jingle2media($(this));
  13043. self.media.push(m);
  13044. });
  13045. // reconstruct msid-semantic -- apparently not necessary
  13046. /*
  13047. var msid = SDPUtil.parse_ssrc(this.raw);
  13048. if (msid.hasOwnProperty('mslabel')) {
  13049. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13050. }
  13051. */
  13052. this.raw = this.session + this.media.join('');
  13053. };
  13054. // translate a jingle content element into an an SDP media part
  13055. SDP.prototype.jingle2media = function (content) {
  13056. var media = '',
  13057. desc = content.find('description'),
  13058. ssrc = desc.attr('ssrc'),
  13059. self = this,
  13060. tmp;
  13061. var sctp = content.find(
  13062. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13063. tmp = { media: desc.attr('media') };
  13064. tmp.port = '1';
  13065. if (content.attr('senders') == 'rejected') {
  13066. // estos hack to reject an m-line.
  13067. tmp.port = '0';
  13068. }
  13069. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13070. if (sctp.length)
  13071. tmp.proto = 'DTLS/SCTP';
  13072. else
  13073. tmp.proto = 'RTP/SAVPF';
  13074. } else {
  13075. tmp.proto = 'RTP/AVPF';
  13076. }
  13077. if (!sctp.length)
  13078. {
  13079. tmp.fmt = desc.find('payload-type').map(
  13080. function () { return this.getAttribute('id'); }).get();
  13081. media += SDPUtil.build_mline(tmp) + '\r\n';
  13082. }
  13083. else
  13084. {
  13085. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13086. media += 'a=sctpmap:' + sctp.attr('number') +
  13087. ' ' + sctp.attr('protocol');
  13088. var streamCount = sctp.attr('streams');
  13089. if (streamCount)
  13090. media += ' ' + streamCount + '\r\n';
  13091. else
  13092. media += '\r\n';
  13093. }
  13094. media += 'c=IN IP4 0.0.0.0\r\n';
  13095. if (!sctp.length)
  13096. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13097. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13098. if (tmp.length) {
  13099. if (tmp.attr('ufrag')) {
  13100. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13101. }
  13102. if (tmp.attr('pwd')) {
  13103. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13104. }
  13105. tmp.find('>fingerprint').each(function () {
  13106. // FIXME: check namespace at some point
  13107. media += 'a=fingerprint:' + this.getAttribute('hash');
  13108. media += ' ' + $(this).text();
  13109. media += '\r\n';
  13110. if (this.getAttribute('setup')) {
  13111. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13112. }
  13113. });
  13114. }
  13115. switch (content.attr('senders')) {
  13116. case 'initiator':
  13117. media += 'a=sendonly\r\n';
  13118. break;
  13119. case 'responder':
  13120. media += 'a=recvonly\r\n';
  13121. break;
  13122. case 'none':
  13123. media += 'a=inactive\r\n';
  13124. break;
  13125. case 'both':
  13126. media += 'a=sendrecv\r\n';
  13127. break;
  13128. }
  13129. media += 'a=mid:' + content.attr('name') + '\r\n';
  13130. // <description><rtcp-mux/></description>
  13131. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13132. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13133. if (desc.find('rtcp-mux').length) {
  13134. media += 'a=rtcp-mux\r\n';
  13135. }
  13136. if (desc.find('encryption').length) {
  13137. desc.find('encryption>crypto').each(function () {
  13138. media += 'a=crypto:' + this.getAttribute('tag');
  13139. media += ' ' + this.getAttribute('crypto-suite');
  13140. media += ' ' + this.getAttribute('key-params');
  13141. if (this.getAttribute('session-params')) {
  13142. media += ' ' + this.getAttribute('session-params');
  13143. }
  13144. media += '\r\n';
  13145. });
  13146. }
  13147. desc.find('payload-type').each(function () {
  13148. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13149. if ($(this).find('>parameter').length) {
  13150. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13151. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13152. media += '\r\n';
  13153. }
  13154. // xep-0293
  13155. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13156. });
  13157. // xep-0293
  13158. media += self.RtcpFbFromJingle(desc, '*');
  13159. // xep-0294
  13160. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13161. tmp.each(function () {
  13162. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13163. });
  13164. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13165. media += SDPUtil.candidateFromJingle(this);
  13166. });
  13167. // XEP-0339 handle ssrc-group attributes
  13168. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13169. var semantics = this.getAttribute('semantics');
  13170. var ssrcs = $(this).find('>source').map(function() {
  13171. return this.getAttribute('ssrc');
  13172. }).get();
  13173. if (ssrcs.length != 0) {
  13174. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13175. }
  13176. });
  13177. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13178. tmp.each(function () {
  13179. var ssrc = this.getAttribute('ssrc');
  13180. $(this).find('>parameter').each(function () {
  13181. var name = this.getAttribute('name');
  13182. var value = this.getAttribute('value');
  13183. value = SDPUtil.filter_special_chars(value);
  13184. media += 'a=ssrc:' + ssrc + ' ' + name;
  13185. if (value && value.length)
  13186. media += ':' + value;
  13187. media += '\r\n';
  13188. });
  13189. });
  13190. return media;
  13191. };
  13192. module.exports = SDP;
  13193. },{"./SDPUtil":56}],55:[function(require,module,exports){
  13194. var SDPUtil = require("./SDPUtil");
  13195. function SDPDiffer(mySDP, otherSDP) {
  13196. this.mySDP = mySDP;
  13197. this.otherSDP = otherSDP;
  13198. }
  13199. /**
  13200. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13201. * @param otherSdp the other SDP to check ssrc with.
  13202. */
  13203. SDPDiffer.prototype.getNewMedia = function() {
  13204. // this could be useful in Array.prototype.
  13205. function arrayEquals(array) {
  13206. // if the other array is a falsy value, return
  13207. if (!array)
  13208. return false;
  13209. // compare lengths - can save a lot of time
  13210. if (this.length != array.length)
  13211. return false;
  13212. for (var i = 0, l=this.length; i < l; i++) {
  13213. // Check if we have nested arrays
  13214. if (this[i] instanceof Array && array[i] instanceof Array) {
  13215. // recurse into the nested arrays
  13216. if (!this[i].equals(array[i]))
  13217. return false;
  13218. }
  13219. else if (this[i] != array[i]) {
  13220. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13221. return false;
  13222. }
  13223. }
  13224. return true;
  13225. }
  13226. var myMedias = this.mySDP.getMediaSsrcMap();
  13227. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13228. var newMedia = {};
  13229. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13230. var myMedia = myMedias[othersMediaIdx];
  13231. var othersMedia = othersMedias[othersMediaIdx];
  13232. if(!myMedia && othersMedia) {
  13233. // Add whole channel
  13234. newMedia[othersMediaIdx] = othersMedia;
  13235. return;
  13236. }
  13237. // Look for new ssrcs accross the channel
  13238. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13239. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13240. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13241. if(!newMedia[othersMediaIdx]){
  13242. newMedia[othersMediaIdx] = {
  13243. mediaindex: othersMedia.mediaindex,
  13244. mid: othersMedia.mid,
  13245. ssrcs: {},
  13246. ssrcGroups: []
  13247. };
  13248. }
  13249. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13250. }
  13251. });
  13252. // Look for new ssrc groups across the channels
  13253. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13254. // try to match the other ssrc-group with an ssrc-group of ours
  13255. var matched = false;
  13256. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13257. var mySsrcGroup = myMedia.ssrcGroups[i];
  13258. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13259. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13260. matched = true;
  13261. break;
  13262. }
  13263. }
  13264. if (!matched) {
  13265. // Allocate channel if we've found an ssrc-group that doesn't
  13266. // exist in our channel
  13267. if(!newMedia[othersMediaIdx]){
  13268. newMedia[othersMediaIdx] = {
  13269. mediaindex: othersMedia.mediaindex,
  13270. mid: othersMedia.mid,
  13271. ssrcs: {},
  13272. ssrcGroups: []
  13273. };
  13274. }
  13275. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13276. }
  13277. });
  13278. });
  13279. return newMedia;
  13280. };
  13281. /**
  13282. * Sends SSRC update IQ.
  13283. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13284. * @param sid session identifier that will be put into the IQ.
  13285. * @param initiator initiator identifier.
  13286. * @param toJid destination Jid
  13287. * @param isAdd indicates if this is remove or add operation.
  13288. */
  13289. SDPDiffer.prototype.toJingle = function(modify, videoType) {
  13290. var sdpMediaSsrcs = this.getNewMedia();
  13291. var self = this;
  13292. // FIXME: only announce video ssrcs since we mix audio and dont need
  13293. // the audio ssrcs therefore
  13294. var modified = false;
  13295. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13296. modified = true;
  13297. var media = sdpMediaSsrcs[mediaindex];
  13298. modify.c('content', {name: media.mid});
  13299. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13300. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13301. // generate sources from lines
  13302. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13303. var mediaSsrc = media.ssrcs[ssrcNum];
  13304. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13305. modify.attrs({ssrc: mediaSsrc.ssrc});
  13306. // iterate over ssrc lines
  13307. mediaSsrc.lines.forEach(function (line) {
  13308. var idx = line.indexOf(' ');
  13309. var kv = line.substr(idx + 1);
  13310. modify.c('parameter');
  13311. if (kv.indexOf(':') == -1) {
  13312. modify.attrs({ name: kv });
  13313. } else {
  13314. var nv = kv.split(':', 2);
  13315. var name = nv[0];
  13316. var value = SDPUtil.filter_special_chars(nv[1]);
  13317. modify.attrs({ name: name });
  13318. modify.attrs({ value: value });
  13319. }
  13320. modify.up(); // end of parameter
  13321. });
  13322. // indicate video type
  13323. if (videoType && media.mid == 'video') {
  13324. modify.c('ssrc-info',
  13325. {
  13326. xmlns: 'http://jitsi.org/jitmeet',
  13327. 'video-type': videoType
  13328. })
  13329. .up();
  13330. }
  13331. modify.up(); // end of source
  13332. });
  13333. // generate source groups from lines
  13334. media.ssrcGroups.forEach(function(ssrcGroup) {
  13335. if (ssrcGroup.ssrcs.length != 0) {
  13336. modify.c('ssrc-group', {
  13337. semantics: ssrcGroup.semantics,
  13338. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13339. });
  13340. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13341. modify.c('source', { ssrc: ssrc })
  13342. .up(); // end of source
  13343. });
  13344. modify.up(); // end of ssrc-group
  13345. }
  13346. });
  13347. modify.up(); // end of description
  13348. modify.up(); // end of content
  13349. });
  13350. return modified;
  13351. };
  13352. module.exports = SDPDiffer;
  13353. },{"./SDPUtil":56}],56:[function(require,module,exports){
  13354. SDPUtil = {
  13355. filter_special_chars: function (text) {
  13356. return text.replace(/[\\\/\{,\}\+]/g, "");
  13357. },
  13358. iceparams: function (mediadesc, sessiondesc) {
  13359. var data = null;
  13360. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13361. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13362. data = {
  13363. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13364. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13365. };
  13366. }
  13367. return data;
  13368. },
  13369. parse_iceufrag: function (line) {
  13370. return line.substring(12);
  13371. },
  13372. build_iceufrag: function (frag) {
  13373. return 'a=ice-ufrag:' + frag;
  13374. },
  13375. parse_icepwd: function (line) {
  13376. return line.substring(10);
  13377. },
  13378. build_icepwd: function (pwd) {
  13379. return 'a=ice-pwd:' + pwd;
  13380. },
  13381. parse_mid: function (line) {
  13382. return line.substring(6);
  13383. },
  13384. parse_mline: function (line) {
  13385. var parts = line.substring(2).split(' '),
  13386. data = {};
  13387. data.media = parts.shift();
  13388. data.port = parts.shift();
  13389. data.proto = parts.shift();
  13390. if (parts[parts.length - 1] === '') { // trailing whitespace
  13391. parts.pop();
  13392. }
  13393. data.fmt = parts;
  13394. return data;
  13395. },
  13396. build_mline: function (mline) {
  13397. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13398. },
  13399. parse_rtpmap: function (line) {
  13400. var parts = line.substring(9).split(' '),
  13401. data = {};
  13402. data.id = parts.shift();
  13403. parts = parts[0].split('/');
  13404. data.name = parts.shift();
  13405. data.clockrate = parts.shift();
  13406. data.channels = parts.length ? parts.shift() : '1';
  13407. return data;
  13408. },
  13409. /**
  13410. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13411. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13412. * @returns [SCTP port number, protocol, streams]
  13413. */
  13414. parse_sctpmap: function (line)
  13415. {
  13416. var parts = line.substring(10).split(' ');
  13417. var sctpPort = parts[0];
  13418. var protocol = parts[1];
  13419. // Stream count is optional
  13420. var streamCount = parts.length > 2 ? parts[2] : null;
  13421. return [sctpPort, protocol, streamCount];// SCTP port
  13422. },
  13423. build_rtpmap: function (el) {
  13424. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13425. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13426. line += '/' + el.getAttribute('channels');
  13427. }
  13428. return line;
  13429. },
  13430. parse_crypto: function (line) {
  13431. var parts = line.substring(9).split(' '),
  13432. data = {};
  13433. data.tag = parts.shift();
  13434. data['crypto-suite'] = parts.shift();
  13435. data['key-params'] = parts.shift();
  13436. if (parts.length) {
  13437. data['session-params'] = parts.join(' ');
  13438. }
  13439. return data;
  13440. },
  13441. parse_fingerprint: function (line) { // RFC 4572
  13442. var parts = line.substring(14).split(' '),
  13443. data = {};
  13444. data.hash = parts.shift();
  13445. data.fingerprint = parts.shift();
  13446. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13447. return data;
  13448. },
  13449. parse_fmtp: function (line) {
  13450. var parts = line.split(' '),
  13451. i, key, value,
  13452. data = [];
  13453. parts.shift();
  13454. parts = parts.join(' ').split(';');
  13455. for (i = 0; i < parts.length; i++) {
  13456. key = parts[i].split('=')[0];
  13457. while (key.length && key[0] == ' ') {
  13458. key = key.substring(1);
  13459. }
  13460. value = parts[i].split('=')[1];
  13461. if (key && value) {
  13462. data.push({name: key, value: value});
  13463. } else if (key) {
  13464. // rfc 4733 (DTMF) style stuff
  13465. data.push({name: '', value: key});
  13466. }
  13467. }
  13468. return data;
  13469. },
  13470. parse_icecandidate: function (line) {
  13471. var candidate = {},
  13472. elems = line.split(' ');
  13473. candidate.foundation = elems[0].substring(12);
  13474. candidate.component = elems[1];
  13475. candidate.protocol = elems[2].toLowerCase();
  13476. candidate.priority = elems[3];
  13477. candidate.ip = elems[4];
  13478. candidate.port = elems[5];
  13479. // elems[6] => "typ"
  13480. candidate.type = elems[7];
  13481. candidate.generation = 0; // default value, may be overwritten below
  13482. for (var i = 8; i < elems.length; i += 2) {
  13483. switch (elems[i]) {
  13484. case 'raddr':
  13485. candidate['rel-addr'] = elems[i + 1];
  13486. break;
  13487. case 'rport':
  13488. candidate['rel-port'] = elems[i + 1];
  13489. break;
  13490. case 'generation':
  13491. candidate.generation = elems[i + 1];
  13492. break;
  13493. case 'tcptype':
  13494. candidate.tcptype = elems[i + 1];
  13495. break;
  13496. default: // TODO
  13497. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13498. }
  13499. }
  13500. candidate.network = '1';
  13501. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13502. return candidate;
  13503. },
  13504. build_icecandidate: function (cand) {
  13505. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13506. line += ' ';
  13507. switch (cand.type) {
  13508. case 'srflx':
  13509. case 'prflx':
  13510. case 'relay':
  13511. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13512. line += 'raddr';
  13513. line += ' ';
  13514. line += cand['rel-addr'];
  13515. line += ' ';
  13516. line += 'rport';
  13517. line += ' ';
  13518. line += cand['rel-port'];
  13519. line += ' ';
  13520. }
  13521. break;
  13522. }
  13523. if (cand.hasOwnAttribute('tcptype')) {
  13524. line += 'tcptype';
  13525. line += ' ';
  13526. line += cand.tcptype;
  13527. line += ' ';
  13528. }
  13529. line += 'generation';
  13530. line += ' ';
  13531. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13532. return line;
  13533. },
  13534. parse_ssrc: function (desc) {
  13535. // proprietary mapping of a=ssrc lines
  13536. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13537. // and parse according to that
  13538. var lines = desc.split('\r\n'),
  13539. data = {};
  13540. for (var i = 0; i < lines.length; i++) {
  13541. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13542. var idx = lines[i].indexOf(' ');
  13543. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13544. }
  13545. }
  13546. return data;
  13547. },
  13548. parse_rtcpfb: function (line) {
  13549. var parts = line.substr(10).split(' ');
  13550. var data = {};
  13551. data.pt = parts.shift();
  13552. data.type = parts.shift();
  13553. data.params = parts;
  13554. return data;
  13555. },
  13556. parse_extmap: function (line) {
  13557. var parts = line.substr(9).split(' ');
  13558. var data = {};
  13559. data.value = parts.shift();
  13560. if (data.value.indexOf('/') != -1) {
  13561. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13562. data.value = data.value.substr(0, data.value.indexOf('/'));
  13563. } else {
  13564. data.direction = 'both';
  13565. }
  13566. data.uri = parts.shift();
  13567. data.params = parts;
  13568. return data;
  13569. },
  13570. find_line: function (haystack, needle, sessionpart) {
  13571. var lines = haystack.split('\r\n');
  13572. for (var i = 0; i < lines.length; i++) {
  13573. if (lines[i].substring(0, needle.length) == needle) {
  13574. return lines[i];
  13575. }
  13576. }
  13577. if (!sessionpart) {
  13578. return false;
  13579. }
  13580. // search session part
  13581. lines = sessionpart.split('\r\n');
  13582. for (var j = 0; j < lines.length; j++) {
  13583. if (lines[j].substring(0, needle.length) == needle) {
  13584. return lines[j];
  13585. }
  13586. }
  13587. return false;
  13588. },
  13589. find_lines: function (haystack, needle, sessionpart) {
  13590. var lines = haystack.split('\r\n'),
  13591. needles = [];
  13592. for (var i = 0; i < lines.length; i++) {
  13593. if (lines[i].substring(0, needle.length) == needle)
  13594. needles.push(lines[i]);
  13595. }
  13596. if (needles.length || !sessionpart) {
  13597. return needles;
  13598. }
  13599. // search session part
  13600. lines = sessionpart.split('\r\n');
  13601. for (var j = 0; j < lines.length; j++) {
  13602. if (lines[j].substring(0, needle.length) == needle) {
  13603. needles.push(lines[j]);
  13604. }
  13605. }
  13606. return needles;
  13607. },
  13608. candidateToJingle: function (line) {
  13609. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13610. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13611. if (line.indexOf('candidate:') === 0) {
  13612. line = 'a=' + line;
  13613. } else if (line.substring(0, 12) != 'a=candidate:') {
  13614. console.log('parseCandidate called with a line that is not a candidate line');
  13615. console.log(line);
  13616. return null;
  13617. }
  13618. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13619. line = line.substring(0, line.length - 2);
  13620. var candidate = {},
  13621. elems = line.split(' '),
  13622. i;
  13623. if (elems[6] != 'typ') {
  13624. console.log('did not find typ in the right place');
  13625. console.log(line);
  13626. return null;
  13627. }
  13628. candidate.foundation = elems[0].substring(12);
  13629. candidate.component = elems[1];
  13630. candidate.protocol = elems[2].toLowerCase();
  13631. candidate.priority = elems[3];
  13632. candidate.ip = elems[4];
  13633. candidate.port = elems[5];
  13634. // elems[6] => "typ"
  13635. candidate.type = elems[7];
  13636. candidate.generation = '0'; // default, may be overwritten below
  13637. for (i = 8; i < elems.length; i += 2) {
  13638. switch (elems[i]) {
  13639. case 'raddr':
  13640. candidate['rel-addr'] = elems[i + 1];
  13641. break;
  13642. case 'rport':
  13643. candidate['rel-port'] = elems[i + 1];
  13644. break;
  13645. case 'generation':
  13646. candidate.generation = elems[i + 1];
  13647. break;
  13648. case 'tcptype':
  13649. candidate.tcptype = elems[i + 1];
  13650. break;
  13651. default: // TODO
  13652. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13653. }
  13654. }
  13655. candidate.network = '1';
  13656. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13657. return candidate;
  13658. },
  13659. candidateFromJingle: function (cand) {
  13660. var line = 'a=candidate:';
  13661. line += cand.getAttribute('foundation');
  13662. line += ' ';
  13663. line += cand.getAttribute('component');
  13664. line += ' ';
  13665. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13666. line += ' ';
  13667. line += cand.getAttribute('priority');
  13668. line += ' ';
  13669. line += cand.getAttribute('ip');
  13670. line += ' ';
  13671. line += cand.getAttribute('port');
  13672. line += ' ';
  13673. line += 'typ';
  13674. line += ' ' + cand.getAttribute('type');
  13675. line += ' ';
  13676. switch (cand.getAttribute('type')) {
  13677. case 'srflx':
  13678. case 'prflx':
  13679. case 'relay':
  13680. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13681. line += 'raddr';
  13682. line += ' ';
  13683. line += cand.getAttribute('rel-addr');
  13684. line += ' ';
  13685. line += 'rport';
  13686. line += ' ';
  13687. line += cand.getAttribute('rel-port');
  13688. line += ' ';
  13689. }
  13690. break;
  13691. }
  13692. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13693. line += 'tcptype';
  13694. line += ' ';
  13695. line += cand.getAttribute('tcptype');
  13696. line += ' ';
  13697. }
  13698. line += 'generation';
  13699. line += ' ';
  13700. line += cand.getAttribute('generation') || '0';
  13701. return line + '\r\n';
  13702. }
  13703. };
  13704. module.exports = SDPUtil;
  13705. },{}],57:[function(require,module,exports){
  13706. var RTC = require('../RTC/RTC');
  13707. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  13708. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13709. function TraceablePeerConnection(ice_config, constraints, session) {
  13710. var self = this;
  13711. var RTCPeerconnectionType = null;
  13712. if (RTCBrowserType.isFirefox()) {
  13713. RTCPeerconnectionType = mozRTCPeerConnection;
  13714. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  13715. RTCPeerconnectionType = RTCPeerConnection;
  13716. } else {
  13717. RTCPeerconnectionType = webkitRTCPeerConnection;
  13718. }
  13719. this.peerconnection = new RTCPeerconnectionType(ice_config, constraints);
  13720. this.updateLog = [];
  13721. this.stats = {};
  13722. this.statsinterval = null;
  13723. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13724. var Interop = require('sdp-interop').Interop;
  13725. this.interop = new Interop();
  13726. var Simulcast = require('sdp-simulcast');
  13727. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  13728. // override as desired
  13729. this.trace = function (what, info) {
  13730. /*console.warn('WTRACE', what, info);
  13731. if (info && RTCBrowserType.isIExplorer()) {
  13732. if (info.length > 1024) {
  13733. console.warn('WTRACE', what, info.substr(1024));
  13734. }
  13735. if (info.length > 2048) {
  13736. console.warn('WTRACE', what, info.substr(2048));
  13737. }
  13738. }*/
  13739. self.updateLog.push({
  13740. time: new Date(),
  13741. type: what,
  13742. value: info || ""
  13743. });
  13744. };
  13745. this.onicecandidate = null;
  13746. this.peerconnection.onicecandidate = function (event) {
  13747. // FIXME: this causes stack overflow with Temasys Plugin
  13748. if (!RTCBrowserType.isTemasysPluginUsed())
  13749. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13750. if (self.onicecandidate !== null) {
  13751. self.onicecandidate(event);
  13752. }
  13753. };
  13754. this.onaddstream = null;
  13755. this.peerconnection.onaddstream = function (event) {
  13756. self.trace('onaddstream', event.stream.id);
  13757. if (self.onaddstream !== null) {
  13758. self.onaddstream(event);
  13759. }
  13760. };
  13761. this.onremovestream = null;
  13762. this.peerconnection.onremovestream = function (event) {
  13763. self.trace('onremovestream', event.stream.id);
  13764. if (self.onremovestream !== null) {
  13765. self.onremovestream(event);
  13766. }
  13767. };
  13768. this.onsignalingstatechange = null;
  13769. this.peerconnection.onsignalingstatechange = function (event) {
  13770. self.trace('onsignalingstatechange', self.signalingState);
  13771. if (self.onsignalingstatechange !== null) {
  13772. self.onsignalingstatechange(event);
  13773. }
  13774. };
  13775. this.oniceconnectionstatechange = null;
  13776. this.peerconnection.oniceconnectionstatechange = function (event) {
  13777. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13778. if (self.oniceconnectionstatechange !== null) {
  13779. self.oniceconnectionstatechange(event);
  13780. }
  13781. };
  13782. this.onnegotiationneeded = null;
  13783. this.peerconnection.onnegotiationneeded = function (event) {
  13784. self.trace('onnegotiationneeded');
  13785. if (self.onnegotiationneeded !== null) {
  13786. self.onnegotiationneeded(event);
  13787. }
  13788. };
  13789. self.ondatachannel = null;
  13790. this.peerconnection.ondatachannel = function (event) {
  13791. self.trace('ondatachannel', event);
  13792. if (self.ondatachannel !== null) {
  13793. self.ondatachannel(event);
  13794. }
  13795. };
  13796. if (!navigator.mozGetUserMedia && this.maxstats) {
  13797. this.statsinterval = window.setInterval(function() {
  13798. self.peerconnection.getStats(function(stats) {
  13799. var results = stats.result();
  13800. for (var i = 0; i < results.length; ++i) {
  13801. //console.log(results[i].type, results[i].id, results[i].names())
  13802. var now = new Date();
  13803. results[i].names().forEach(function (name) {
  13804. var id = results[i].id + '-' + name;
  13805. if (!self.stats[id]) {
  13806. self.stats[id] = {
  13807. startTime: now,
  13808. endTime: now,
  13809. values: [],
  13810. times: []
  13811. };
  13812. }
  13813. self.stats[id].values.push(results[i].stat(name));
  13814. self.stats[id].times.push(now.getTime());
  13815. if (self.stats[id].values.length > self.maxstats) {
  13816. self.stats[id].values.shift();
  13817. self.stats[id].times.shift();
  13818. }
  13819. self.stats[id].endTime = now;
  13820. });
  13821. }
  13822. });
  13823. }, 1000);
  13824. }
  13825. };
  13826. dumpSDP = function(description) {
  13827. if (typeof description === 'undefined' || description == null) {
  13828. return '';
  13829. }
  13830. return 'type: ' + description.type + '\r\n' + description.sdp;
  13831. };
  13832. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  13833. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  13834. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  13835. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  13836. var desc = this.peerconnection.localDescription;
  13837. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  13838. // if we're running on FF, transform to Plan B first.
  13839. if (navigator.mozGetUserMedia) {
  13840. desc = this.interop.toPlanB(desc);
  13841. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  13842. }
  13843. return desc;
  13844. });
  13845. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13846. var desc = this.peerconnection.remoteDescription;
  13847. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  13848. // if we're running on FF, transform to Plan B first.
  13849. if (navigator.mozGetUserMedia) {
  13850. desc = this.interop.toPlanB(desc);
  13851. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13852. }
  13853. return desc;
  13854. });
  13855. }
  13856. TraceablePeerConnection.prototype.addStream = function (stream) {
  13857. this.trace('addStream', stream.id);
  13858. try
  13859. {
  13860. this.peerconnection.addStream(stream);
  13861. }
  13862. catch (e)
  13863. {
  13864. console.error(e);
  13865. return;
  13866. }
  13867. };
  13868. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13869. this.trace('removeStream', stream.id);
  13870. if(stopStreams) {
  13871. stream.getAudioTracks().forEach(function (track) {
  13872. // stop() not supported with IE
  13873. if (track.stop) {
  13874. track.stop();
  13875. }
  13876. });
  13877. stream.getVideoTracks().forEach(function (track) {
  13878. // stop() not supported with IE
  13879. if (track.stop) {
  13880. track.stop();
  13881. }
  13882. });
  13883. if (stream.stop) {
  13884. stream.stop();
  13885. }
  13886. }
  13887. try {
  13888. // FF doesn't support this yet.
  13889. if (this.peerconnection.removeStream)
  13890. this.peerconnection.removeStream(stream);
  13891. } catch (e) {
  13892. console.error(e);
  13893. }
  13894. };
  13895. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13896. this.trace('createDataChannel', label, opts);
  13897. return this.peerconnection.createDataChannel(label, opts);
  13898. };
  13899. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13900. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  13901. // if we're running on FF, transform to Plan A first.
  13902. if (navigator.mozGetUserMedia) {
  13903. description = this.interop.toUnifiedPlan(description);
  13904. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13905. }
  13906. var self = this;
  13907. this.peerconnection.setLocalDescription(description,
  13908. function () {
  13909. self.trace('setLocalDescriptionOnSuccess');
  13910. successCallback();
  13911. },
  13912. function (err) {
  13913. self.trace('setLocalDescriptionOnFailure', err);
  13914. failureCallback(err);
  13915. }
  13916. );
  13917. /*
  13918. if (this.statsinterval === null && this.maxstats > 0) {
  13919. // start gathering stats
  13920. }
  13921. */
  13922. };
  13923. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13924. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  13925. // TODO the focus should squeze or explode the remote simulcast
  13926. description = this.simulcast.mungeRemoteDescription(description);
  13927. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  13928. // if we're running on FF, transform to Plan A first.
  13929. if (navigator.mozGetUserMedia) {
  13930. description = this.interop.toUnifiedPlan(description);
  13931. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13932. }
  13933. var self = this;
  13934. this.peerconnection.setRemoteDescription(description,
  13935. function () {
  13936. self.trace('setRemoteDescriptionOnSuccess');
  13937. successCallback();
  13938. },
  13939. function (err) {
  13940. self.trace('setRemoteDescriptionOnFailure', err);
  13941. failureCallback(err);
  13942. }
  13943. );
  13944. /*
  13945. if (this.statsinterval === null && this.maxstats > 0) {
  13946. // start gathering stats
  13947. }
  13948. */
  13949. };
  13950. TraceablePeerConnection.prototype.close = function () {
  13951. this.trace('stop');
  13952. if (this.statsinterval !== null) {
  13953. window.clearInterval(this.statsinterval);
  13954. this.statsinterval = null;
  13955. }
  13956. this.peerconnection.close();
  13957. };
  13958. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13959. var self = this;
  13960. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13961. this.peerconnection.createOffer(
  13962. function (offer) {
  13963. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  13964. // if we're running on FF, transform to Plan B first.
  13965. // NOTE this is not tested because in meet the focus generates the
  13966. // offer.
  13967. if (navigator.mozGetUserMedia) {
  13968. offer = self.interop.toPlanB(offer);
  13969. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13970. }
  13971. if (config.enableSimulcast && self.simulcast.isSupported()) {
  13972. offer = self.simulcast.mungeLocalDescription(offer);
  13973. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  13974. }
  13975. successCallback(offer);
  13976. },
  13977. function(err) {
  13978. self.trace('createOfferOnFailure', err);
  13979. failureCallback(err);
  13980. },
  13981. constraints
  13982. );
  13983. };
  13984. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13985. var self = this;
  13986. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13987. this.peerconnection.createAnswer(
  13988. function (answer) {
  13989. self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
  13990. // if we're running on FF, transform to Plan A first.
  13991. if (navigator.mozGetUserMedia) {
  13992. answer = self.interop.toPlanB(answer);
  13993. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13994. }
  13995. if (config.enableSimulcast && self.simulcast.isSupported()) {
  13996. answer = self.simulcast.mungeLocalDescription(answer);
  13997. self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
  13998. }
  13999. successCallback(answer);
  14000. },
  14001. function(err) {
  14002. self.trace('createAnswerOnFailure', err);
  14003. failureCallback(err);
  14004. },
  14005. constraints
  14006. );
  14007. };
  14008. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  14009. var self = this;
  14010. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14011. this.peerconnection.addIceCandidate(candidate);
  14012. /* maybe later
  14013. this.peerconnection.addIceCandidate(candidate,
  14014. function () {
  14015. self.trace('addIceCandidateOnSuccess');
  14016. successCallback();
  14017. },
  14018. function (err) {
  14019. self.trace('addIceCandidateOnFailure', err);
  14020. failureCallback(err);
  14021. }
  14022. );
  14023. */
  14024. };
  14025. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14026. if (navigator.mozGetUserMedia) {
  14027. // ignore for now...
  14028. if(!errback)
  14029. errback = function () {
  14030. }
  14031. this.peerconnection.getStats(null,callback,errback);
  14032. } else {
  14033. this.peerconnection.getStats(callback);
  14034. }
  14035. };
  14036. module.exports = TraceablePeerConnection;
  14037. },{"../../service/xmpp/XMPPEvents":112,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"sdp-interop":89,"sdp-simulcast":96}],58:[function(require,module,exports){
  14038. /* global $, $iq, APP, config, connection, UI, messageHandler,
  14039. roomName, sessionTerminated, Strophe, Util */
  14040. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14041. var Settings = require("../settings/Settings");
  14042. var AuthenticationEvents
  14043. = require("../../service/authentication/AuthenticationEvents");
  14044. /**
  14045. * Contains logic responsible for enabling/disabling functionality available
  14046. * only to moderator users.
  14047. */
  14048. var connection = null;
  14049. var focusUserJid;
  14050. function createExpBackoffTimer(step) {
  14051. var count = 1;
  14052. return function (reset) {
  14053. // Reset call
  14054. if (reset) {
  14055. count = 1;
  14056. return;
  14057. }
  14058. // Calculate next timeout
  14059. var timeout = Math.pow(2, count - 1);
  14060. count += 1;
  14061. return timeout * step;
  14062. };
  14063. }
  14064. var getNextTimeout = createExpBackoffTimer(1000);
  14065. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14066. // External authentication stuff
  14067. var externalAuthEnabled = false;
  14068. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14069. // it will be enabled automatically if focus detects the component through
  14070. // service discovery.
  14071. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14072. var eventEmitter = null;
  14073. var Moderator = {
  14074. isModerator: function () {
  14075. return connection && connection.emuc.isModerator();
  14076. },
  14077. isPeerModerator: function (peerJid) {
  14078. return connection &&
  14079. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14080. },
  14081. isExternalAuthEnabled: function () {
  14082. return externalAuthEnabled;
  14083. },
  14084. isSipGatewayEnabled: function () {
  14085. return sipGatewayEnabled;
  14086. },
  14087. setConnection: function (con) {
  14088. connection = con;
  14089. },
  14090. init: function (xmpp, emitter) {
  14091. this.xmppService = xmpp;
  14092. eventEmitter = emitter;
  14093. // Message listener that talks to POPUP window
  14094. function listener(event) {
  14095. if (event.data && event.data.sessionId) {
  14096. if (event.origin !== window.location.origin) {
  14097. console.warn(
  14098. "Ignoring sessionId from different origin: " + event.origin);
  14099. return;
  14100. }
  14101. localStorage.setItem('sessionId', event.data.sessionId);
  14102. // After popup is closed we will authenticate
  14103. }
  14104. }
  14105. // Register
  14106. if (window.addEventListener) {
  14107. window.addEventListener("message", listener, false);
  14108. } else {
  14109. window.attachEvent("onmessage", listener);
  14110. }
  14111. },
  14112. onMucMemberLeft: function (jid) {
  14113. console.info("Someone left is it focus ? " + jid);
  14114. var resource = Strophe.getResourceFromJid(jid);
  14115. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14116. console.info(
  14117. "Focus has left the room - leaving conference");
  14118. //hangUp();
  14119. // We'd rather reload to have everything re-initialized
  14120. // FIXME: show some message before reload
  14121. location.reload();
  14122. }
  14123. },
  14124. setFocusUserJid: function (focusJid) {
  14125. if (!focusUserJid) {
  14126. focusUserJid = focusJid;
  14127. console.info("Focus jid set to: " + focusUserJid);
  14128. }
  14129. },
  14130. getFocusUserJid: function () {
  14131. return focusUserJid;
  14132. },
  14133. getFocusComponent: function () {
  14134. // Get focus component address
  14135. var focusComponent = config.hosts.focus;
  14136. // If not specified use default: 'focus.domain'
  14137. if (!focusComponent) {
  14138. focusComponent = 'focus.' + config.hosts.domain;
  14139. }
  14140. return focusComponent;
  14141. },
  14142. createConferenceIq: function (roomName) {
  14143. // Generate create conference IQ
  14144. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14145. // Session Id used for authentication
  14146. var sessionId = localStorage.getItem('sessionId');
  14147. var machineUID = Settings.getSettings().uid;
  14148. console.info(
  14149. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14150. elem.c('conference', {
  14151. xmlns: 'http://jitsi.org/protocol/focus',
  14152. room: roomName,
  14153. 'machine-uid': machineUID
  14154. });
  14155. if (sessionId) {
  14156. elem.attrs({ 'session-id': sessionId});
  14157. }
  14158. if (config.hosts.bridge !== undefined) {
  14159. elem.c(
  14160. 'property',
  14161. { name: 'bridge', value: config.hosts.bridge})
  14162. .up();
  14163. }
  14164. // Tell the focus we have Jigasi configured
  14165. if (config.hosts.call_control !== undefined) {
  14166. elem.c(
  14167. 'property',
  14168. { name: 'call_control', value: config.hosts.call_control})
  14169. .up();
  14170. }
  14171. if (config.channelLastN !== undefined) {
  14172. elem.c(
  14173. 'property',
  14174. { name: 'channelLastN', value: config.channelLastN})
  14175. .up();
  14176. }
  14177. if (config.adaptiveLastN !== undefined) {
  14178. elem.c(
  14179. 'property',
  14180. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14181. .up();
  14182. }
  14183. if (config.adaptiveSimulcast !== undefined) {
  14184. elem.c(
  14185. 'property',
  14186. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14187. .up();
  14188. }
  14189. if (config.openSctp !== undefined) {
  14190. elem.c(
  14191. 'property',
  14192. { name: 'openSctp', value: config.openSctp})
  14193. .up();
  14194. }
  14195. if(config.startAudioMuted !== undefined)
  14196. {
  14197. elem.c(
  14198. 'property',
  14199. { name: 'startAudioMuted', value: config.startAudioMuted})
  14200. .up();
  14201. }
  14202. if(config.startVideoMuted !== undefined)
  14203. {
  14204. elem.c(
  14205. 'property',
  14206. { name: 'startVideoMuted', value: config.startVideoMuted})
  14207. .up();
  14208. }
  14209. elem.c(
  14210. 'property',
  14211. { name: 'simulcastMode', value: 'rewriting'})
  14212. .up();
  14213. elem.up();
  14214. return elem;
  14215. },
  14216. parseSessionId: function (resultIq) {
  14217. var sessionId = $(resultIq).find('conference').attr('session-id');
  14218. if (sessionId) {
  14219. console.info('Received sessionId: ' + sessionId);
  14220. localStorage.setItem('sessionId', sessionId);
  14221. }
  14222. },
  14223. parseConfigOptions: function (resultIq) {
  14224. Moderator.setFocusUserJid(
  14225. $(resultIq).find('conference').attr('focusjid'));
  14226. var authenticationEnabled
  14227. = $(resultIq).find(
  14228. '>conference>property' +
  14229. '[name=\'authentication\'][value=\'true\']').length > 0;
  14230. console.info("Authentication enabled: " + authenticationEnabled);
  14231. externalAuthEnabled
  14232. = $(resultIq).find(
  14233. '>conference>property' +
  14234. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14235. console.info('External authentication enabled: ' + externalAuthEnabled);
  14236. if (!externalAuthEnabled) {
  14237. // We expect to receive sessionId in 'internal' authentication mode
  14238. Moderator.parseSessionId(resultIq);
  14239. }
  14240. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14241. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14242. authenticationEnabled, authIdentity);
  14243. // Check if focus has auto-detected Jigasi component(this will be also
  14244. // included if we have passed our host from the config)
  14245. if ($(resultIq).find(
  14246. '>conference>property' +
  14247. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14248. sipGatewayEnabled = true;
  14249. }
  14250. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14251. },
  14252. // FIXME: we need to show the fact that we're waiting for the focus
  14253. // to the user(or that focus is not available)
  14254. allocateConferenceFocus: function (roomName, callback) {
  14255. // Try to use focus user JID from the config
  14256. Moderator.setFocusUserJid(config.focusUserJid);
  14257. // Send create conference IQ
  14258. var iq = Moderator.createConferenceIq(roomName);
  14259. var self = this;
  14260. connection.sendIQ(
  14261. iq,
  14262. function (result) {
  14263. // Setup config options
  14264. Moderator.parseConfigOptions(result);
  14265. if ('true' === $(result).find('conference').attr('ready')) {
  14266. // Reset both timers
  14267. getNextTimeout(true);
  14268. getNextErrorTimeout(true);
  14269. // Exec callback
  14270. callback();
  14271. } else {
  14272. var waitMs = getNextTimeout();
  14273. console.info("Waiting for the focus... " + waitMs);
  14274. // Reset error timeout
  14275. getNextErrorTimeout(true);
  14276. window.setTimeout(
  14277. function () {
  14278. Moderator.allocateConferenceFocus(
  14279. roomName, callback);
  14280. }, waitMs);
  14281. }
  14282. },
  14283. function (error) {
  14284. // Invalid session ? remove and try again
  14285. // without session ID to get a new one
  14286. var invalidSession
  14287. = $(error).find('>error>session-invalid').length;
  14288. if (invalidSession) {
  14289. console.info("Session expired! - removing");
  14290. localStorage.removeItem("sessionId");
  14291. }
  14292. if ($(error).find('>error>graceful-shutdown').length) {
  14293. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14294. return;
  14295. }
  14296. // Check for error returned by the reservation system
  14297. var reservationErr = $(error).find('>error>reservation-error');
  14298. if (reservationErr.length) {
  14299. // Trigger error event
  14300. var errorCode = reservationErr.attr('error-code');
  14301. var errorMsg;
  14302. if ($(error).find('>error>text')) {
  14303. errorMsg = $(error).find('>error>text').text();
  14304. }
  14305. eventEmitter.emit(
  14306. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14307. return;
  14308. }
  14309. // Not authorized to create new room
  14310. if ($(error).find('>error>not-authorized').length) {
  14311. console.warn("Unauthorized to start the conference", error);
  14312. var toDomain
  14313. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14314. if (toDomain !== config.hosts.anonymousdomain) {
  14315. // FIXME: "is external" should come either from
  14316. // the focus or config.js
  14317. externalAuthEnabled = true;
  14318. }
  14319. eventEmitter.emit(
  14320. XMPPEvents.AUTHENTICATION_REQUIRED,
  14321. function () {
  14322. Moderator.allocateConferenceFocus(
  14323. roomName, callback);
  14324. });
  14325. return;
  14326. }
  14327. var waitMs = getNextErrorTimeout();
  14328. console.error("Focus error, retry after " + waitMs, error);
  14329. // Show message
  14330. var focusComponent = Moderator.getFocusComponent();
  14331. var retrySec = waitMs / 1000;
  14332. // FIXME: message is duplicated ?
  14333. // Do not show in case of session invalid
  14334. // which means just a retry
  14335. if (!invalidSession) {
  14336. APP.UI.messageHandler.notify(
  14337. null, "notify.focus",
  14338. 'disconnected', "notify.focusFail",
  14339. {component: focusComponent, ms: retrySec});
  14340. }
  14341. // Reset response timeout
  14342. getNextTimeout(true);
  14343. window.setTimeout(
  14344. function () {
  14345. Moderator.allocateConferenceFocus(roomName, callback);
  14346. }, waitMs);
  14347. }
  14348. );
  14349. },
  14350. getLoginUrl: function (roomName, urlCallback) {
  14351. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14352. iq.c('login-url', {
  14353. xmlns: 'http://jitsi.org/protocol/focus',
  14354. room: roomName,
  14355. 'machine-uid': Settings.getSettings().uid
  14356. });
  14357. connection.sendIQ(
  14358. iq,
  14359. function (result) {
  14360. var url = $(result).find('login-url').attr('url');
  14361. url = url = decodeURIComponent(url);
  14362. if (url) {
  14363. console.info("Got auth url: " + url);
  14364. urlCallback(url);
  14365. } else {
  14366. console.error(
  14367. "Failed to get auth url from the focus", result);
  14368. }
  14369. },
  14370. function (error) {
  14371. console.error("Get auth url error", error);
  14372. }
  14373. );
  14374. },
  14375. getPopupLoginUrl: function (roomName, urlCallback) {
  14376. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14377. iq.c('login-url', {
  14378. xmlns: 'http://jitsi.org/protocol/focus',
  14379. room: roomName,
  14380. 'machine-uid': Settings.getSettings().uid,
  14381. popup: true
  14382. });
  14383. connection.sendIQ(
  14384. iq,
  14385. function (result) {
  14386. var url = $(result).find('login-url').attr('url');
  14387. url = url = decodeURIComponent(url);
  14388. if (url) {
  14389. console.info("Got POPUP auth url: " + url);
  14390. urlCallback(url);
  14391. } else {
  14392. console.error(
  14393. "Failed to get POPUP auth url from the focus", result);
  14394. }
  14395. },
  14396. function (error) {
  14397. console.error('Get POPUP auth url error', error);
  14398. }
  14399. );
  14400. },
  14401. logout: function (callback) {
  14402. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14403. var sessionId = localStorage.getItem('sessionId');
  14404. if (!sessionId) {
  14405. callback();
  14406. return;
  14407. }
  14408. iq.c('logout', {
  14409. xmlns: 'http://jitsi.org/protocol/focus',
  14410. 'session-id': sessionId
  14411. });
  14412. connection.sendIQ(
  14413. iq,
  14414. function (result) {
  14415. var logoutUrl = $(result).find('logout').attr('logout-url');
  14416. if (logoutUrl) {
  14417. logoutUrl = decodeURIComponent(logoutUrl);
  14418. }
  14419. console.info("Log out OK, url: " + logoutUrl, result);
  14420. localStorage.removeItem('sessionId');
  14421. callback(logoutUrl);
  14422. },
  14423. function (error) {
  14424. console.error("Logout error", error);
  14425. }
  14426. );
  14427. }
  14428. };
  14429. module.exports = Moderator;
  14430. },{"../../service/authentication/AuthenticationEvents":107,"../../service/xmpp/XMPPEvents":112,"../settings/Settings":47}],59:[function(require,module,exports){
  14431. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  14432. Toolbar, Util */
  14433. var Moderator = require("./moderator");
  14434. var recordingToken = null;
  14435. var recordingEnabled;
  14436. /**
  14437. * Whether to use a jirecon component for recording, or use the videobridge
  14438. * through COLIBRI.
  14439. */
  14440. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14441. /**
  14442. * The ID of the jirecon recording session. Jirecon generates it when we
  14443. * initially start recording, and it needs to be used in subsequent requests
  14444. * to jirecon.
  14445. */
  14446. var jireconRid = null;
  14447. function setRecordingToken(token) {
  14448. recordingToken = token;
  14449. }
  14450. function setRecording(state, token, callback, connection) {
  14451. if (useJirecon){
  14452. setRecordingJirecon(state, token, callback, connection);
  14453. } else {
  14454. setRecordingColibri(state, token, callback, connection);
  14455. }
  14456. }
  14457. function setRecordingJirecon(state, token, callback, connection) {
  14458. if (state == recordingEnabled){
  14459. return;
  14460. }
  14461. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14462. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14463. action: state ? 'start' : 'stop',
  14464. mucjid: connection.emuc.roomjid});
  14465. if (!state){
  14466. iq.attrs({rid: jireconRid});
  14467. }
  14468. console.log('Start recording');
  14469. connection.sendIQ(
  14470. iq,
  14471. function (result) {
  14472. // TODO wait for an IQ with the real status, since this is
  14473. // provisional?
  14474. jireconRid = $(result).find('recording').attr('rid');
  14475. console.log('Recording ' + (state ? 'started' : 'stopped') +
  14476. '(jirecon)' + result);
  14477. recordingEnabled = state;
  14478. if (!state){
  14479. jireconRid = null;
  14480. }
  14481. callback(state);
  14482. },
  14483. function (error) {
  14484. console.log('Failed to start recording, error: ', error);
  14485. callback(recordingEnabled);
  14486. });
  14487. }
  14488. // Sends a COLIBRI message which enables or disables (according to 'state')
  14489. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14490. // with the new recording state, according to the IQ.
  14491. function setRecordingColibri(state, token, callback, connection) {
  14492. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14493. elem.c('conference', {
  14494. xmlns: 'http://jitsi.org/protocol/colibri'
  14495. });
  14496. elem.c('recording', {state: state, token: token});
  14497. connection.sendIQ(elem,
  14498. function (result) {
  14499. console.log('Set recording "', state, '". Result:', result);
  14500. var recordingElem = $(result).find('>conference>recording');
  14501. var newState = ('true' === recordingElem.attr('state'));
  14502. recordingEnabled = newState;
  14503. callback(newState);
  14504. },
  14505. function (error) {
  14506. console.warn(error);
  14507. callback(recordingEnabled);
  14508. }
  14509. );
  14510. }
  14511. var Recording = {
  14512. toggleRecording: function (tokenEmptyCallback,
  14513. startingCallback, startedCallback, connection) {
  14514. if (!Moderator.isModerator()) {
  14515. console.log(
  14516. 'non-focus, or conference not yet organized:' +
  14517. ' not enabling recording');
  14518. return;
  14519. }
  14520. var self = this;
  14521. // Jirecon does not (currently) support a token.
  14522. if (!recordingToken && !useJirecon) {
  14523. tokenEmptyCallback(function (value) {
  14524. setRecordingToken(value);
  14525. self.toggleRecording(tokenEmptyCallback,
  14526. startingCallback, startedCallback, connection);
  14527. });
  14528. return;
  14529. }
  14530. var oldState = recordingEnabled;
  14531. startingCallback(!oldState);
  14532. setRecording(!oldState,
  14533. recordingToken,
  14534. function (state) {
  14535. console.log("New recording state: ", state);
  14536. if (state === oldState) {
  14537. // FIXME: new focus:
  14538. // this will not work when moderator changes
  14539. // during active session. Then it will assume that
  14540. // recording status has changed to true, but it might have
  14541. // been already true(and we only received actual status from
  14542. // the focus).
  14543. //
  14544. // SO we start with status null, so that it is initialized
  14545. // here and will fail only after second click, so if invalid
  14546. // token was used we have to press the button twice before
  14547. // current status will be fetched and token will be reset.
  14548. //
  14549. // Reliable way would be to return authentication error.
  14550. // Or status update when moderator connects.
  14551. // Or we have to stop recording session when current
  14552. // moderator leaves the room.
  14553. // Failed to change, reset the token because it might
  14554. // have been wrong
  14555. setRecordingToken(null);
  14556. }
  14557. startedCallback(state);
  14558. },
  14559. connection
  14560. );
  14561. }
  14562. }
  14563. module.exports = Recording;
  14564. },{"./moderator":58}],60:[function(require,module,exports){
  14565. /* jshint -W117 */
  14566. /* a simple MUC connection plugin
  14567. * can only handle a single MUC room
  14568. */
  14569. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14570. var Moderator = require("./moderator");
  14571. var JingleSession = require("./JingleSession");
  14572. var bridgeIsDown = false;
  14573. module.exports = function(XMPP, eventEmitter) {
  14574. Strophe.addConnectionPlugin('emuc', {
  14575. connection: null,
  14576. roomjid: null,
  14577. myroomjid: null,
  14578. members: {},
  14579. list_members: [], // so we can elect a new focus
  14580. presMap: {},
  14581. preziMap: {},
  14582. joined: false,
  14583. isOwner: false,
  14584. role: null,
  14585. focusMucJid: null,
  14586. init: function (conn) {
  14587. this.connection = conn;
  14588. },
  14589. initPresenceMap: function (myroomjid) {
  14590. this.presMap['to'] = myroomjid;
  14591. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14592. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted())
  14593. {
  14594. this.addAudioInfoToPresence(true);
  14595. }
  14596. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted())
  14597. {
  14598. this.addVideoInfoToPresence(true);
  14599. }
  14600. },
  14601. doJoin: function (jid, password) {
  14602. this.myroomjid = jid;
  14603. console.info("Joined MUC as " + this.myroomjid);
  14604. this.initPresenceMap(this.myroomjid);
  14605. if (!this.roomjid) {
  14606. this.roomjid = Strophe.getBareJidFromJid(jid);
  14607. // add handlers (just once)
  14608. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14609. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14610. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14611. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14612. }
  14613. if (password !== undefined) {
  14614. this.presMap['password'] = password;
  14615. }
  14616. this.sendPresence();
  14617. },
  14618. doLeave: function () {
  14619. console.log("do leave", this.myroomjid);
  14620. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14621. this.presMap.length = 0;
  14622. this.connection.send(pres);
  14623. },
  14624. createNonAnonymousRoom: function () {
  14625. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  14626. var getForm = $iq({type: 'get', to: this.roomjid})
  14627. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  14628. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14629. var self = this;
  14630. this.connection.sendIQ(getForm, function (form) {
  14631. if (!$(form).find(
  14632. '>query>x[xmlns="jabber:x:data"]' +
  14633. '>field[var="muc#roomconfig_whois"]').length) {
  14634. console.error('non-anonymous rooms not supported');
  14635. return;
  14636. }
  14637. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  14638. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14639. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14640. formSubmit.c('field', {'var': 'FORM_TYPE'})
  14641. .c('value')
  14642. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14643. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  14644. .c('value').t('anyone').up().up();
  14645. self.connection.sendIQ(formSubmit);
  14646. }, function (error) {
  14647. console.error("Error getting room configuration form");
  14648. });
  14649. },
  14650. onPresence: function (pres) {
  14651. var from = pres.getAttribute('from');
  14652. // What is this for? A workaround for something?
  14653. if (pres.getAttribute('type')) {
  14654. return true;
  14655. }
  14656. // Parse etherpad tag.
  14657. var etherpad = $(pres).find('>etherpad');
  14658. if (etherpad.length) {
  14659. if (config.etherpad_base) {
  14660. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  14661. }
  14662. }
  14663. // Parse prezi tag.
  14664. var presentation = $(pres).find('>prezi');
  14665. if (presentation.length) {
  14666. var url = presentation.attr('url');
  14667. var current = presentation.find('>current').text();
  14668. console.log('presentation info received from', from, url);
  14669. if (this.preziMap[from] == null) {
  14670. this.preziMap[from] = url;
  14671. $(document).trigger('presentationadded.muc', [from, url, current]);
  14672. }
  14673. else {
  14674. $(document).trigger('gotoslide.muc', [from, url, current]);
  14675. }
  14676. }
  14677. else if (this.preziMap[from] != null) {
  14678. var url = this.preziMap[from];
  14679. delete this.preziMap[from];
  14680. $(document).trigger('presentationremoved.muc', [from, url]);
  14681. }
  14682. // Parse audio info tag.
  14683. var audioMuted = $(pres).find('>audiomuted');
  14684. if (audioMuted.length) {
  14685. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  14686. from, (audioMuted.text() === "true"));
  14687. }
  14688. // Parse video info tag.
  14689. var videoMuted = $(pres).find('>videomuted');
  14690. if (videoMuted.length) {
  14691. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  14692. from, (videoMuted.text() === "true"));
  14693. }
  14694. var startMuted = $(pres).find('>startmuted');
  14695. if (startMuted.length)
  14696. {
  14697. eventEmitter.emit(XMPPEvents.START_MUTED,
  14698. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  14699. }
  14700. var devices = $(pres).find('>devices');
  14701. if(devices.length)
  14702. {
  14703. var audio = devices.find('>audio');
  14704. var video = devices.find('>video');
  14705. var devicesValues = {audio: false, video: false};
  14706. if(audio.length && audio.text() === "true")
  14707. {
  14708. devicesValues.audio = true;
  14709. }
  14710. if(video.length && video.text() === "true")
  14711. {
  14712. devicesValues.video = true;
  14713. }
  14714. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  14715. Strophe.getResourceFromJid(from), devicesValues);
  14716. }
  14717. var stats = $(pres).find('>stats');
  14718. if (stats.length) {
  14719. var statsObj = {};
  14720. Strophe.forEachChild(stats[0], "stat", function (el) {
  14721. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  14722. });
  14723. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  14724. }
  14725. // Parse status.
  14726. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  14727. this.isOwner = true;
  14728. this.createNonAnonymousRoom();
  14729. }
  14730. // Parse roles.
  14731. var member = {};
  14732. member.show = $(pres).find('>show').text();
  14733. member.status = $(pres).find('>status').text();
  14734. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  14735. member.affiliation = tmp.attr('affiliation');
  14736. member.role = tmp.attr('role');
  14737. // Focus recognition
  14738. member.jid = tmp.attr('jid');
  14739. member.isFocus = false;
  14740. if (member.jid
  14741. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  14742. member.isFocus = true;
  14743. }
  14744. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  14745. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  14746. if (from == this.myroomjid) {
  14747. if (member.affiliation == 'owner') this.isOwner = true;
  14748. if (this.role !== member.role) {
  14749. this.role = member.role;
  14750. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  14751. from, member, pres, Moderator.isModerator());
  14752. }
  14753. if (!this.joined) {
  14754. this.joined = true;
  14755. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  14756. this.list_members.push(from);
  14757. }
  14758. } else if (this.members[from] === undefined) {
  14759. // new participant
  14760. this.members[from] = member;
  14761. this.list_members.push(from);
  14762. console.log('entered', from, member);
  14763. if (member.isFocus) {
  14764. this.focusMucJid = from;
  14765. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  14766. }
  14767. else {
  14768. var id = $(pres).find('>userId').text();
  14769. var email = $(pres).find('>email');
  14770. if (email.length > 0) {
  14771. id = email.text();
  14772. }
  14773. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  14774. }
  14775. } else {
  14776. // Presence update for existing participant
  14777. // Watch role change:
  14778. if (this.members[from].role != member.role) {
  14779. this.members[from].role = member.role;
  14780. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  14781. member.role, member.displayName);
  14782. }
  14783. }
  14784. // Always trigger presence to update bindings
  14785. this.parsePresence(from, member, pres);
  14786. // Trigger status message update
  14787. if (member.status) {
  14788. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  14789. }
  14790. return true;
  14791. },
  14792. onPresenceUnavailable: function (pres) {
  14793. var from = pres.getAttribute('from');
  14794. // room destroyed ?
  14795. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14796. '>destroy').length) {
  14797. var reason;
  14798. var reasonSelect = $(pres).find(
  14799. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14800. '>destroy>reason');
  14801. if (reasonSelect.length) {
  14802. reason = reasonSelect.text();
  14803. }
  14804. XMPP.disposeConference(false);
  14805. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  14806. return true;
  14807. }
  14808. // Status code 110 indicates that this notification is "self-presence".
  14809. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  14810. delete this.members[from];
  14811. this.list_members.splice(this.list_members.indexOf(from), 1);
  14812. this.onParticipantLeft(from);
  14813. }
  14814. // If the status code is 110 this means we're leaving and we would like
  14815. // to remove everyone else from our view, so we trigger the event.
  14816. else if (this.list_members.length > 1) {
  14817. for (var i = 0; i < this.list_members.length; i++) {
  14818. var member = this.list_members[i];
  14819. delete this.members[i];
  14820. this.list_members.splice(i, 1);
  14821. this.onParticipantLeft(member);
  14822. }
  14823. }
  14824. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  14825. $(document).trigger('kicked.muc', [from]);
  14826. if (this.myroomjid === from) {
  14827. XMPP.disposeConference(false);
  14828. eventEmitter.emit(XMPPEvents.KICKED);
  14829. }
  14830. }
  14831. return true;
  14832. },
  14833. onPresenceError: function (pres) {
  14834. var from = pres.getAttribute('from');
  14835. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14836. console.log('on password required', from);
  14837. var self = this;
  14838. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  14839. self.doJoin(from, value);
  14840. });
  14841. } else if ($(pres).find(
  14842. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14843. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  14844. if (toDomain === config.hosts.anonymousdomain) {
  14845. // enter the room by replying with 'not-authorized'. This would
  14846. // result in reconnection from authorized domain.
  14847. // We're either missing Jicofo/Prosody config for anonymous
  14848. // domains or something is wrong.
  14849. // XMPP.promptLogin();
  14850. APP.UI.messageHandler.openReportDialog(null,
  14851. "dialog.joinError", pres);
  14852. } else {
  14853. console.warn('onPresError ', pres);
  14854. APP.UI.messageHandler.openReportDialog(null,
  14855. "dialog.connectError",
  14856. pres);
  14857. }
  14858. } else {
  14859. console.warn('onPresError ', pres);
  14860. APP.UI.messageHandler.openReportDialog(null,
  14861. "dialog.connectError",
  14862. pres);
  14863. }
  14864. return true;
  14865. },
  14866. sendMessage: function (body, nickname) {
  14867. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14868. msg.c('body', body).up();
  14869. if (nickname) {
  14870. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  14871. }
  14872. this.connection.send(msg);
  14873. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  14874. },
  14875. setSubject: function (subject) {
  14876. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14877. msg.c('subject', subject);
  14878. this.connection.send(msg);
  14879. console.log("topic changed to " + subject);
  14880. },
  14881. onMessage: function (msg) {
  14882. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14883. var from = msg.getAttribute('from');
  14884. var nick =
  14885. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14886. .text() ||
  14887. Strophe.getResourceFromJid(from);
  14888. var txt = $(msg).find('>body').text();
  14889. var type = msg.getAttribute("type");
  14890. if (type == "error") {
  14891. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14892. $(msg).find('>text').text(), txt);
  14893. return true;
  14894. }
  14895. var subject = $(msg).find('>subject');
  14896. if (subject.length) {
  14897. var subjectText = subject.text();
  14898. if (subjectText || subjectText == "") {
  14899. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14900. console.log("Subject is changed to " + subjectText);
  14901. }
  14902. }
  14903. // xep-0203 delay
  14904. var stamp = $(msg).find('>delay').attr('stamp');
  14905. if (!stamp) {
  14906. // or xep-0091 delay, UTC timestamp
  14907. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  14908. if (stamp) {
  14909. // the format is CCYYMMDDThh:mm:ss
  14910. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  14911. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  14912. }
  14913. }
  14914. if (txt) {
  14915. console.log('chat', nick, txt);
  14916. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14917. from, nick, txt, this.myroomjid, stamp);
  14918. }
  14919. return true;
  14920. },
  14921. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14922. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14923. var ob = this;
  14924. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14925. function (res) {
  14926. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14927. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14928. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14929. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14930. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14931. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14932. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14933. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14934. ob.connection.sendIQ(formsubmit,
  14935. onSuccess,
  14936. onError);
  14937. } else {
  14938. onNotSupported();
  14939. }
  14940. }, onError);
  14941. },
  14942. kick: function (jid) {
  14943. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14944. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14945. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14946. .c('reason').t('You have been kicked.').up().up().up();
  14947. this.connection.sendIQ(
  14948. kickIQ,
  14949. function (result) {
  14950. console.log('Kick participant with jid: ', jid, result);
  14951. },
  14952. function (error) {
  14953. console.log('Kick participant error: ', error);
  14954. });
  14955. },
  14956. sendPresence: function () {
  14957. if (!this.presMap['to']) {
  14958. // Too early to send presence - not initialized
  14959. return;
  14960. }
  14961. var pres = $pres({to: this.presMap['to'] });
  14962. pres.c('x', {xmlns: this.presMap['xns']});
  14963. if (this.presMap['password']) {
  14964. pres.c('password').t(this.presMap['password']).up();
  14965. }
  14966. pres.up();
  14967. // Send XEP-0115 'c' stanza that contains our capabilities info
  14968. if (this.connection.caps) {
  14969. this.connection.caps.node = config.clientNode;
  14970. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14971. }
  14972. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14973. .t(navigator.userAgent).up();
  14974. if (this.presMap['bridgeIsDown']) {
  14975. pres.c('bridgeIsDown').up();
  14976. }
  14977. if (this.presMap['email']) {
  14978. pres.c('email').t(this.presMap['email']).up();
  14979. }
  14980. if (this.presMap['userId']) {
  14981. pres.c('userId').t(this.presMap['userId']).up();
  14982. }
  14983. if (this.presMap['displayName']) {
  14984. // XEP-0172
  14985. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14986. .t(this.presMap['displayName']).up();
  14987. }
  14988. if(this.presMap["devices"])
  14989. {
  14990. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14991. .c('video').t(this.presMap['devices'].video).up().up();
  14992. }
  14993. if (this.presMap['audions']) {
  14994. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14995. .t(this.presMap['audiomuted']).up();
  14996. }
  14997. if (this.presMap['videons']) {
  14998. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14999. .t(this.presMap['videomuted']).up();
  15000. }
  15001. if (this.presMap['statsns']) {
  15002. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15003. for (var stat in this.presMap["stats"])
  15004. if (this.presMap["stats"][stat] != null)
  15005. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15006. pres.up();
  15007. }
  15008. if (this.presMap['prezins']) {
  15009. pres.c('prezi',
  15010. {xmlns: this.presMap['prezins'],
  15011. 'url': this.presMap['preziurl']})
  15012. .c('current').t(this.presMap['prezicurrent']).up().up();
  15013. }
  15014. if(this.presMap["startMuted"] !== undefined)
  15015. {
  15016. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15017. video: this.presMap["startMuted"].video,
  15018. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15019. delete this.presMap["startMuted"];
  15020. }
  15021. pres.up();
  15022. this.connection.send(pres);
  15023. },
  15024. addDisplayNameToPresence: function (displayName) {
  15025. this.presMap['displayName'] = displayName;
  15026. },
  15027. addDevicesToPresence: function (devices) {
  15028. this.presMap['devices'] = devices;
  15029. },
  15030. addPreziToPresence: function (url, currentSlide) {
  15031. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15032. this.presMap['preziurl'] = url;
  15033. this.presMap['prezicurrent'] = currentSlide;
  15034. },
  15035. removePreziFromPresence: function () {
  15036. delete this.presMap['prezins'];
  15037. delete this.presMap['preziurl'];
  15038. delete this.presMap['prezicurrent'];
  15039. },
  15040. addCurrentSlideToPresence: function (currentSlide) {
  15041. this.presMap['prezicurrent'] = currentSlide;
  15042. },
  15043. getPrezi: function (roomjid) {
  15044. return this.preziMap[roomjid];
  15045. },
  15046. addAudioInfoToPresence: function (isMuted) {
  15047. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15048. this.presMap['audiomuted'] = isMuted.toString();
  15049. },
  15050. addVideoInfoToPresence: function (isMuted) {
  15051. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15052. this.presMap['videomuted'] = isMuted.toString();
  15053. },
  15054. addConnectionInfoToPresence: function (stats) {
  15055. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15056. this.presMap['stats'] = stats;
  15057. },
  15058. findJidFromResource: function (resourceJid) {
  15059. if (resourceJid &&
  15060. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15061. return this.myroomjid;
  15062. }
  15063. var peerJid = null;
  15064. Object.keys(this.members).some(function (jid) {
  15065. peerJid = jid;
  15066. return Strophe.getResourceFromJid(jid) === resourceJid;
  15067. });
  15068. return peerJid;
  15069. },
  15070. addBridgeIsDownToPresence: function () {
  15071. this.presMap['bridgeIsDown'] = true;
  15072. },
  15073. addEmailToPresence: function (email) {
  15074. this.presMap['email'] = email;
  15075. },
  15076. addUserIdToPresence: function (userId) {
  15077. this.presMap['userId'] = userId;
  15078. },
  15079. addStartMutedToPresence: function (audio, video) {
  15080. this.presMap["startMuted"] = {audio: audio, video: video};
  15081. },
  15082. isModerator: function () {
  15083. return this.role === 'moderator';
  15084. },
  15085. getMemberRole: function (peerJid) {
  15086. if (this.members[peerJid]) {
  15087. return this.members[peerJid].role;
  15088. }
  15089. return null;
  15090. },
  15091. onParticipantLeft: function (jid) {
  15092. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15093. this.connection.jingle.terminateByJid(jid);
  15094. if (this.getPrezi(jid)) {
  15095. $(document).trigger('presentationremoved.muc',
  15096. [jid, this.getPrezi(jid)]);
  15097. }
  15098. Moderator.onMucMemberLeft(jid);
  15099. },
  15100. parsePresence: function (from, memeber, pres) {
  15101. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  15102. bridgeIsDown = true;
  15103. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15104. }
  15105. if(memeber.isFocus)
  15106. return;
  15107. var displayName = !config.displayJids
  15108. ? memeber.displayName : Strophe.getResourceFromJid(from);
  15109. if (displayName && displayName.length > 0)
  15110. {
  15111. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15112. }
  15113. var id = $(pres).find('>userID').text();
  15114. var email = $(pres).find('>email');
  15115. if(email.length > 0) {
  15116. id = email.text();
  15117. }
  15118. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15119. }
  15120. });
  15121. };
  15122. },{"../../service/xmpp/XMPPEvents":112,"./JingleSession":53,"./moderator":58}],61:[function(require,module,exports){
  15123. /* jshint -W117 */
  15124. var JingleSession = require("./JingleSession");
  15125. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15126. module.exports = function(XMPP, eventEmitter)
  15127. {
  15128. function CallIncomingJingle(sid, connection) {
  15129. var sess = connection.jingle.sessions[sid];
  15130. // TODO: do we check activecall == null?
  15131. connection.jingle.activecall = sess;
  15132. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15133. // TODO: check affiliation and/or role
  15134. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15135. sess.usedrip = true; // not-so-naive trickle ice
  15136. sess.sendAnswer();
  15137. sess.accept();
  15138. };
  15139. Strophe.addConnectionPlugin('jingle', {
  15140. connection: null,
  15141. sessions: {},
  15142. jid2session: {},
  15143. ice_config: {iceServers: []},
  15144. pc_constraints: {},
  15145. activecall: null,
  15146. media_constraints: {
  15147. mandatory: {
  15148. 'OfferToReceiveAudio': true,
  15149. 'OfferToReceiveVideo': true
  15150. }
  15151. // MozDontOfferDataChannel: true when this is firefox
  15152. },
  15153. init: function (conn) {
  15154. this.connection = conn;
  15155. if (this.connection.disco) {
  15156. // http://xmpp.org/extensions/xep-0167.html#support
  15157. // http://xmpp.org/extensions/xep-0176.html#support
  15158. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15159. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15160. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15161. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15162. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15163. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15164. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15165. // this is dealt with by SDP O/A so we don't need to annouce this
  15166. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15167. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15168. if (config.useRtcpMux) {
  15169. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15170. }
  15171. if (config.useBundle) {
  15172. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15173. }
  15174. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15175. }
  15176. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15177. },
  15178. onJingle: function (iq) {
  15179. var sid = $(iq).find('jingle').attr('sid');
  15180. var action = $(iq).find('jingle').attr('action');
  15181. var fromJid = iq.getAttribute('from');
  15182. // send ack first
  15183. var ack = $iq({type: 'result',
  15184. to: fromJid,
  15185. id: iq.getAttribute('id')
  15186. });
  15187. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15188. var sess = this.sessions[sid];
  15189. if ('session-initiate' != action) {
  15190. if (sess === null) {
  15191. ack.type = 'error';
  15192. ack.c('error', {type: 'cancel'})
  15193. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15194. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15195. this.connection.send(ack);
  15196. return true;
  15197. }
  15198. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  15199. // local jid is not checked
  15200. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  15201. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15202. ack.type = 'error';
  15203. ack.c('error', {type: 'cancel'})
  15204. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15205. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15206. this.connection.send(ack);
  15207. return true;
  15208. }
  15209. } else if (sess !== undefined) {
  15210. // existing session with same session id
  15211. // this might be out-of-order if the sess.peerjid is the same as from
  15212. ack.type = 'error';
  15213. ack.c('error', {type: 'cancel'})
  15214. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15215. console.warn('duplicate session id', sid);
  15216. this.connection.send(ack);
  15217. return true;
  15218. }
  15219. // FIXME: check for a defined action
  15220. this.connection.send(ack);
  15221. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15222. switch (action) {
  15223. case 'session-initiate':
  15224. var startMuted = $(iq).find('jingle>startmuted');
  15225. if(startMuted && startMuted.length > 0)
  15226. {
  15227. var audioMuted = startMuted.attr("audio");
  15228. var videoMuted = startMuted.attr("video");
  15229. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  15230. (videoMuted === "true"));
  15231. }
  15232. sess = new JingleSession(
  15233. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15234. this.connection, XMPP, eventEmitter);
  15235. // configure session
  15236. sess.media_constraints = this.media_constraints;
  15237. sess.pc_constraints = this.pc_constraints;
  15238. sess.ice_config = this.ice_config;
  15239. sess.initiate(fromJid, false);
  15240. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15241. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15242. this.sessions[sess.sid] = sess;
  15243. this.jid2session[sess.peerjid] = sess;
  15244. // the callback should either
  15245. // .sendAnswer and .accept
  15246. // or .sendTerminate -- not necessarily synchronus
  15247. CallIncomingJingle(sess.sid, this.connection);
  15248. break;
  15249. case 'session-accept':
  15250. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15251. sess.accept();
  15252. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15253. break;
  15254. case 'session-terminate':
  15255. // If this is not the focus sending the terminate, we have
  15256. // nothing more to do here.
  15257. if (Object.keys(this.sessions).length < 1
  15258. || !(this.sessions[Object.keys(this.sessions)[0]]
  15259. instanceof JingleSession))
  15260. {
  15261. break;
  15262. }
  15263. console.log('terminating...', sess.sid);
  15264. sess.terminate();
  15265. this.terminate(sess.sid);
  15266. if ($(iq).find('>jingle>reason').length) {
  15267. $(document).trigger('callterminated.jingle', [
  15268. sess.sid,
  15269. sess.peerjid,
  15270. $(iq).find('>jingle>reason>:first')[0].tagName,
  15271. $(iq).find('>jingle>reason>text').text()
  15272. ]);
  15273. } else {
  15274. $(document).trigger('callterminated.jingle',
  15275. [sess.sid, sess.peerjid]);
  15276. }
  15277. break;
  15278. case 'transport-info':
  15279. sess.addIceCandidate($(iq).find('>jingle>content'));
  15280. break;
  15281. case 'session-info':
  15282. var affected;
  15283. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15284. $(document).trigger('ringing.jingle', [sess.sid]);
  15285. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15286. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15287. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15288. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15289. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15290. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15291. }
  15292. break;
  15293. case 'addsource': // FIXME: proprietary, un-jingleish
  15294. case 'source-add': // FIXME: proprietary
  15295. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15296. break;
  15297. case 'removesource': // FIXME: proprietary, un-jingleish
  15298. case 'source-remove': // FIXME: proprietary
  15299. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15300. break;
  15301. default:
  15302. console.warn('jingle action not implemented', action);
  15303. break;
  15304. }
  15305. return true;
  15306. },
  15307. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15308. var sess = new JingleSession(myjid || this.connection.jid,
  15309. Math.random().toString(36).substr(2, 12), // random string
  15310. this.connection, XMPP, eventEmitter);
  15311. // configure session
  15312. sess.media_constraints = this.media_constraints;
  15313. sess.pc_constraints = this.pc_constraints;
  15314. sess.ice_config = this.ice_config;
  15315. sess.initiate(peerjid, true);
  15316. this.sessions[sess.sid] = sess;
  15317. this.jid2session[sess.peerjid] = sess;
  15318. sess.sendOffer();
  15319. return sess;
  15320. },
  15321. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15322. if (sid === null || sid === undefined) {
  15323. for (sid in this.sessions) {
  15324. if (this.sessions[sid].state != 'ended') {
  15325. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15326. this.sessions[sid].terminate();
  15327. }
  15328. delete this.jid2session[this.sessions[sid].peerjid];
  15329. delete this.sessions[sid];
  15330. }
  15331. } else if (this.sessions.hasOwnProperty(sid)) {
  15332. if (this.sessions[sid].state != 'ended') {
  15333. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15334. this.sessions[sid].terminate();
  15335. }
  15336. delete this.jid2session[this.sessions[sid].peerjid];
  15337. delete this.sessions[sid];
  15338. }
  15339. },
  15340. // Used to terminate a session when an unavailable presence is received.
  15341. terminateByJid: function (jid) {
  15342. if (this.jid2session.hasOwnProperty(jid)) {
  15343. var sess = this.jid2session[jid];
  15344. if (sess) {
  15345. sess.terminate();
  15346. console.log('peer went away silently', jid);
  15347. delete this.sessions[sess.sid];
  15348. delete this.jid2session[jid];
  15349. $(document).trigger('callterminated.jingle',
  15350. [sess.sid, jid], 'gone');
  15351. }
  15352. }
  15353. },
  15354. terminateRemoteByJid: function (jid, reason) {
  15355. if (this.jid2session.hasOwnProperty(jid)) {
  15356. var sess = this.jid2session[jid];
  15357. if (sess) {
  15358. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15359. sess.terminate();
  15360. console.log('terminate peer with jid', sess.sid, jid);
  15361. delete this.sessions[sess.sid];
  15362. delete this.jid2session[jid];
  15363. $(document).trigger('callterminated.jingle',
  15364. [sess.sid, jid, 'kicked']);
  15365. }
  15366. }
  15367. },
  15368. getStunAndTurnCredentials: function () {
  15369. // get stun and turn configuration from server via xep-0215
  15370. // uses time-limited credentials as described in
  15371. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15372. //
  15373. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15374. // for a prosody module which implements this
  15375. //
  15376. // currently, this doesn't work with updateIce and therefore credentials with a long
  15377. // validity have to be fetched before creating the peerconnection
  15378. // TODO: implement refresh via updateIce as described in
  15379. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15380. var self = this;
  15381. this.connection.sendIQ(
  15382. $iq({type: 'get', to: this.connection.domain})
  15383. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15384. function (res) {
  15385. var iceservers = [];
  15386. $(res).find('>services>service').each(function (idx, el) {
  15387. el = $(el);
  15388. var dict = {};
  15389. var type = el.attr('type');
  15390. switch (type) {
  15391. case 'stun':
  15392. dict.url = 'stun:' + el.attr('host');
  15393. if (el.attr('port')) {
  15394. dict.url += ':' + el.attr('port');
  15395. }
  15396. iceservers.push(dict);
  15397. break;
  15398. case 'turn':
  15399. case 'turns':
  15400. dict.url = type + ':';
  15401. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15402. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15403. dict.url += el.attr('username') + '@';
  15404. } else {
  15405. dict.username = el.attr('username'); // only works in M28
  15406. }
  15407. }
  15408. dict.url += el.attr('host');
  15409. if (el.attr('port') && el.attr('port') != '3478') {
  15410. dict.url += ':' + el.attr('port');
  15411. }
  15412. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15413. dict.url += '?transport=' + el.attr('transport');
  15414. }
  15415. if (el.attr('password')) {
  15416. dict.credential = el.attr('password');
  15417. }
  15418. iceservers.push(dict);
  15419. break;
  15420. }
  15421. });
  15422. self.ice_config.iceServers = iceservers;
  15423. },
  15424. function (err) {
  15425. console.warn('getting turn credentials failed', err);
  15426. console.warn('is mod_turncredentials or similar installed?');
  15427. }
  15428. );
  15429. // implement push?
  15430. },
  15431. /**
  15432. * Populates the log data
  15433. */
  15434. populateData: function () {
  15435. var data = {};
  15436. var self = this;
  15437. Object.keys(this.sessions).forEach(function (sid) {
  15438. var session = self.sessions[sid];
  15439. if (session.peerconnection && session.peerconnection.updateLog) {
  15440. // FIXME: should probably be a .dump call
  15441. data["jingle_" + session.sid] = {
  15442. updateLog: session.peerconnection.updateLog,
  15443. stats: session.peerconnection.stats,
  15444. url: window.location.href
  15445. };
  15446. }
  15447. });
  15448. return data;
  15449. }
  15450. });
  15451. };
  15452. },{"../../service/xmpp/XMPPEvents":112,"./JingleSession":53}],62:[function(require,module,exports){
  15453. /* global Strophe */
  15454. module.exports = function () {
  15455. Strophe.addConnectionPlugin('logger', {
  15456. // logs raw stanzas and makes them available for download as JSON
  15457. connection: null,
  15458. log: [],
  15459. init: function (conn) {
  15460. this.connection = conn;
  15461. this.connection.rawInput = this.log_incoming.bind(this);
  15462. this.connection.rawOutput = this.log_outgoing.bind(this);
  15463. },
  15464. log_incoming: function (stanza) {
  15465. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15466. },
  15467. log_outgoing: function (stanza) {
  15468. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15469. }
  15470. });
  15471. };
  15472. },{}],63:[function(require,module,exports){
  15473. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15474. setAudioMuted, Strophe */
  15475. /**
  15476. * Moderate connection plugin.
  15477. */
  15478. module.exports = function (XMPP) {
  15479. Strophe.addConnectionPlugin('moderate', {
  15480. connection: null,
  15481. init: function (conn) {
  15482. this.connection = conn;
  15483. this.connection.addHandler(this.onMute.bind(this),
  15484. 'http://jitsi.org/jitmeet/audio',
  15485. 'iq',
  15486. 'set',
  15487. null,
  15488. null);
  15489. },
  15490. setMute: function (jid, mute) {
  15491. console.info("set mute", mute);
  15492. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15493. .c('mute', {
  15494. xmlns: 'http://jitsi.org/jitmeet/audio',
  15495. jid: jid
  15496. })
  15497. .t(mute.toString())
  15498. .up();
  15499. this.connection.sendIQ(
  15500. iqToFocus,
  15501. function (result) {
  15502. console.log('set mute', result);
  15503. },
  15504. function (error) {
  15505. console.log('set mute error', error);
  15506. });
  15507. },
  15508. onMute: function (iq) {
  15509. var from = iq.getAttribute('from');
  15510. if (from !== this.connection.emuc.focusMucJid) {
  15511. console.warn("Ignored mute from non focus peer");
  15512. return false;
  15513. }
  15514. var mute = $(iq).find('mute');
  15515. if (mute.length) {
  15516. var doMuteAudio = mute.text() === "true";
  15517. APP.UI.setAudioMuted(doMuteAudio);
  15518. XMPP.forceMuted = doMuteAudio;
  15519. }
  15520. return true;
  15521. },
  15522. eject: function (jid) {
  15523. // We're not the focus, so can't terminate
  15524. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15525. this.connection.emuc.kick(jid);
  15526. }
  15527. });
  15528. }
  15529. },{}],64:[function(require,module,exports){
  15530. /* jshint -W117 */
  15531. module.exports = function() {
  15532. Strophe.addConnectionPlugin('rayo',
  15533. {
  15534. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15535. connection: null,
  15536. init: function (conn) {
  15537. this.connection = conn;
  15538. if (this.connection.disco) {
  15539. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15540. }
  15541. this.connection.addHandler(
  15542. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15543. },
  15544. onRayo: function (iq) {
  15545. console.info("Rayo IQ", iq);
  15546. },
  15547. dial: function (to, from, roomName, roomPass) {
  15548. var self = this;
  15549. var req = $iq(
  15550. {
  15551. type: 'set',
  15552. to: this.connection.emuc.focusMucJid
  15553. }
  15554. );
  15555. req.c('dial',
  15556. {
  15557. xmlns: this.RAYO_XMLNS,
  15558. to: to,
  15559. from: from
  15560. });
  15561. req.c('header',
  15562. {
  15563. name: 'JvbRoomName',
  15564. value: roomName
  15565. }).up();
  15566. if (roomPass !== null && roomPass.length) {
  15567. req.c('header',
  15568. {
  15569. name: 'JvbRoomPassword',
  15570. value: roomPass
  15571. }).up();
  15572. }
  15573. this.connection.sendIQ(
  15574. req,
  15575. function (result) {
  15576. console.info('Dial result ', result);
  15577. var resource = $(result).find('ref').attr('uri');
  15578. this.call_resource = resource.substr('xmpp:'.length);
  15579. console.info(
  15580. "Received call resource: " + this.call_resource);
  15581. },
  15582. function (error) {
  15583. console.info('Dial error ', error);
  15584. }
  15585. );
  15586. },
  15587. hang_up: function () {
  15588. if (!this.call_resource) {
  15589. console.warn("No call in progress");
  15590. return;
  15591. }
  15592. var self = this;
  15593. var req = $iq(
  15594. {
  15595. type: 'set',
  15596. to: this.call_resource
  15597. }
  15598. );
  15599. req.c('hangup',
  15600. {
  15601. xmlns: this.RAYO_XMLNS
  15602. });
  15603. this.connection.sendIQ(
  15604. req,
  15605. function (result) {
  15606. console.info('Hangup result ', result);
  15607. self.call_resource = null;
  15608. },
  15609. function (error) {
  15610. console.info('Hangup error ', error);
  15611. self.call_resource = null;
  15612. }
  15613. );
  15614. }
  15615. }
  15616. );
  15617. };
  15618. },{}],65:[function(require,module,exports){
  15619. /**
  15620. * Strophe logger implementation. Logs from level WARN and above.
  15621. */
  15622. module.exports = function () {
  15623. Strophe.log = function (level, msg) {
  15624. switch (level) {
  15625. case Strophe.LogLevel.WARN:
  15626. console.warn("Strophe: " + msg);
  15627. break;
  15628. case Strophe.LogLevel.ERROR:
  15629. case Strophe.LogLevel.FATAL:
  15630. console.error("Strophe: " + msg);
  15631. break;
  15632. }
  15633. };
  15634. Strophe.getStatusString = function (status) {
  15635. switch (status) {
  15636. case Strophe.Status.ERROR:
  15637. return "ERROR";
  15638. case Strophe.Status.CONNECTING:
  15639. return "CONNECTING";
  15640. case Strophe.Status.CONNFAIL:
  15641. return "CONNFAIL";
  15642. case Strophe.Status.AUTHENTICATING:
  15643. return "AUTHENTICATING";
  15644. case Strophe.Status.AUTHFAIL:
  15645. return "AUTHFAIL";
  15646. case Strophe.Status.CONNECTED:
  15647. return "CONNECTED";
  15648. case Strophe.Status.DISCONNECTED:
  15649. return "DISCONNECTED";
  15650. case Strophe.Status.DISCONNECTING:
  15651. return "DISCONNECTING";
  15652. case Strophe.Status.ATTACHED:
  15653. return "ATTACHED";
  15654. default:
  15655. return "unknown";
  15656. }
  15657. };
  15658. };
  15659. },{}],66:[function(require,module,exports){
  15660. /* global $, APP, config, Strophe*/
  15661. var Moderator = require("./moderator");
  15662. var EventEmitter = require("events");
  15663. var Recording = require("./recording");
  15664. var SDP = require("./SDP");
  15665. var Settings = require("../settings/Settings");
  15666. var Pako = require("pako");
  15667. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  15668. var RTCEvents = require("../../service/RTC/RTCEvents");
  15669. var UIEvents = require("../../service/UI/UIEvents");
  15670. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15671. var retry = require('retry');
  15672. var eventEmitter = new EventEmitter();
  15673. var connection = null;
  15674. var authenticatedUser = false;
  15675. function connect(jid, password) {
  15676. var faultTolerantConnect = retry.operation({
  15677. retries: 3
  15678. });
  15679. // fault tolerant connect
  15680. faultTolerantConnect.attempt(function () {
  15681. connection = XMPP.createConnection();
  15682. Moderator.setConnection(connection);
  15683. if (connection.disco) {
  15684. // for chrome, add multistream cap
  15685. }
  15686. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  15687. if (config.useIPv6) {
  15688. // https://code.google.com/p/webrtc/issues/detail?id=2828
  15689. if (!connection.jingle.pc_constraints.optional)
  15690. connection.jingle.pc_constraints.optional = [];
  15691. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  15692. }
  15693. // Include user info in MUC presence
  15694. var settings = Settings.getSettings();
  15695. if (settings.email) {
  15696. connection.emuc.addEmailToPresence(settings.email);
  15697. }
  15698. if (settings.uid) {
  15699. connection.emuc.addUserIdToPresence(settings.uid);
  15700. }
  15701. if (settings.displayName) {
  15702. connection.emuc.addDisplayNameToPresence(settings.displayName);
  15703. }
  15704. // connection.connect() starts the connection process.
  15705. //
  15706. // As the connection process proceeds, the user supplied callback will
  15707. // be triggered multiple times with status updates. The callback should
  15708. // take two arguments - the status code and the error condition.
  15709. //
  15710. // The status code will be one of the values in the Strophe.Status
  15711. // constants. The error condition will be one of the conditions defined
  15712. // in RFC 3920 or the condition ‘strophe-parsererror’.
  15713. //
  15714. // The Parameters wait, hold and route are optional and only relevant
  15715. // for BOSH connections. Please see XEP 124 for a more detailed
  15716. // explanation of the optional parameters.
  15717. //
  15718. // Connection status constants for use by the connection handler
  15719. // callback.
  15720. //
  15721. // Status.ERROR - An error has occurred (websockets specific)
  15722. // Status.CONNECTING - The connection is currently being made
  15723. // Status.CONNFAIL - The connection attempt failed
  15724. // Status.AUTHENTICATING - The connection is authenticating
  15725. // Status.AUTHFAIL - The authentication attempt failed
  15726. // Status.CONNECTED - The connection has succeeded
  15727. // Status.DISCONNECTED - The connection has been terminated
  15728. // Status.DISCONNECTING - The connection is currently being terminated
  15729. // Status.ATTACHED - The connection has been attached
  15730. var anonymousConnectionFailed = false;
  15731. var connectionFailed = false;
  15732. var lastErrorMsg;
  15733. connection.connect(jid, password, function (status, msg) {
  15734. console.log('Strophe status changed to',
  15735. Strophe.getStatusString(status), msg);
  15736. if (status === Strophe.Status.CONNECTED) {
  15737. if (config.useStunTurn) {
  15738. connection.jingle.getStunAndTurnCredentials();
  15739. }
  15740. console.info("My Jabber ID: " + connection.jid);
  15741. if (password)
  15742. authenticatedUser = true;
  15743. maybeDoJoin();
  15744. } else if (status === Strophe.Status.CONNFAIL) {
  15745. if (msg === 'x-strophe-bad-non-anon-jid') {
  15746. anonymousConnectionFailed = true;
  15747. } else {
  15748. connectionFailed = true;
  15749. }
  15750. lastErrorMsg = msg;
  15751. } else if (status === Strophe.Status.DISCONNECTED) {
  15752. if (anonymousConnectionFailed) {
  15753. // prompt user for username and password
  15754. XMPP.promptLogin();
  15755. } else {
  15756. // Strophe already has built-in HTTP/BOSH error handling and
  15757. // request retry logic. Requests are resent automatically
  15758. // until their error count reaches 5. Strophe.js disconnects
  15759. // if the error count is > 5. We are not replicating this
  15760. // here.
  15761. //
  15762. // The "problem" is that failed HTTP/BOSH requests don't
  15763. // trigger a callback with a status update, so when a
  15764. // callback with status Strophe.Status.DISCONNECTED arrives,
  15765. // we can't be sure if it's a graceful disconnect or if it's
  15766. // triggered by some HTTP/BOSH error.
  15767. //
  15768. // But that's a minor issue in Jitsi Meet as we never
  15769. // disconnect anyway, not even when the user closes the
  15770. // browser window (which is kind of wrong, but the point is
  15771. // that we should never ever get disconnected).
  15772. //
  15773. // On the other hand, failed connections due to XMPP layer
  15774. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  15775. //
  15776. // Here we implement retry logic for failed connections due
  15777. // to XMPP layer errors and we display an error to the user
  15778. // if we get disconnected from the XMPP server permanently.
  15779. // If the connection failed, retry.
  15780. if (connectionFailed
  15781. && faultTolerantConnect.retry("connection-failed")) {
  15782. return;
  15783. }
  15784. // If we failed to connect to the XMPP server, fire an event
  15785. // to let all the interested module now about it.
  15786. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  15787. msg ? msg : lastErrorMsg);
  15788. }
  15789. } else if (status === Strophe.Status.AUTHFAIL) {
  15790. // wrong password or username, prompt user
  15791. XMPP.promptLogin();
  15792. }
  15793. });
  15794. });
  15795. }
  15796. function maybeDoJoin() {
  15797. if (connection && connection.connected &&
  15798. Strophe.getResourceFromJid(connection.jid)
  15799. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15800. // .connected is true while connecting?
  15801. doJoin();
  15802. }
  15803. }
  15804. function doJoin() {
  15805. var roomName = APP.UI.generateRoomName();
  15806. Moderator.allocateConferenceFocus(
  15807. roomName, APP.UI.checkForNicknameAndJoin);
  15808. }
  15809. function initStrophePlugins()
  15810. {
  15811. require("./strophe.emuc")(XMPP, eventEmitter);
  15812. require("./strophe.jingle")(XMPP, eventEmitter);
  15813. require("./strophe.moderate")(XMPP);
  15814. require("./strophe.util")();
  15815. require("./strophe.rayo")();
  15816. require("./strophe.logger")();
  15817. }
  15818. function registerListeners() {
  15819. APP.RTC.addStreamListener(maybeDoJoin,
  15820. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  15821. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  15822. XMPP.addToPresence("devices", devices);
  15823. })
  15824. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  15825. XMPP.addToPresence("displayName", nickname);
  15826. });
  15827. }
  15828. var unload = (function () {
  15829. var unloaded = false;
  15830. return function () {
  15831. if (unloaded) { return; }
  15832. unloaded = true;
  15833. if (connection && connection.connected) {
  15834. // ensure signout
  15835. $.ajax({
  15836. type: 'POST',
  15837. url: config.bosh,
  15838. async: false,
  15839. cache: false,
  15840. contentType: 'application/xml',
  15841. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  15842. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  15843. (connection.sid || connection._proto.sid) +
  15844. "' type='terminate'>" +
  15845. "<presence xmlns='jabber:client' type='unavailable'/>" +
  15846. "</body>",
  15847. success: function (data) {
  15848. console.log('signed out');
  15849. console.log(data);
  15850. },
  15851. error: function (XMLHttpRequest, textStatus, errorThrown) {
  15852. console.log('signout error',
  15853. textStatus + ' (' + errorThrown + ')');
  15854. }
  15855. });
  15856. }
  15857. XMPP.disposeConference(true);
  15858. };
  15859. })();
  15860. function setupEvents() {
  15861. // In recent versions of FF the 'beforeunload' event is not fired when the
  15862. // window or the tab is closed. It is only fired when we leave the page
  15863. // (change URL). If this participant doesn't unload properly, then it
  15864. // becomes a ghost for the rest of the participants that stay in the
  15865. // conference. Thankfully handling the 'unload' event in addition to the
  15866. // 'beforeunload' event seems to garante the execution of the 'unload'
  15867. // method at least once.
  15868. //
  15869. // The 'unload' method can safely be run multiple times, it will actually do
  15870. // something only the first time that it's run, so we're don't have to worry
  15871. // about browsers that fire both events.
  15872. $(window).bind('beforeunload', unload);
  15873. $(window).bind('unload', unload);
  15874. }
  15875. var XMPP = {
  15876. getConnection: function(){ return connection; },
  15877. sessionTerminated: false,
  15878. /**
  15879. * XMPP connection status
  15880. */
  15881. Status: Strophe.Status,
  15882. /**
  15883. * Remembers if we were muted by the focus.
  15884. * @type {boolean}
  15885. */
  15886. forceMuted: false,
  15887. start: function () {
  15888. setupEvents();
  15889. initStrophePlugins();
  15890. registerListeners();
  15891. Moderator.init(this, eventEmitter);
  15892. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  15893. // Force authenticated domain if room is appended with '?login=true'
  15894. if (config.hosts.anonymousdomain &&
  15895. window.location.search.indexOf("login=true") !== -1) {
  15896. configDomain = config.hosts.domain;
  15897. }
  15898. var jid = configDomain || window.location.hostname;
  15899. connect(jid, null);
  15900. },
  15901. createConnection: function () {
  15902. var bosh = config.bosh || '/http-bind';
  15903. return new Strophe.Connection(bosh);
  15904. },
  15905. getStatusString: function (status) {
  15906. return Strophe.getStatusString(status);
  15907. },
  15908. promptLogin: function () {
  15909. // FIXME: re-use LoginDialog which supports retries
  15910. APP.UI.showLoginPopup(connect);
  15911. },
  15912. joinRoom: function(roomName, useNicks, nick)
  15913. {
  15914. var roomjid;
  15915. roomjid = roomName;
  15916. if (useNicks) {
  15917. if (nick) {
  15918. roomjid += '/' + nick;
  15919. } else {
  15920. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  15921. }
  15922. } else {
  15923. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  15924. if(!authenticatedUser)
  15925. tmpJid = tmpJid.substr(0, 8);
  15926. roomjid += '/' + tmpJid;
  15927. }
  15928. connection.emuc.doJoin(roomjid);
  15929. },
  15930. myJid: function () {
  15931. if(!connection)
  15932. return null;
  15933. return connection.emuc.myroomjid;
  15934. },
  15935. myResource: function () {
  15936. if(!connection || ! connection.emuc.myroomjid)
  15937. return null;
  15938. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  15939. },
  15940. disposeConference: function (onUnload) {
  15941. var handler = connection.jingle.activecall;
  15942. if (handler && handler.peerconnection) {
  15943. // FIXME: probably removing streams is not required and close() should
  15944. // be enough
  15945. if (APP.RTC.localAudio) {
  15946. handler.peerconnection.removeStream(
  15947. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15948. }
  15949. if (APP.RTC.localVideo) {
  15950. handler.peerconnection.removeStream(
  15951. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15952. }
  15953. handler.peerconnection.close();
  15954. }
  15955. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  15956. connection.jingle.activecall = null;
  15957. if(!onUnload)
  15958. {
  15959. this.sessionTerminated = true;
  15960. connection.emuc.doLeave();
  15961. }
  15962. },
  15963. addListener: function(type, listener)
  15964. {
  15965. eventEmitter.on(type, listener);
  15966. },
  15967. removeListener: function (type, listener) {
  15968. eventEmitter.removeListener(type, listener);
  15969. },
  15970. allocateConferenceFocus: function(roomName, callback) {
  15971. Moderator.allocateConferenceFocus(roomName, callback);
  15972. },
  15973. getLoginUrl: function (roomName, callback) {
  15974. Moderator.getLoginUrl(roomName, callback);
  15975. },
  15976. getPopupLoginUrl: function (roomName, callback) {
  15977. Moderator.getPopupLoginUrl(roomName, callback);
  15978. },
  15979. isModerator: function () {
  15980. return Moderator.isModerator();
  15981. },
  15982. isSipGatewayEnabled: function () {
  15983. return Moderator.isSipGatewayEnabled();
  15984. },
  15985. isExternalAuthEnabled: function () {
  15986. return Moderator.isExternalAuthEnabled();
  15987. },
  15988. isConferenceInProgress: function () {
  15989. return connection && connection.jingle.activecall &&
  15990. connection.jingle.activecall.peerconnection;
  15991. },
  15992. switchStreams: function (stream, oldStream, callback, isAudio) {
  15993. if (this.isConferenceInProgress()) {
  15994. // FIXME: will block switchInProgress on true value in case of exception
  15995. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  15996. } else {
  15997. // We are done immediately
  15998. console.warn("No conference handler or conference not started yet");
  15999. callback();
  16000. }
  16001. },
  16002. sendVideoInfoPresence: function (mute) {
  16003. if(!connection)
  16004. return;
  16005. connection.emuc.addVideoInfoToPresence(mute);
  16006. connection.emuc.sendPresence();
  16007. },
  16008. setVideoMute: function (mute, callback, options) {
  16009. if(!connection)
  16010. return;
  16011. var self = this;
  16012. var localCallback = function (mute) {
  16013. self.sendVideoInfoPresence(mute);
  16014. return callback(mute);
  16015. };
  16016. if(connection.jingle.activecall)
  16017. {
  16018. connection.jingle.activecall.setVideoMute(
  16019. mute, localCallback, options);
  16020. }
  16021. else {
  16022. localCallback(mute);
  16023. }
  16024. },
  16025. setAudioMute: function (mute, callback) {
  16026. if (!(connection && APP.RTC.localAudio)) {
  16027. return false;
  16028. }
  16029. if (this.forceMuted && !mute) {
  16030. console.info("Asking focus for unmute");
  16031. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16032. // FIXME: wait for result before resetting muted status
  16033. this.forceMuted = false;
  16034. }
  16035. if (mute == APP.RTC.localAudio.isMuted()) {
  16036. // Nothing to do
  16037. return true;
  16038. }
  16039. // It is not clear what is the right way to handle multiple tracks.
  16040. // So at least make sure that they are all muted or all unmuted and
  16041. // that we send presence just once.
  16042. APP.RTC.localAudio.setMute(!mute);
  16043. // isMuted is the opposite of audioEnabled
  16044. this.sendAudioInfoPresence(mute, callback);
  16045. return true;
  16046. },
  16047. sendAudioInfoPresence: function(mute, callback)
  16048. {
  16049. if(connection) {
  16050. connection.emuc.addAudioInfoToPresence(mute);
  16051. connection.emuc.sendPresence();
  16052. }
  16053. callback();
  16054. return true;
  16055. },
  16056. // Really mute video, i.e. dont even send black frames
  16057. muteVideo: function (pc, unmute) {
  16058. // FIXME: this probably needs another of those lovely state safeguards...
  16059. // which checks for iceconn == connected and sigstate == stable
  16060. pc.setRemoteDescription(pc.remoteDescription,
  16061. function () {
  16062. pc.createAnswer(
  16063. function (answer) {
  16064. var sdp = new SDP(answer.sdp);
  16065. if (sdp.media.length > 1) {
  16066. if (unmute)
  16067. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  16068. else
  16069. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  16070. sdp.raw = sdp.session + sdp.media.join('');
  16071. answer.sdp = sdp.raw;
  16072. }
  16073. pc.setLocalDescription(answer,
  16074. function () {
  16075. console.log('mute SLD ok');
  16076. },
  16077. function (error) {
  16078. console.log('mute SLD error');
  16079. APP.UI.messageHandler.showError("dialog.error",
  16080. "dialog.SLDFailure");
  16081. }
  16082. );
  16083. },
  16084. function (error) {
  16085. console.log(error);
  16086. APP.UI.messageHandler.showError();
  16087. }
  16088. );
  16089. },
  16090. function (error) {
  16091. console.log('muteVideo SRD error');
  16092. APP.UI.messageHandler.showError("dialog.error",
  16093. "dialog.SRDFailure");
  16094. }
  16095. );
  16096. },
  16097. toggleRecording: function (tokenEmptyCallback,
  16098. startingCallback, startedCallback) {
  16099. Recording.toggleRecording(tokenEmptyCallback,
  16100. startingCallback, startedCallback, connection);
  16101. },
  16102. addToPresence: function (name, value, dontSend) {
  16103. switch (name)
  16104. {
  16105. case "displayName":
  16106. connection.emuc.addDisplayNameToPresence(value);
  16107. break;
  16108. case "prezi":
  16109. connection.emuc.addPreziToPresence(value, 0);
  16110. break;
  16111. case "preziSlide":
  16112. connection.emuc.addCurrentSlideToPresence(value);
  16113. break;
  16114. case "connectionQuality":
  16115. connection.emuc.addConnectionInfoToPresence(value);
  16116. break;
  16117. case "email":
  16118. connection.emuc.addEmailToPresence(value);
  16119. break;
  16120. case "devices":
  16121. connection.emuc.addDevicesToPresence(value);
  16122. break;
  16123. case "startMuted":
  16124. if(!Moderator.isModerator())
  16125. return;
  16126. connection.emuc.addStartMutedToPresence(value[0],
  16127. value[1]);
  16128. break;
  16129. default :
  16130. console.log("Unknown tag for presence: " + name);
  16131. return;
  16132. }
  16133. if (!dontSend)
  16134. connection.emuc.sendPresence();
  16135. },
  16136. /**
  16137. * Sends 'data' as a log message to the focus. Returns true iff a message
  16138. * was sent.
  16139. * @param data
  16140. * @returns {boolean} true iff a message was sent.
  16141. */
  16142. sendLogs: function (data) {
  16143. if(!connection.emuc.focusMucJid)
  16144. return false;
  16145. var deflate = true;
  16146. var content = JSON.stringify(data);
  16147. if (deflate) {
  16148. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16149. }
  16150. content = Base64.encode(content);
  16151. // XEP-0337-ish
  16152. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16153. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16154. id: 'PeerConnectionStats'});
  16155. message.c('message').t(content).up();
  16156. if (deflate) {
  16157. message.c('tag', {name: "deflated", value: "true"}).up();
  16158. }
  16159. message.up();
  16160. connection.send(message);
  16161. return true;
  16162. },
  16163. populateData: function () {
  16164. var data = {};
  16165. if (connection.jingle) {
  16166. data = connection.jingle.populateData();
  16167. }
  16168. return data;
  16169. },
  16170. getLogger: function () {
  16171. if(connection.logger)
  16172. return connection.logger.log;
  16173. return null;
  16174. },
  16175. getPrezi: function () {
  16176. return connection.emuc.getPrezi(this.myJid());
  16177. },
  16178. removePreziFromPresence: function () {
  16179. connection.emuc.removePreziFromPresence();
  16180. connection.emuc.sendPresence();
  16181. },
  16182. sendChatMessage: function (message, nickname) {
  16183. connection.emuc.sendMessage(message, nickname);
  16184. },
  16185. setSubject: function (topic) {
  16186. connection.emuc.setSubject(topic);
  16187. },
  16188. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16189. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16190. },
  16191. dial: function (to, from, roomName,roomPass) {
  16192. connection.rayo.dial(to, from, roomName,roomPass);
  16193. },
  16194. setMute: function (jid, mute) {
  16195. connection.moderate.setMute(jid, mute);
  16196. },
  16197. eject: function (jid) {
  16198. connection.moderate.eject(jid);
  16199. },
  16200. logout: function (callback) {
  16201. Moderator.logout(callback);
  16202. },
  16203. findJidFromResource: function (resource) {
  16204. return connection.emuc.findJidFromResource(resource);
  16205. },
  16206. getMembers: function () {
  16207. return connection.emuc.members;
  16208. },
  16209. getJidFromSSRC: function (ssrc) {
  16210. if (!this.isConferenceInProgress())
  16211. return null;
  16212. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16213. },
  16214. getMUCJoined: function () {
  16215. return connection.emuc.joined;
  16216. },
  16217. getSessions: function () {
  16218. return connection.jingle.sessions;
  16219. },
  16220. removeStream: function (stream) {
  16221. if (!this.isConferenceInProgress())
  16222. return;
  16223. connection.jingle.activecall.peerconnection.removeStream(stream);
  16224. }
  16225. };
  16226. module.exports = XMPP;
  16227. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes":105,"../../service/UI/UIEvents":106,"../../service/xmpp/XMPPEvents":112,"../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":113,"pako":69,"retry":85}],67:[function(require,module,exports){
  16228. (function (process){
  16229. /*!
  16230. * async
  16231. * https://github.com/caolan/async
  16232. *
  16233. * Copyright 2010-2014 Caolan McMahon
  16234. * Released under the MIT license
  16235. */
  16236. /*jshint onevar: false, indent:4 */
  16237. /*global setImmediate: false, setTimeout: false, console: false */
  16238. (function () {
  16239. var async = {};
  16240. // global on the server, window in the browser
  16241. var root, previous_async;
  16242. root = this;
  16243. if (root != null) {
  16244. previous_async = root.async;
  16245. }
  16246. async.noConflict = function () {
  16247. root.async = previous_async;
  16248. return async;
  16249. };
  16250. function only_once(fn) {
  16251. var called = false;
  16252. return function() {
  16253. if (called) throw new Error("Callback was already called.");
  16254. called = true;
  16255. fn.apply(root, arguments);
  16256. }
  16257. }
  16258. //// cross-browser compatiblity functions ////
  16259. var _toString = Object.prototype.toString;
  16260. var _isArray = Array.isArray || function (obj) {
  16261. return _toString.call(obj) === '[object Array]';
  16262. };
  16263. var _each = function (arr, iterator) {
  16264. if (arr.forEach) {
  16265. return arr.forEach(iterator);
  16266. }
  16267. for (var i = 0; i < arr.length; i += 1) {
  16268. iterator(arr[i], i, arr);
  16269. }
  16270. };
  16271. var _map = function (arr, iterator) {
  16272. if (arr.map) {
  16273. return arr.map(iterator);
  16274. }
  16275. var results = [];
  16276. _each(arr, function (x, i, a) {
  16277. results.push(iterator(x, i, a));
  16278. });
  16279. return results;
  16280. };
  16281. var _reduce = function (arr, iterator, memo) {
  16282. if (arr.reduce) {
  16283. return arr.reduce(iterator, memo);
  16284. }
  16285. _each(arr, function (x, i, a) {
  16286. memo = iterator(memo, x, i, a);
  16287. });
  16288. return memo;
  16289. };
  16290. var _keys = function (obj) {
  16291. if (Object.keys) {
  16292. return Object.keys(obj);
  16293. }
  16294. var keys = [];
  16295. for (var k in obj) {
  16296. if (obj.hasOwnProperty(k)) {
  16297. keys.push(k);
  16298. }
  16299. }
  16300. return keys;
  16301. };
  16302. //// exported async module functions ////
  16303. //// nextTick implementation with browser-compatible fallback ////
  16304. if (typeof process === 'undefined' || !(process.nextTick)) {
  16305. if (typeof setImmediate === 'function') {
  16306. async.nextTick = function (fn) {
  16307. // not a direct alias for IE10 compatibility
  16308. setImmediate(fn);
  16309. };
  16310. async.setImmediate = async.nextTick;
  16311. }
  16312. else {
  16313. async.nextTick = function (fn) {
  16314. setTimeout(fn, 0);
  16315. };
  16316. async.setImmediate = async.nextTick;
  16317. }
  16318. }
  16319. else {
  16320. async.nextTick = process.nextTick;
  16321. if (typeof setImmediate !== 'undefined') {
  16322. async.setImmediate = function (fn) {
  16323. // not a direct alias for IE10 compatibility
  16324. setImmediate(fn);
  16325. };
  16326. }
  16327. else {
  16328. async.setImmediate = async.nextTick;
  16329. }
  16330. }
  16331. async.each = function (arr, iterator, callback) {
  16332. callback = callback || function () {};
  16333. if (!arr.length) {
  16334. return callback();
  16335. }
  16336. var completed = 0;
  16337. _each(arr, function (x) {
  16338. iterator(x, only_once(done) );
  16339. });
  16340. function done(err) {
  16341. if (err) {
  16342. callback(err);
  16343. callback = function () {};
  16344. }
  16345. else {
  16346. completed += 1;
  16347. if (completed >= arr.length) {
  16348. callback();
  16349. }
  16350. }
  16351. }
  16352. };
  16353. async.forEach = async.each;
  16354. async.eachSeries = function (arr, iterator, callback) {
  16355. callback = callback || function () {};
  16356. if (!arr.length) {
  16357. return callback();
  16358. }
  16359. var completed = 0;
  16360. var iterate = function () {
  16361. iterator(arr[completed], function (err) {
  16362. if (err) {
  16363. callback(err);
  16364. callback = function () {};
  16365. }
  16366. else {
  16367. completed += 1;
  16368. if (completed >= arr.length) {
  16369. callback();
  16370. }
  16371. else {
  16372. iterate();
  16373. }
  16374. }
  16375. });
  16376. };
  16377. iterate();
  16378. };
  16379. async.forEachSeries = async.eachSeries;
  16380. async.eachLimit = function (arr, limit, iterator, callback) {
  16381. var fn = _eachLimit(limit);
  16382. fn.apply(null, [arr, iterator, callback]);
  16383. };
  16384. async.forEachLimit = async.eachLimit;
  16385. var _eachLimit = function (limit) {
  16386. return function (arr, iterator, callback) {
  16387. callback = callback || function () {};
  16388. if (!arr.length || limit <= 0) {
  16389. return callback();
  16390. }
  16391. var completed = 0;
  16392. var started = 0;
  16393. var running = 0;
  16394. (function replenish () {
  16395. if (completed >= arr.length) {
  16396. return callback();
  16397. }
  16398. while (running < limit && started < arr.length) {
  16399. started += 1;
  16400. running += 1;
  16401. iterator(arr[started - 1], function (err) {
  16402. if (err) {
  16403. callback(err);
  16404. callback = function () {};
  16405. }
  16406. else {
  16407. completed += 1;
  16408. running -= 1;
  16409. if (completed >= arr.length) {
  16410. callback();
  16411. }
  16412. else {
  16413. replenish();
  16414. }
  16415. }
  16416. });
  16417. }
  16418. })();
  16419. };
  16420. };
  16421. var doParallel = function (fn) {
  16422. return function () {
  16423. var args = Array.prototype.slice.call(arguments);
  16424. return fn.apply(null, [async.each].concat(args));
  16425. };
  16426. };
  16427. var doParallelLimit = function(limit, fn) {
  16428. return function () {
  16429. var args = Array.prototype.slice.call(arguments);
  16430. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16431. };
  16432. };
  16433. var doSeries = function (fn) {
  16434. return function () {
  16435. var args = Array.prototype.slice.call(arguments);
  16436. return fn.apply(null, [async.eachSeries].concat(args));
  16437. };
  16438. };
  16439. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16440. arr = _map(arr, function (x, i) {
  16441. return {index: i, value: x};
  16442. });
  16443. if (!callback) {
  16444. eachfn(arr, function (x, callback) {
  16445. iterator(x.value, function (err) {
  16446. callback(err);
  16447. });
  16448. });
  16449. } else {
  16450. var results = [];
  16451. eachfn(arr, function (x, callback) {
  16452. iterator(x.value, function (err, v) {
  16453. results[x.index] = v;
  16454. callback(err);
  16455. });
  16456. }, function (err) {
  16457. callback(err, results);
  16458. });
  16459. }
  16460. };
  16461. async.map = doParallel(_asyncMap);
  16462. async.mapSeries = doSeries(_asyncMap);
  16463. async.mapLimit = function (arr, limit, iterator, callback) {
  16464. return _mapLimit(limit)(arr, iterator, callback);
  16465. };
  16466. var _mapLimit = function(limit) {
  16467. return doParallelLimit(limit, _asyncMap);
  16468. };
  16469. // reduce only has a series version, as doing reduce in parallel won't
  16470. // work in many situations.
  16471. async.reduce = function (arr, memo, iterator, callback) {
  16472. async.eachSeries(arr, function (x, callback) {
  16473. iterator(memo, x, function (err, v) {
  16474. memo = v;
  16475. callback(err);
  16476. });
  16477. }, function (err) {
  16478. callback(err, memo);
  16479. });
  16480. };
  16481. // inject alias
  16482. async.inject = async.reduce;
  16483. // foldl alias
  16484. async.foldl = async.reduce;
  16485. async.reduceRight = function (arr, memo, iterator, callback) {
  16486. var reversed = _map(arr, function (x) {
  16487. return x;
  16488. }).reverse();
  16489. async.reduce(reversed, memo, iterator, callback);
  16490. };
  16491. // foldr alias
  16492. async.foldr = async.reduceRight;
  16493. var _filter = function (eachfn, arr, iterator, callback) {
  16494. var results = [];
  16495. arr = _map(arr, function (x, i) {
  16496. return {index: i, value: x};
  16497. });
  16498. eachfn(arr, function (x, callback) {
  16499. iterator(x.value, function (v) {
  16500. if (v) {
  16501. results.push(x);
  16502. }
  16503. callback();
  16504. });
  16505. }, function (err) {
  16506. callback(_map(results.sort(function (a, b) {
  16507. return a.index - b.index;
  16508. }), function (x) {
  16509. return x.value;
  16510. }));
  16511. });
  16512. };
  16513. async.filter = doParallel(_filter);
  16514. async.filterSeries = doSeries(_filter);
  16515. // select alias
  16516. async.select = async.filter;
  16517. async.selectSeries = async.filterSeries;
  16518. var _reject = function (eachfn, arr, iterator, callback) {
  16519. var results = [];
  16520. arr = _map(arr, function (x, i) {
  16521. return {index: i, value: x};
  16522. });
  16523. eachfn(arr, function (x, callback) {
  16524. iterator(x.value, function (v) {
  16525. if (!v) {
  16526. results.push(x);
  16527. }
  16528. callback();
  16529. });
  16530. }, function (err) {
  16531. callback(_map(results.sort(function (a, b) {
  16532. return a.index - b.index;
  16533. }), function (x) {
  16534. return x.value;
  16535. }));
  16536. });
  16537. };
  16538. async.reject = doParallel(_reject);
  16539. async.rejectSeries = doSeries(_reject);
  16540. var _detect = function (eachfn, arr, iterator, main_callback) {
  16541. eachfn(arr, function (x, callback) {
  16542. iterator(x, function (result) {
  16543. if (result) {
  16544. main_callback(x);
  16545. main_callback = function () {};
  16546. }
  16547. else {
  16548. callback();
  16549. }
  16550. });
  16551. }, function (err) {
  16552. main_callback();
  16553. });
  16554. };
  16555. async.detect = doParallel(_detect);
  16556. async.detectSeries = doSeries(_detect);
  16557. async.some = function (arr, iterator, main_callback) {
  16558. async.each(arr, function (x, callback) {
  16559. iterator(x, function (v) {
  16560. if (v) {
  16561. main_callback(true);
  16562. main_callback = function () {};
  16563. }
  16564. callback();
  16565. });
  16566. }, function (err) {
  16567. main_callback(false);
  16568. });
  16569. };
  16570. // any alias
  16571. async.any = async.some;
  16572. async.every = function (arr, iterator, main_callback) {
  16573. async.each(arr, function (x, callback) {
  16574. iterator(x, function (v) {
  16575. if (!v) {
  16576. main_callback(false);
  16577. main_callback = function () {};
  16578. }
  16579. callback();
  16580. });
  16581. }, function (err) {
  16582. main_callback(true);
  16583. });
  16584. };
  16585. // all alias
  16586. async.all = async.every;
  16587. async.sortBy = function (arr, iterator, callback) {
  16588. async.map(arr, function (x, callback) {
  16589. iterator(x, function (err, criteria) {
  16590. if (err) {
  16591. callback(err);
  16592. }
  16593. else {
  16594. callback(null, {value: x, criteria: criteria});
  16595. }
  16596. });
  16597. }, function (err, results) {
  16598. if (err) {
  16599. return callback(err);
  16600. }
  16601. else {
  16602. var fn = function (left, right) {
  16603. var a = left.criteria, b = right.criteria;
  16604. return a < b ? -1 : a > b ? 1 : 0;
  16605. };
  16606. callback(null, _map(results.sort(fn), function (x) {
  16607. return x.value;
  16608. }));
  16609. }
  16610. });
  16611. };
  16612. async.auto = function (tasks, callback) {
  16613. callback = callback || function () {};
  16614. var keys = _keys(tasks);
  16615. var remainingTasks = keys.length
  16616. if (!remainingTasks) {
  16617. return callback();
  16618. }
  16619. var results = {};
  16620. var listeners = [];
  16621. var addListener = function (fn) {
  16622. listeners.unshift(fn);
  16623. };
  16624. var removeListener = function (fn) {
  16625. for (var i = 0; i < listeners.length; i += 1) {
  16626. if (listeners[i] === fn) {
  16627. listeners.splice(i, 1);
  16628. return;
  16629. }
  16630. }
  16631. };
  16632. var taskComplete = function () {
  16633. remainingTasks--
  16634. _each(listeners.slice(0), function (fn) {
  16635. fn();
  16636. });
  16637. };
  16638. addListener(function () {
  16639. if (!remainingTasks) {
  16640. var theCallback = callback;
  16641. // prevent final callback from calling itself if it errors
  16642. callback = function () {};
  16643. theCallback(null, results);
  16644. }
  16645. });
  16646. _each(keys, function (k) {
  16647. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  16648. var taskCallback = function (err) {
  16649. var args = Array.prototype.slice.call(arguments, 1);
  16650. if (args.length <= 1) {
  16651. args = args[0];
  16652. }
  16653. if (err) {
  16654. var safeResults = {};
  16655. _each(_keys(results), function(rkey) {
  16656. safeResults[rkey] = results[rkey];
  16657. });
  16658. safeResults[k] = args;
  16659. callback(err, safeResults);
  16660. // stop subsequent errors hitting callback multiple times
  16661. callback = function () {};
  16662. }
  16663. else {
  16664. results[k] = args;
  16665. async.setImmediate(taskComplete);
  16666. }
  16667. };
  16668. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  16669. var ready = function () {
  16670. return _reduce(requires, function (a, x) {
  16671. return (a && results.hasOwnProperty(x));
  16672. }, true) && !results.hasOwnProperty(k);
  16673. };
  16674. if (ready()) {
  16675. task[task.length - 1](taskCallback, results);
  16676. }
  16677. else {
  16678. var listener = function () {
  16679. if (ready()) {
  16680. removeListener(listener);
  16681. task[task.length - 1](taskCallback, results);
  16682. }
  16683. };
  16684. addListener(listener);
  16685. }
  16686. });
  16687. };
  16688. async.retry = function(times, task, callback) {
  16689. var DEFAULT_TIMES = 5;
  16690. var attempts = [];
  16691. // Use defaults if times not passed
  16692. if (typeof times === 'function') {
  16693. callback = task;
  16694. task = times;
  16695. times = DEFAULT_TIMES;
  16696. }
  16697. // Make sure times is a number
  16698. times = parseInt(times, 10) || DEFAULT_TIMES;
  16699. var wrappedTask = function(wrappedCallback, wrappedResults) {
  16700. var retryAttempt = function(task, finalAttempt) {
  16701. return function(seriesCallback) {
  16702. task(function(err, result){
  16703. seriesCallback(!err || finalAttempt, {err: err, result: result});
  16704. }, wrappedResults);
  16705. };
  16706. };
  16707. while (times) {
  16708. attempts.push(retryAttempt(task, !(times-=1)));
  16709. }
  16710. async.series(attempts, function(done, data){
  16711. data = data[data.length - 1];
  16712. (wrappedCallback || callback)(data.err, data.result);
  16713. });
  16714. }
  16715. // If a callback is passed, run this as a controll flow
  16716. return callback ? wrappedTask() : wrappedTask
  16717. };
  16718. async.waterfall = function (tasks, callback) {
  16719. callback = callback || function () {};
  16720. if (!_isArray(tasks)) {
  16721. var err = new Error('First argument to waterfall must be an array of functions');
  16722. return callback(err);
  16723. }
  16724. if (!tasks.length) {
  16725. return callback();
  16726. }
  16727. var wrapIterator = function (iterator) {
  16728. return function (err) {
  16729. if (err) {
  16730. callback.apply(null, arguments);
  16731. callback = function () {};
  16732. }
  16733. else {
  16734. var args = Array.prototype.slice.call(arguments, 1);
  16735. var next = iterator.next();
  16736. if (next) {
  16737. args.push(wrapIterator(next));
  16738. }
  16739. else {
  16740. args.push(callback);
  16741. }
  16742. async.setImmediate(function () {
  16743. iterator.apply(null, args);
  16744. });
  16745. }
  16746. };
  16747. };
  16748. wrapIterator(async.iterator(tasks))();
  16749. };
  16750. var _parallel = function(eachfn, tasks, callback) {
  16751. callback = callback || function () {};
  16752. if (_isArray(tasks)) {
  16753. eachfn.map(tasks, function (fn, callback) {
  16754. if (fn) {
  16755. fn(function (err) {
  16756. var args = Array.prototype.slice.call(arguments, 1);
  16757. if (args.length <= 1) {
  16758. args = args[0];
  16759. }
  16760. callback.call(null, err, args);
  16761. });
  16762. }
  16763. }, callback);
  16764. }
  16765. else {
  16766. var results = {};
  16767. eachfn.each(_keys(tasks), function (k, callback) {
  16768. tasks[k](function (err) {
  16769. var args = Array.prototype.slice.call(arguments, 1);
  16770. if (args.length <= 1) {
  16771. args = args[0];
  16772. }
  16773. results[k] = args;
  16774. callback(err);
  16775. });
  16776. }, function (err) {
  16777. callback(err, results);
  16778. });
  16779. }
  16780. };
  16781. async.parallel = function (tasks, callback) {
  16782. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16783. };
  16784. async.parallelLimit = function(tasks, limit, callback) {
  16785. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16786. };
  16787. async.series = function (tasks, callback) {
  16788. callback = callback || function () {};
  16789. if (_isArray(tasks)) {
  16790. async.mapSeries(tasks, function (fn, callback) {
  16791. if (fn) {
  16792. fn(function (err) {
  16793. var args = Array.prototype.slice.call(arguments, 1);
  16794. if (args.length <= 1) {
  16795. args = args[0];
  16796. }
  16797. callback.call(null, err, args);
  16798. });
  16799. }
  16800. }, callback);
  16801. }
  16802. else {
  16803. var results = {};
  16804. async.eachSeries(_keys(tasks), function (k, callback) {
  16805. tasks[k](function (err) {
  16806. var args = Array.prototype.slice.call(arguments, 1);
  16807. if (args.length <= 1) {
  16808. args = args[0];
  16809. }
  16810. results[k] = args;
  16811. callback(err);
  16812. });
  16813. }, function (err) {
  16814. callback(err, results);
  16815. });
  16816. }
  16817. };
  16818. async.iterator = function (tasks) {
  16819. var makeCallback = function (index) {
  16820. var fn = function () {
  16821. if (tasks.length) {
  16822. tasks[index].apply(null, arguments);
  16823. }
  16824. return fn.next();
  16825. };
  16826. fn.next = function () {
  16827. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  16828. };
  16829. return fn;
  16830. };
  16831. return makeCallback(0);
  16832. };
  16833. async.apply = function (fn) {
  16834. var args = Array.prototype.slice.call(arguments, 1);
  16835. return function () {
  16836. return fn.apply(
  16837. null, args.concat(Array.prototype.slice.call(arguments))
  16838. );
  16839. };
  16840. };
  16841. var _concat = function (eachfn, arr, fn, callback) {
  16842. var r = [];
  16843. eachfn(arr, function (x, cb) {
  16844. fn(x, function (err, y) {
  16845. r = r.concat(y || []);
  16846. cb(err);
  16847. });
  16848. }, function (err) {
  16849. callback(err, r);
  16850. });
  16851. };
  16852. async.concat = doParallel(_concat);
  16853. async.concatSeries = doSeries(_concat);
  16854. async.whilst = function (test, iterator, callback) {
  16855. if (test()) {
  16856. iterator(function (err) {
  16857. if (err) {
  16858. return callback(err);
  16859. }
  16860. async.whilst(test, iterator, callback);
  16861. });
  16862. }
  16863. else {
  16864. callback();
  16865. }
  16866. };
  16867. async.doWhilst = function (iterator, test, callback) {
  16868. iterator(function (err) {
  16869. if (err) {
  16870. return callback(err);
  16871. }
  16872. var args = Array.prototype.slice.call(arguments, 1);
  16873. if (test.apply(null, args)) {
  16874. async.doWhilst(iterator, test, callback);
  16875. }
  16876. else {
  16877. callback();
  16878. }
  16879. });
  16880. };
  16881. async.until = function (test, iterator, callback) {
  16882. if (!test()) {
  16883. iterator(function (err) {
  16884. if (err) {
  16885. return callback(err);
  16886. }
  16887. async.until(test, iterator, callback);
  16888. });
  16889. }
  16890. else {
  16891. callback();
  16892. }
  16893. };
  16894. async.doUntil = function (iterator, test, callback) {
  16895. iterator(function (err) {
  16896. if (err) {
  16897. return callback(err);
  16898. }
  16899. var args = Array.prototype.slice.call(arguments, 1);
  16900. if (!test.apply(null, args)) {
  16901. async.doUntil(iterator, test, callback);
  16902. }
  16903. else {
  16904. callback();
  16905. }
  16906. });
  16907. };
  16908. async.queue = function (worker, concurrency) {
  16909. if (concurrency === undefined) {
  16910. concurrency = 1;
  16911. }
  16912. function _insert(q, data, pos, callback) {
  16913. if (!q.started){
  16914. q.started = true;
  16915. }
  16916. if (!_isArray(data)) {
  16917. data = [data];
  16918. }
  16919. if(data.length == 0) {
  16920. // call drain immediately if there are no tasks
  16921. return async.setImmediate(function() {
  16922. if (q.drain) {
  16923. q.drain();
  16924. }
  16925. });
  16926. }
  16927. _each(data, function(task) {
  16928. var item = {
  16929. data: task,
  16930. callback: typeof callback === 'function' ? callback : null
  16931. };
  16932. if (pos) {
  16933. q.tasks.unshift(item);
  16934. } else {
  16935. q.tasks.push(item);
  16936. }
  16937. if (q.saturated && q.tasks.length === q.concurrency) {
  16938. q.saturated();
  16939. }
  16940. async.setImmediate(q.process);
  16941. });
  16942. }
  16943. var workers = 0;
  16944. var q = {
  16945. tasks: [],
  16946. concurrency: concurrency,
  16947. saturated: null,
  16948. empty: null,
  16949. drain: null,
  16950. started: false,
  16951. paused: false,
  16952. push: function (data, callback) {
  16953. _insert(q, data, false, callback);
  16954. },
  16955. kill: function () {
  16956. q.drain = null;
  16957. q.tasks = [];
  16958. },
  16959. unshift: function (data, callback) {
  16960. _insert(q, data, true, callback);
  16961. },
  16962. process: function () {
  16963. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  16964. var task = q.tasks.shift();
  16965. if (q.empty && q.tasks.length === 0) {
  16966. q.empty();
  16967. }
  16968. workers += 1;
  16969. var next = function () {
  16970. workers -= 1;
  16971. if (task.callback) {
  16972. task.callback.apply(task, arguments);
  16973. }
  16974. if (q.drain && q.tasks.length + workers === 0) {
  16975. q.drain();
  16976. }
  16977. q.process();
  16978. };
  16979. var cb = only_once(next);
  16980. worker(task.data, cb);
  16981. }
  16982. },
  16983. length: function () {
  16984. return q.tasks.length;
  16985. },
  16986. running: function () {
  16987. return workers;
  16988. },
  16989. idle: function() {
  16990. return q.tasks.length + workers === 0;
  16991. },
  16992. pause: function () {
  16993. if (q.paused === true) { return; }
  16994. q.paused = true;
  16995. q.process();
  16996. },
  16997. resume: function () {
  16998. if (q.paused === false) { return; }
  16999. q.paused = false;
  17000. q.process();
  17001. }
  17002. };
  17003. return q;
  17004. };
  17005. async.priorityQueue = function (worker, concurrency) {
  17006. function _compareTasks(a, b){
  17007. return a.priority - b.priority;
  17008. };
  17009. function _binarySearch(sequence, item, compare) {
  17010. var beg = -1,
  17011. end = sequence.length - 1;
  17012. while (beg < end) {
  17013. var mid = beg + ((end - beg + 1) >>> 1);
  17014. if (compare(item, sequence[mid]) >= 0) {
  17015. beg = mid;
  17016. } else {
  17017. end = mid - 1;
  17018. }
  17019. }
  17020. return beg;
  17021. }
  17022. function _insert(q, data, priority, callback) {
  17023. if (!q.started){
  17024. q.started = true;
  17025. }
  17026. if (!_isArray(data)) {
  17027. data = [data];
  17028. }
  17029. if(data.length == 0) {
  17030. // call drain immediately if there are no tasks
  17031. return async.setImmediate(function() {
  17032. if (q.drain) {
  17033. q.drain();
  17034. }
  17035. });
  17036. }
  17037. _each(data, function(task) {
  17038. var item = {
  17039. data: task,
  17040. priority: priority,
  17041. callback: typeof callback === 'function' ? callback : null
  17042. };
  17043. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17044. if (q.saturated && q.tasks.length === q.concurrency) {
  17045. q.saturated();
  17046. }
  17047. async.setImmediate(q.process);
  17048. });
  17049. }
  17050. // Start with a normal queue
  17051. var q = async.queue(worker, concurrency);
  17052. // Override push to accept second parameter representing priority
  17053. q.push = function (data, priority, callback) {
  17054. _insert(q, data, priority, callback);
  17055. };
  17056. // Remove unshift function
  17057. delete q.unshift;
  17058. return q;
  17059. };
  17060. async.cargo = function (worker, payload) {
  17061. var working = false,
  17062. tasks = [];
  17063. var cargo = {
  17064. tasks: tasks,
  17065. payload: payload,
  17066. saturated: null,
  17067. empty: null,
  17068. drain: null,
  17069. drained: true,
  17070. push: function (data, callback) {
  17071. if (!_isArray(data)) {
  17072. data = [data];
  17073. }
  17074. _each(data, function(task) {
  17075. tasks.push({
  17076. data: task,
  17077. callback: typeof callback === 'function' ? callback : null
  17078. });
  17079. cargo.drained = false;
  17080. if (cargo.saturated && tasks.length === payload) {
  17081. cargo.saturated();
  17082. }
  17083. });
  17084. async.setImmediate(cargo.process);
  17085. },
  17086. process: function process() {
  17087. if (working) return;
  17088. if (tasks.length === 0) {
  17089. if(cargo.drain && !cargo.drained) cargo.drain();
  17090. cargo.drained = true;
  17091. return;
  17092. }
  17093. var ts = typeof payload === 'number'
  17094. ? tasks.splice(0, payload)
  17095. : tasks.splice(0, tasks.length);
  17096. var ds = _map(ts, function (task) {
  17097. return task.data;
  17098. });
  17099. if(cargo.empty) cargo.empty();
  17100. working = true;
  17101. worker(ds, function () {
  17102. working = false;
  17103. var args = arguments;
  17104. _each(ts, function (data) {
  17105. if (data.callback) {
  17106. data.callback.apply(null, args);
  17107. }
  17108. });
  17109. process();
  17110. });
  17111. },
  17112. length: function () {
  17113. return tasks.length;
  17114. },
  17115. running: function () {
  17116. return working;
  17117. }
  17118. };
  17119. return cargo;
  17120. };
  17121. var _console_fn = function (name) {
  17122. return function (fn) {
  17123. var args = Array.prototype.slice.call(arguments, 1);
  17124. fn.apply(null, args.concat([function (err) {
  17125. var args = Array.prototype.slice.call(arguments, 1);
  17126. if (typeof console !== 'undefined') {
  17127. if (err) {
  17128. if (console.error) {
  17129. console.error(err);
  17130. }
  17131. }
  17132. else if (console[name]) {
  17133. _each(args, function (x) {
  17134. console[name](x);
  17135. });
  17136. }
  17137. }
  17138. }]));
  17139. };
  17140. };
  17141. async.log = _console_fn('log');
  17142. async.dir = _console_fn('dir');
  17143. /*async.info = _console_fn('info');
  17144. async.warn = _console_fn('warn');
  17145. async.error = _console_fn('error');*/
  17146. async.memoize = function (fn, hasher) {
  17147. var memo = {};
  17148. var queues = {};
  17149. hasher = hasher || function (x) {
  17150. return x;
  17151. };
  17152. var memoized = function () {
  17153. var args = Array.prototype.slice.call(arguments);
  17154. var callback = args.pop();
  17155. var key = hasher.apply(null, args);
  17156. if (key in memo) {
  17157. async.nextTick(function () {
  17158. callback.apply(null, memo[key]);
  17159. });
  17160. }
  17161. else if (key in queues) {
  17162. queues[key].push(callback);
  17163. }
  17164. else {
  17165. queues[key] = [callback];
  17166. fn.apply(null, args.concat([function () {
  17167. memo[key] = arguments;
  17168. var q = queues[key];
  17169. delete queues[key];
  17170. for (var i = 0, l = q.length; i < l; i++) {
  17171. q[i].apply(null, arguments);
  17172. }
  17173. }]));
  17174. }
  17175. };
  17176. memoized.memo = memo;
  17177. memoized.unmemoized = fn;
  17178. return memoized;
  17179. };
  17180. async.unmemoize = function (fn) {
  17181. return function () {
  17182. return (fn.unmemoized || fn).apply(null, arguments);
  17183. };
  17184. };
  17185. async.times = function (count, iterator, callback) {
  17186. var counter = [];
  17187. for (var i = 0; i < count; i++) {
  17188. counter.push(i);
  17189. }
  17190. return async.map(counter, iterator, callback);
  17191. };
  17192. async.timesSeries = function (count, iterator, callback) {
  17193. var counter = [];
  17194. for (var i = 0; i < count; i++) {
  17195. counter.push(i);
  17196. }
  17197. return async.mapSeries(counter, iterator, callback);
  17198. };
  17199. async.seq = function (/* functions... */) {
  17200. var fns = arguments;
  17201. return function () {
  17202. var that = this;
  17203. var args = Array.prototype.slice.call(arguments);
  17204. var callback = args.pop();
  17205. async.reduce(fns, args, function (newargs, fn, cb) {
  17206. fn.apply(that, newargs.concat([function () {
  17207. var err = arguments[0];
  17208. var nextargs = Array.prototype.slice.call(arguments, 1);
  17209. cb(err, nextargs);
  17210. }]))
  17211. },
  17212. function (err, results) {
  17213. callback.apply(that, [err].concat(results));
  17214. });
  17215. };
  17216. };
  17217. async.compose = function (/* functions... */) {
  17218. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17219. };
  17220. var _applyEach = function (eachfn, fns /*args...*/) {
  17221. var go = function () {
  17222. var that = this;
  17223. var args = Array.prototype.slice.call(arguments);
  17224. var callback = args.pop();
  17225. return eachfn(fns, function (fn, cb) {
  17226. fn.apply(that, args.concat([cb]));
  17227. },
  17228. callback);
  17229. };
  17230. if (arguments.length > 2) {
  17231. var args = Array.prototype.slice.call(arguments, 2);
  17232. return go.apply(this, args);
  17233. }
  17234. else {
  17235. return go;
  17236. }
  17237. };
  17238. async.applyEach = doParallel(_applyEach);
  17239. async.applyEachSeries = doSeries(_applyEach);
  17240. async.forever = function (fn, callback) {
  17241. function next(err) {
  17242. if (err) {
  17243. if (callback) {
  17244. return callback(err);
  17245. }
  17246. throw err;
  17247. }
  17248. fn(next);
  17249. }
  17250. next();
  17251. };
  17252. // Node.js
  17253. if (typeof module !== 'undefined' && module.exports) {
  17254. module.exports = async;
  17255. }
  17256. // AMD / RequireJS
  17257. else if (typeof define !== 'undefined' && define.amd) {
  17258. define([], function () {
  17259. return async;
  17260. });
  17261. }
  17262. // included directly via <script> tag
  17263. else {
  17264. root.async = async;
  17265. }
  17266. }());
  17267. }).call(this,require('_process'))
  17268. },{"_process":114}],68:[function(require,module,exports){
  17269. // i18next, v1.7.7
  17270. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17271. // Distributed under MIT license
  17272. // http://i18next.com
  17273. (function() {
  17274. // add indexOf to non ECMA-262 standard compliant browsers
  17275. if (!Array.prototype.indexOf) {
  17276. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17277. "use strict";
  17278. if (this == null) {
  17279. throw new TypeError();
  17280. }
  17281. var t = Object(this);
  17282. var len = t.length >>> 0;
  17283. if (len === 0) {
  17284. return -1;
  17285. }
  17286. var n = 0;
  17287. if (arguments.length > 0) {
  17288. n = Number(arguments[1]);
  17289. if (n != n) { // shortcut for verifying if it's NaN
  17290. n = 0;
  17291. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17292. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17293. }
  17294. }
  17295. if (n >= len) {
  17296. return -1;
  17297. }
  17298. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17299. for (; k < len; k++) {
  17300. if (k in t && t[k] === searchElement) {
  17301. return k;
  17302. }
  17303. }
  17304. return -1;
  17305. }
  17306. }
  17307. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17308. if (!Array.prototype.lastIndexOf) {
  17309. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17310. "use strict";
  17311. if (this == null) {
  17312. throw new TypeError();
  17313. }
  17314. var t = Object(this);
  17315. var len = t.length >>> 0;
  17316. if (len === 0) {
  17317. return -1;
  17318. }
  17319. var n = len;
  17320. if (arguments.length > 1) {
  17321. n = Number(arguments[1]);
  17322. if (n != n) {
  17323. n = 0;
  17324. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17325. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17326. }
  17327. }
  17328. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17329. for (; k >= 0; k--) {
  17330. if (k in t && t[k] === searchElement) {
  17331. return k;
  17332. }
  17333. }
  17334. return -1;
  17335. };
  17336. }
  17337. // Add string trim for IE8.
  17338. if (typeof String.prototype.trim !== 'function') {
  17339. String.prototype.trim = function() {
  17340. return this.replace(/^\s+|\s+$/g, '');
  17341. }
  17342. }
  17343. var root = this
  17344. , $ = root.jQuery || root.Zepto
  17345. , i18n = {}
  17346. , resStore = {}
  17347. , currentLng
  17348. , replacementCounter = 0
  17349. , languages = []
  17350. , initialized = false
  17351. , sync = {};
  17352. // Export the i18next object for **CommonJS**.
  17353. // If we're not in CommonJS, add `i18n` to the
  17354. // global object or to jquery.
  17355. if (typeof module !== 'undefined' && module.exports) {
  17356. if (!$) {
  17357. try {
  17358. $ = require('jquery');
  17359. } catch(e) {
  17360. // just ignore
  17361. }
  17362. }
  17363. if ($) {
  17364. $.i18n = $.i18n || i18n;
  17365. }
  17366. module.exports = i18n;
  17367. } else {
  17368. if ($) {
  17369. $.i18n = $.i18n || i18n;
  17370. }
  17371. root.i18n = root.i18n || i18n;
  17372. }
  17373. sync = {
  17374. load: function(lngs, options, cb) {
  17375. if (options.useLocalStorage) {
  17376. sync._loadLocal(lngs, options, function(err, store) {
  17377. var missingLngs = [];
  17378. for (var i = 0, len = lngs.length; i < len; i++) {
  17379. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17380. }
  17381. if (missingLngs.length > 0) {
  17382. sync._fetch(missingLngs, options, function(err, fetched) {
  17383. f.extend(store, fetched);
  17384. sync._storeLocal(fetched);
  17385. cb(null, store);
  17386. });
  17387. } else {
  17388. cb(null, store);
  17389. }
  17390. });
  17391. } else {
  17392. sync._fetch(lngs, options, function(err, store){
  17393. cb(null, store);
  17394. });
  17395. }
  17396. },
  17397. _loadLocal: function(lngs, options, cb) {
  17398. var store = {}
  17399. , nowMS = new Date().getTime();
  17400. if(window.localStorage) {
  17401. var todo = lngs.length;
  17402. f.each(lngs, function(key, lng) {
  17403. var local = window.localStorage.getItem('res_' + lng);
  17404. if (local) {
  17405. local = JSON.parse(local);
  17406. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17407. store[lng] = local;
  17408. }
  17409. }
  17410. todo--; // wait for all done befor callback
  17411. if (todo === 0) cb(null, store);
  17412. });
  17413. }
  17414. },
  17415. _storeLocal: function(store) {
  17416. if(window.localStorage) {
  17417. for (var m in store) {
  17418. store[m].i18nStamp = new Date().getTime();
  17419. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17420. }
  17421. }
  17422. return;
  17423. },
  17424. _fetch: function(lngs, options, cb) {
  17425. var ns = options.ns
  17426. , store = {};
  17427. if (!options.dynamicLoad) {
  17428. var todo = ns.namespaces.length * lngs.length
  17429. , errors;
  17430. // load each file individual
  17431. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17432. f.each(lngs, function(lngIndex, lngValue) {
  17433. // Call this once our translation has returned.
  17434. var loadComplete = function(err, data) {
  17435. if (err) {
  17436. errors = errors || [];
  17437. errors.push(err);
  17438. }
  17439. store[lngValue] = store[lngValue] || {};
  17440. store[lngValue][nsValue] = data;
  17441. todo--; // wait for all done befor callback
  17442. if (todo === 0) cb(errors, store);
  17443. };
  17444. if(typeof options.customLoad == 'function'){
  17445. // Use the specified custom callback.
  17446. options.customLoad(lngValue, nsValue, options, loadComplete);
  17447. } else {
  17448. //~ // Use our inbuilt sync.
  17449. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17450. }
  17451. });
  17452. });
  17453. } else {
  17454. // Call this once our translation has returned.
  17455. var loadComplete = function(err, data) {
  17456. cb(null, data);
  17457. };
  17458. if(typeof options.customLoad == 'function'){
  17459. // Use the specified custom callback.
  17460. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17461. } else {
  17462. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17463. // load all needed stuff once
  17464. f.ajax({
  17465. url: url,
  17466. success: function(data, status, xhr) {
  17467. f.log('loaded: ' + url);
  17468. loadComplete(null, data);
  17469. },
  17470. error : function(xhr, status, error) {
  17471. f.log('failed loading: ' + url);
  17472. loadComplete('failed loading resource.json error: ' + error);
  17473. },
  17474. dataType: "json",
  17475. async : options.getAsync
  17476. });
  17477. }
  17478. }
  17479. },
  17480. _fetchOne: function(lng, ns, options, done) {
  17481. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17482. f.ajax({
  17483. url: url,
  17484. success: function(data, status, xhr) {
  17485. f.log('loaded: ' + url);
  17486. done(null, data);
  17487. },
  17488. error : function(xhr, status, error) {
  17489. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17490. // file loaded but invalid json, stop waste time !
  17491. f.error('There is a typo in: ' + url);
  17492. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17493. f.log('Does not exist: ' + url);
  17494. } else {
  17495. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17496. f.log(theStatus + ' when loading ' + url);
  17497. }
  17498. done(error, {});
  17499. },
  17500. dataType: "json",
  17501. async : options.getAsync
  17502. });
  17503. },
  17504. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17505. var payload = {};
  17506. payload[key] = defaultValue;
  17507. var urls = [];
  17508. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17509. for (var i = 0; i < o.fallbackLng.length; i++) {
  17510. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17511. }
  17512. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17513. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17514. } else if (o.sendMissingTo === 'all') {
  17515. for (var i = 0, l = lngs.length; i < l; i++) {
  17516. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17517. }
  17518. }
  17519. for (var y = 0, len = urls.length; y < len; y++) {
  17520. var item = urls[y];
  17521. f.ajax({
  17522. url: item.url,
  17523. type: o.sendType,
  17524. data: payload,
  17525. success: function(data, status, xhr) {
  17526. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17527. // add key to resStore
  17528. var keys = key.split('.');
  17529. var x = 0;
  17530. var value = resStore[item.lng][ns];
  17531. while (keys[x]) {
  17532. if (x === keys.length - 1) {
  17533. value = value[keys[x]] = defaultValue;
  17534. } else {
  17535. value = value[keys[x]] = value[keys[x]] || {};
  17536. }
  17537. x++;
  17538. }
  17539. },
  17540. error : function(xhr, status, error) {
  17541. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17542. },
  17543. dataType: "json",
  17544. async : o.postAsync
  17545. });
  17546. }
  17547. },
  17548. reload: reload
  17549. };
  17550. // defaults
  17551. var o = {
  17552. lng: undefined,
  17553. load: 'all',
  17554. preload: [],
  17555. lowerCaseLng: false,
  17556. returnObjectTrees: false,
  17557. fallbackLng: ['dev'],
  17558. fallbackNS: [],
  17559. detectLngQS: 'setLng',
  17560. detectLngFromLocalStorage: false,
  17561. ns: 'translation',
  17562. fallbackOnNull: true,
  17563. fallbackOnEmpty: false,
  17564. fallbackToDefaultNS: false,
  17565. nsseparator: ':',
  17566. keyseparator: '.',
  17567. selectorAttr: 'data-i18n',
  17568. debug: false,
  17569. resGetPath: 'locales/__lng__/__ns__.json',
  17570. resPostPath: 'locales/add/__lng__/__ns__',
  17571. getAsync: true,
  17572. postAsync: true,
  17573. resStore: undefined,
  17574. useLocalStorage: false,
  17575. localStorageExpirationTime: 7*24*60*60*1000,
  17576. dynamicLoad: false,
  17577. sendMissing: false,
  17578. sendMissingTo: 'fallback', // current | all
  17579. sendType: 'POST',
  17580. interpolationPrefix: '__',
  17581. interpolationSuffix: '__',
  17582. defaultVariables: false,
  17583. reusePrefix: '$t(',
  17584. reuseSuffix: ')',
  17585. pluralSuffix: '_plural',
  17586. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17587. contextNotFound: ['context_not_found', Math.random()].join(''),
  17588. escapeInterpolation: false,
  17589. indefiniteSuffix: '_indefinite',
  17590. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17591. setJqueryExt: true,
  17592. defaultValueFromContent: true,
  17593. useDataAttrOptions: false,
  17594. cookieExpirationTime: undefined,
  17595. useCookie: true,
  17596. cookieName: 'i18next',
  17597. cookieDomain: undefined,
  17598. objectTreeKeyHandler: undefined,
  17599. postProcess: undefined,
  17600. parseMissingKey: undefined,
  17601. missingKeyHandler: sync.postMissing,
  17602. shortcutFunction: 'sprintf' // or: defaultValue
  17603. };
  17604. function _extend(target, source) {
  17605. if (!source || typeof source === 'function') {
  17606. return target;
  17607. }
  17608. for (var attr in source) { target[attr] = source[attr]; }
  17609. return target;
  17610. }
  17611. function _deepExtend(target, source) {
  17612. for (var prop in source)
  17613. if (prop in target)
  17614. _deepExtend(target[prop], source[prop]);
  17615. else
  17616. target[prop] = source[prop];
  17617. return target;
  17618. }
  17619. function _each(object, callback, args) {
  17620. var name, i = 0,
  17621. length = object.length,
  17622. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17623. if (args) {
  17624. if (isObj) {
  17625. for (name in object) {
  17626. if (callback.apply(object[name], args) === false) {
  17627. break;
  17628. }
  17629. }
  17630. } else {
  17631. for ( ; i < length; ) {
  17632. if (callback.apply(object[i++], args) === false) {
  17633. break;
  17634. }
  17635. }
  17636. }
  17637. // A special, fast, case for the most common use of each
  17638. } else {
  17639. if (isObj) {
  17640. for (name in object) {
  17641. if (callback.call(object[name], name, object[name]) === false) {
  17642. break;
  17643. }
  17644. }
  17645. } else {
  17646. for ( ; i < length; ) {
  17647. if (callback.call(object[i], i, object[i++]) === false) {
  17648. break;
  17649. }
  17650. }
  17651. }
  17652. }
  17653. return object;
  17654. }
  17655. var _entityMap = {
  17656. "&": "&amp;",
  17657. "<": "&lt;",
  17658. ">": "&gt;",
  17659. '"': '&quot;',
  17660. "'": '&#39;',
  17661. "/": '&#x2F;'
  17662. };
  17663. function _escape(data) {
  17664. if (typeof data === 'string') {
  17665. return data.replace(/[&<>"'\/]/g, function (s) {
  17666. return _entityMap[s];
  17667. });
  17668. }else{
  17669. return data;
  17670. }
  17671. }
  17672. function _ajax(options) {
  17673. // v0.5.0 of https://github.com/goloroden/http.js
  17674. var getXhr = function (callback) {
  17675. // Use the native XHR object if the browser supports it.
  17676. if (window.XMLHttpRequest) {
  17677. return callback(null, new XMLHttpRequest());
  17678. } else if (window.ActiveXObject) {
  17679. // In Internet Explorer check for ActiveX versions of the XHR object.
  17680. try {
  17681. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  17682. } catch (e) {
  17683. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  17684. }
  17685. }
  17686. // If no XHR support was found, throw an error.
  17687. return callback(new Error());
  17688. };
  17689. var encodeUsingUrlEncoding = function (data) {
  17690. if(typeof data === 'string') {
  17691. return data;
  17692. }
  17693. var result = [];
  17694. for(var dataItem in data) {
  17695. if(data.hasOwnProperty(dataItem)) {
  17696. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  17697. }
  17698. }
  17699. return result.join('&');
  17700. };
  17701. var utf8 = function (text) {
  17702. text = text.replace(/\r\n/g, '\n');
  17703. var result = '';
  17704. for(var i = 0; i < text.length; i++) {
  17705. var c = text.charCodeAt(i);
  17706. if(c < 128) {
  17707. result += String.fromCharCode(c);
  17708. } else if((c > 127) && (c < 2048)) {
  17709. result += String.fromCharCode((c >> 6) | 192);
  17710. result += String.fromCharCode((c & 63) | 128);
  17711. } else {
  17712. result += String.fromCharCode((c >> 12) | 224);
  17713. result += String.fromCharCode(((c >> 6) & 63) | 128);
  17714. result += String.fromCharCode((c & 63) | 128);
  17715. }
  17716. }
  17717. return result;
  17718. };
  17719. var base64 = function (text) {
  17720. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17721. text = utf8(text);
  17722. var result = '',
  17723. chr1, chr2, chr3,
  17724. enc1, enc2, enc3, enc4,
  17725. i = 0;
  17726. do {
  17727. chr1 = text.charCodeAt(i++);
  17728. chr2 = text.charCodeAt(i++);
  17729. chr3 = text.charCodeAt(i++);
  17730. enc1 = chr1 >> 2;
  17731. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  17732. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  17733. enc4 = chr3 & 63;
  17734. if(isNaN(chr2)) {
  17735. enc3 = enc4 = 64;
  17736. } else if(isNaN(chr3)) {
  17737. enc4 = 64;
  17738. }
  17739. result +=
  17740. keyStr.charAt(enc1) +
  17741. keyStr.charAt(enc2) +
  17742. keyStr.charAt(enc3) +
  17743. keyStr.charAt(enc4);
  17744. chr1 = chr2 = chr3 = '';
  17745. enc1 = enc2 = enc3 = enc4 = '';
  17746. } while(i < text.length);
  17747. return result;
  17748. };
  17749. var mergeHeaders = function () {
  17750. // Use the first header object as base.
  17751. var result = arguments[0];
  17752. // Iterate through the remaining header objects and add them.
  17753. for(var i = 1; i < arguments.length; i++) {
  17754. var currentHeaders = arguments[i];
  17755. for(var header in currentHeaders) {
  17756. if(currentHeaders.hasOwnProperty(header)) {
  17757. result[header] = currentHeaders[header];
  17758. }
  17759. }
  17760. }
  17761. // Return the merged headers.
  17762. return result;
  17763. };
  17764. var ajax = function (method, url, options, callback) {
  17765. // Adjust parameters.
  17766. if(typeof options === 'function') {
  17767. callback = options;
  17768. options = {};
  17769. }
  17770. // Set default parameter values.
  17771. options.cache = options.cache || false;
  17772. options.data = options.data || {};
  17773. options.headers = options.headers || {};
  17774. options.jsonp = options.jsonp || false;
  17775. options.async = options.async === undefined ? true : options.async;
  17776. // Merge the various header objects.
  17777. var headers = mergeHeaders({
  17778. 'accept': '*/*',
  17779. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  17780. }, ajax.headers, options.headers);
  17781. // Encode the data according to the content-type.
  17782. var payload;
  17783. if (headers['content-type'] === 'application/json') {
  17784. payload = JSON.stringify(options.data);
  17785. } else {
  17786. payload = encodeUsingUrlEncoding(options.data);
  17787. }
  17788. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17789. // if neccessary.
  17790. if(method === 'GET') {
  17791. // Setup the query string.
  17792. var queryString = [];
  17793. if(payload) {
  17794. queryString.push(payload);
  17795. payload = null;
  17796. }
  17797. // Handle caching.
  17798. if(!options.cache) {
  17799. queryString.push('_=' + (new Date()).getTime());
  17800. }
  17801. // If neccessary prepare the query string for a JSONP call.
  17802. if(options.jsonp) {
  17803. queryString.push('callback=' + options.jsonp);
  17804. queryString.push('jsonp=' + options.jsonp);
  17805. }
  17806. // Merge the query string and attach it to the url.
  17807. queryString = queryString.join('&');
  17808. if (queryString.length > 1) {
  17809. if (url.indexOf('?') > -1) {
  17810. url += '&' + queryString;
  17811. } else {
  17812. url += '?' + queryString;
  17813. }
  17814. }
  17815. // Make a JSONP call if neccessary.
  17816. if(options.jsonp) {
  17817. var head = document.getElementsByTagName('head')[0];
  17818. var script = document.createElement('script');
  17819. script.type = 'text/javascript';
  17820. script.src = url;
  17821. head.appendChild(script);
  17822. return;
  17823. }
  17824. }
  17825. // Since we got here, it is no JSONP request, so make a normal XHR request.
  17826. getXhr(function (err, xhr) {
  17827. if(err) return callback(err);
  17828. // Open the request.
  17829. xhr.open(method, url, options.async);
  17830. // Set the request headers.
  17831. for(var header in headers) {
  17832. if(headers.hasOwnProperty(header)) {
  17833. xhr.setRequestHeader(header, headers[header]);
  17834. }
  17835. }
  17836. // Handle the request events.
  17837. xhr.onreadystatechange = function () {
  17838. if(xhr.readyState === 4) {
  17839. var data = xhr.responseText || '';
  17840. // If no callback is given, return.
  17841. if(!callback) {
  17842. return;
  17843. }
  17844. // Return an object that provides access to the data as text and JSON.
  17845. callback(xhr.status, {
  17846. text: function () {
  17847. return data;
  17848. },
  17849. json: function () {
  17850. try {
  17851. return JSON.parse(data)
  17852. } catch (e) {
  17853. f.error('Can not parse JSON. URL: ' + url);
  17854. return {};
  17855. }
  17856. }
  17857. });
  17858. }
  17859. };
  17860. // Actually send the XHR request.
  17861. xhr.send(payload);
  17862. });
  17863. };
  17864. // Define the external interface.
  17865. var http = {
  17866. authBasic: function (username, password) {
  17867. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  17868. },
  17869. connect: function (url, options, callback) {
  17870. return ajax('CONNECT', url, options, callback);
  17871. },
  17872. del: function (url, options, callback) {
  17873. return ajax('DELETE', url, options, callback);
  17874. },
  17875. get: function (url, options, callback) {
  17876. return ajax('GET', url, options, callback);
  17877. },
  17878. head: function (url, options, callback) {
  17879. return ajax('HEAD', url, options, callback);
  17880. },
  17881. headers: function (headers) {
  17882. ajax.headers = headers || {};
  17883. },
  17884. isAllowed: function (url, verb, callback) {
  17885. this.options(url, function (status, data) {
  17886. callback(data.text().indexOf(verb) !== -1);
  17887. });
  17888. },
  17889. options: function (url, options, callback) {
  17890. return ajax('OPTIONS', url, options, callback);
  17891. },
  17892. patch: function (url, options, callback) {
  17893. return ajax('PATCH', url, options, callback);
  17894. },
  17895. post: function (url, options, callback) {
  17896. return ajax('POST', url, options, callback);
  17897. },
  17898. put: function (url, options, callback) {
  17899. return ajax('PUT', url, options, callback);
  17900. },
  17901. trace: function (url, options, callback) {
  17902. return ajax('TRACE', url, options, callback);
  17903. }
  17904. };
  17905. var methode = options.type ? options.type.toLowerCase() : 'get';
  17906. http[methode](options.url, options, function (status, data) {
  17907. // file: protocol always gives status code 0, so check for data
  17908. if (status === 200 || (status === 0 && data.text())) {
  17909. options.success(data.json(), status, null);
  17910. } else {
  17911. options.error(data.text(), status, null);
  17912. }
  17913. });
  17914. }
  17915. var _cookie = {
  17916. create: function(name,value,minutes,domain) {
  17917. var expires;
  17918. if (minutes) {
  17919. var date = new Date();
  17920. date.setTime(date.getTime()+(minutes*60*1000));
  17921. expires = "; expires="+date.toGMTString();
  17922. }
  17923. else expires = "";
  17924. domain = (domain)? "domain="+domain+";" : "";
  17925. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  17926. },
  17927. read: function(name) {
  17928. var nameEQ = name + "=";
  17929. var ca = document.cookie.split(';');
  17930. for(var i=0;i < ca.length;i++) {
  17931. var c = ca[i];
  17932. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  17933. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  17934. }
  17935. return null;
  17936. },
  17937. remove: function(name) {
  17938. this.create(name,"",-1);
  17939. }
  17940. };
  17941. var cookie_noop = {
  17942. create: function(name,value,minutes,domain) {},
  17943. read: function(name) { return null; },
  17944. remove: function(name) {}
  17945. };
  17946. // move dependent functions to a container so that
  17947. // they can be overriden easier in no jquery environment (node.js)
  17948. var f = {
  17949. extend: $ ? $.extend : _extend,
  17950. deepExtend: _deepExtend,
  17951. each: $ ? $.each : _each,
  17952. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  17953. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  17954. detectLanguage: detectLanguage,
  17955. escape: _escape,
  17956. log: function(str) {
  17957. if (o.debug && typeof console !== "undefined") console.log(str);
  17958. },
  17959. error: function(str) {
  17960. if (typeof console !== "undefined") console.error(str);
  17961. },
  17962. getCountyIndexOfLng: function(lng) {
  17963. var lng_index = 0;
  17964. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  17965. return lng_index;
  17966. },
  17967. toLanguages: function(lng) {
  17968. var log = this.log;
  17969. function applyCase(l) {
  17970. var ret = l;
  17971. if (typeof l === 'string' && l.indexOf('-') > -1) {
  17972. var parts = l.split('-');
  17973. ret = o.lowerCaseLng ?
  17974. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17975. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17976. } else {
  17977. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  17978. }
  17979. return ret;
  17980. }
  17981. var languages = [];
  17982. var whitelist = o.lngWhitelist || false;
  17983. var addLanguage = function(language){
  17984. //reject langs not whitelisted
  17985. if(!whitelist || whitelist.indexOf(language) > -1){
  17986. languages.push(language);
  17987. }else{
  17988. log('rejecting non-whitelisted language: ' + language);
  17989. }
  17990. };
  17991. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  17992. var parts = lng.split('-');
  17993. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  17994. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  17995. } else {
  17996. addLanguage(applyCase(lng));
  17997. }
  17998. for (var i = 0; i < o.fallbackLng.length; i++) {
  17999. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18000. }
  18001. return languages;
  18002. },
  18003. regexEscape: function(str) {
  18004. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18005. },
  18006. regexReplacementEscape: function(strOrFn) {
  18007. if (typeof strOrFn === 'string') {
  18008. return strOrFn.replace(/\$/g, "$$$$");
  18009. } else {
  18010. return strOrFn;
  18011. }
  18012. },
  18013. localStorage: {
  18014. setItem: function(key, value) {
  18015. if (window.localStorage) {
  18016. try {
  18017. window.localStorage.setItem(key, value);
  18018. } catch (e) {
  18019. f.log('failed to set value for key "' + key + '" to localStorage.');
  18020. }
  18021. }
  18022. }
  18023. }
  18024. };
  18025. function init(options, cb) {
  18026. if (typeof options === 'function') {
  18027. cb = options;
  18028. options = {};
  18029. }
  18030. options = options || {};
  18031. // override defaults with passed in options
  18032. f.extend(o, options);
  18033. delete o.fixLng; /* passed in each time */
  18034. // override functions: .log(), .detectLanguage(), etc
  18035. if (o.functions) {
  18036. delete o.functions;
  18037. f.extend(f, options.functions);
  18038. }
  18039. // create namespace object if namespace is passed in as string
  18040. if (typeof o.ns == 'string') {
  18041. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18042. }
  18043. // fallback namespaces
  18044. if (typeof o.fallbackNS == 'string') {
  18045. o.fallbackNS = [o.fallbackNS];
  18046. }
  18047. // fallback languages
  18048. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18049. o.fallbackLng = [o.fallbackLng];
  18050. }
  18051. // escape prefix/suffix
  18052. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18053. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18054. if (!o.lng) o.lng = f.detectLanguage();
  18055. languages = f.toLanguages(o.lng);
  18056. currentLng = languages[0];
  18057. f.log('currentLng set to: ' + currentLng);
  18058. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18059. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18060. }
  18061. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18062. f.localStorage.setItem('i18next_lng', currentLng);
  18063. }
  18064. var lngTranslate = translate;
  18065. if (options.fixLng) {
  18066. lngTranslate = function(key, options) {
  18067. options = options || {};
  18068. options.lng = options.lng || lngTranslate.lng;
  18069. return translate(key, options);
  18070. };
  18071. lngTranslate.lng = currentLng;
  18072. }
  18073. pluralExtensions.setCurrentLng(currentLng);
  18074. // add JQuery extensions
  18075. if ($ && o.setJqueryExt) addJqueryFunct();
  18076. // jQuery deferred
  18077. var deferred;
  18078. if ($ && $.Deferred) {
  18079. deferred = $.Deferred();
  18080. }
  18081. // return immidiatly if res are passed in
  18082. if (o.resStore) {
  18083. resStore = o.resStore;
  18084. initialized = true;
  18085. if (cb) cb(lngTranslate);
  18086. if (deferred) deferred.resolve(lngTranslate);
  18087. if (deferred) return deferred.promise();
  18088. return;
  18089. }
  18090. // languages to load
  18091. var lngsToLoad = f.toLanguages(o.lng);
  18092. if (typeof o.preload === 'string') o.preload = [o.preload];
  18093. for (var i = 0, l = o.preload.length; i < l; i++) {
  18094. var pres = f.toLanguages(o.preload[i]);
  18095. for (var y = 0, len = pres.length; y < len; y++) {
  18096. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18097. lngsToLoad.push(pres[y]);
  18098. }
  18099. }
  18100. }
  18101. // else load them
  18102. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18103. resStore = store;
  18104. initialized = true;
  18105. if (cb) cb(lngTranslate);
  18106. if (deferred) deferred.resolve(lngTranslate);
  18107. });
  18108. if (deferred) return deferred.promise();
  18109. }
  18110. function preload(lngs, cb) {
  18111. if (typeof lngs === 'string') lngs = [lngs];
  18112. for (var i = 0, l = lngs.length; i < l; i++) {
  18113. if (o.preload.indexOf(lngs[i]) < 0) {
  18114. o.preload.push(lngs[i]);
  18115. }
  18116. }
  18117. return init(cb);
  18118. }
  18119. function addResourceBundle(lng, ns, resources, deep) {
  18120. if (typeof ns !== 'string') {
  18121. resources = ns;
  18122. ns = o.ns.defaultNs;
  18123. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18124. o.ns.namespaces.push(ns);
  18125. }
  18126. resStore[lng] = resStore[lng] || {};
  18127. resStore[lng][ns] = resStore[lng][ns] || {};
  18128. if (deep) {
  18129. f.deepExtend(resStore[lng][ns], resources);
  18130. } else {
  18131. f.extend(resStore[lng][ns], resources);
  18132. }
  18133. }
  18134. function hasResourceBundle(lng, ns) {
  18135. if (typeof ns !== 'string') {
  18136. ns = o.ns.defaultNs;
  18137. }
  18138. resStore[lng] = resStore[lng] || {};
  18139. var res = resStore[lng][ns] || {};
  18140. var hasValues = false;
  18141. for(var prop in res) {
  18142. if (res.hasOwnProperty(prop)) {
  18143. hasValues = true;
  18144. }
  18145. }
  18146. return hasValues;
  18147. }
  18148. function removeResourceBundle(lng, ns) {
  18149. if (typeof ns !== 'string') {
  18150. ns = o.ns.defaultNs;
  18151. }
  18152. resStore[lng] = resStore[lng] || {};
  18153. resStore[lng][ns] = {};
  18154. }
  18155. function addResource(lng, ns, key, value) {
  18156. if (typeof ns !== 'string') {
  18157. resource = ns;
  18158. ns = o.ns.defaultNs;
  18159. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18160. o.ns.namespaces.push(ns);
  18161. }
  18162. resStore[lng] = resStore[lng] || {};
  18163. resStore[lng][ns] = resStore[lng][ns] || {};
  18164. var keys = key.split(o.keyseparator);
  18165. var x = 0;
  18166. var node = resStore[lng][ns];
  18167. var origRef = node;
  18168. while (keys[x]) {
  18169. if (x == keys.length - 1)
  18170. node[keys[x]] = value;
  18171. else {
  18172. if (node[keys[x]] == null)
  18173. node[keys[x]] = {};
  18174. node = node[keys[x]];
  18175. }
  18176. x++;
  18177. }
  18178. }
  18179. function addResources(lng, ns, resources) {
  18180. if (typeof ns !== 'string') {
  18181. resource = ns;
  18182. ns = o.ns.defaultNs;
  18183. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18184. o.ns.namespaces.push(ns);
  18185. }
  18186. for (var m in resources) {
  18187. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18188. }
  18189. }
  18190. function setDefaultNamespace(ns) {
  18191. o.ns.defaultNs = ns;
  18192. }
  18193. function loadNamespace(namespace, cb) {
  18194. loadNamespaces([namespace], cb);
  18195. }
  18196. function loadNamespaces(namespaces, cb) {
  18197. var opts = {
  18198. dynamicLoad: o.dynamicLoad,
  18199. resGetPath: o.resGetPath,
  18200. getAsync: o.getAsync,
  18201. customLoad: o.customLoad,
  18202. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18203. };
  18204. // languages to load
  18205. var lngsToLoad = f.toLanguages(o.lng);
  18206. if (typeof o.preload === 'string') o.preload = [o.preload];
  18207. for (var i = 0, l = o.preload.length; i < l; i++) {
  18208. var pres = f.toLanguages(o.preload[i]);
  18209. for (var y = 0, len = pres.length; y < len; y++) {
  18210. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18211. lngsToLoad.push(pres[y]);
  18212. }
  18213. }
  18214. }
  18215. // check if we have to load
  18216. var lngNeedLoad = [];
  18217. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18218. var needLoad = false;
  18219. var resSet = resStore[lngsToLoad[a]];
  18220. if (resSet) {
  18221. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18222. if (!resSet[namespaces[b]]) needLoad = true;
  18223. }
  18224. } else {
  18225. needLoad = true;
  18226. }
  18227. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18228. }
  18229. if (lngNeedLoad.length) {
  18230. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18231. var todo = namespaces.length * lngNeedLoad.length;
  18232. // load each file individual
  18233. f.each(namespaces, function(nsIndex, nsValue) {
  18234. // append namespace to namespace array
  18235. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18236. o.ns.namespaces.push(nsValue);
  18237. }
  18238. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18239. resStore[lngValue] = resStore[lngValue] || {};
  18240. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18241. todo--; // wait for all done befor callback
  18242. if (todo === 0 && cb) {
  18243. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18244. cb();
  18245. }
  18246. });
  18247. });
  18248. });
  18249. } else {
  18250. if (cb) cb();
  18251. }
  18252. }
  18253. function setLng(lng, options, cb) {
  18254. if (typeof options === 'function') {
  18255. cb = options;
  18256. options = {};
  18257. } else if (!options) {
  18258. options = {};
  18259. }
  18260. options.lng = lng;
  18261. return init(options, cb);
  18262. }
  18263. function lng() {
  18264. return currentLng;
  18265. }
  18266. function reload(cb) {
  18267. resStore = {};
  18268. setLng(currentLng, cb);
  18269. }
  18270. function addJqueryFunct() {
  18271. // $.t shortcut
  18272. $.t = $.t || translate;
  18273. function parse(ele, key, options) {
  18274. if (key.length === 0) return;
  18275. var attr = 'text';
  18276. if (key.indexOf('[') === 0) {
  18277. var parts = key.split(']');
  18278. key = parts[1];
  18279. attr = parts[0].substr(1, parts[0].length-1);
  18280. }
  18281. if (key.indexOf(';') === key.length-1) {
  18282. key = key.substr(0, key.length-2);
  18283. }
  18284. var optionsToUse;
  18285. if (attr === 'html') {
  18286. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18287. ele.html($.t(key, optionsToUse));
  18288. } else if (attr === 'text') {
  18289. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18290. ele.text($.t(key, optionsToUse));
  18291. } else if (attr === 'prepend') {
  18292. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18293. ele.prepend($.t(key, optionsToUse));
  18294. } else if (attr === 'append') {
  18295. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18296. ele.append($.t(key, optionsToUse));
  18297. } else if (attr.indexOf("data-") === 0) {
  18298. var dataAttr = attr.substr(("data-").length);
  18299. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18300. var translated = $.t(key, optionsToUse);
  18301. //we change into the data cache
  18302. ele.data(dataAttr, translated);
  18303. //we change into the dom
  18304. ele.attr(attr, translated);
  18305. } else {
  18306. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18307. ele.attr(attr, $.t(key, optionsToUse));
  18308. }
  18309. }
  18310. function localize(ele, options) {
  18311. var key = ele.attr(o.selectorAttr);
  18312. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18313. if (!key) return;
  18314. var target = ele
  18315. , targetSelector = ele.data("i18n-target");
  18316. if (targetSelector) {
  18317. target = ele.find(targetSelector) || ele;
  18318. }
  18319. if (!options && o.useDataAttrOptions === true) {
  18320. options = ele.data("i18n-options");
  18321. }
  18322. options = options || {};
  18323. if (key.indexOf(';') >= 0) {
  18324. var keys = key.split(';');
  18325. $.each(keys, function(m, k) {
  18326. if (k !== '') parse(target, k, options);
  18327. });
  18328. } else {
  18329. parse(target, key, options);
  18330. }
  18331. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18332. }
  18333. // fn
  18334. $.fn.i18n = function (options) {
  18335. return this.each(function() {
  18336. // localize element itself
  18337. localize($(this), options);
  18338. // localize childs
  18339. var elements = $(this).find('[' + o.selectorAttr + ']');
  18340. elements.each(function() {
  18341. localize($(this), options);
  18342. });
  18343. });
  18344. };
  18345. }
  18346. function applyReplacement(str, replacementHash, nestedKey, options) {
  18347. if (!str) return str;
  18348. options = options || replacementHash; // first call uses replacement hash combined with options
  18349. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18350. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18351. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18352. , unEscapingSuffix = 'HTML'+suffix;
  18353. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18354. f.each(hash, function(key, value) {
  18355. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18356. if (typeof value === 'object' && value !== null) {
  18357. str = applyReplacement(str, value, nextKey, options);
  18358. } else {
  18359. if (options.escapeInterpolation || o.escapeInterpolation) {
  18360. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18361. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18362. } else {
  18363. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18364. }
  18365. // str = options.escapeInterpolation;
  18366. }
  18367. });
  18368. return str;
  18369. }
  18370. // append it to functions
  18371. f.applyReplacement = applyReplacement;
  18372. function applyReuse(translated, options) {
  18373. var comma = ',';
  18374. var options_open = '{';
  18375. var options_close = '}';
  18376. var opts = f.extend({}, options);
  18377. delete opts.postProcess;
  18378. while (translated.indexOf(o.reusePrefix) != -1) {
  18379. replacementCounter++;
  18380. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18381. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18382. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18383. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18384. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18385. if (index_of_end_of_closing <= index_of_opening) {
  18386. f.error('there is an missing closing in following translation value', translated);
  18387. return '';
  18388. }
  18389. if (token_without_symbols.indexOf(comma) != -1) {
  18390. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18391. 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) {
  18392. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18393. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18394. try {
  18395. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18396. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18397. } catch (e) {
  18398. }
  18399. }
  18400. }
  18401. var translated_token = _translate(token_without_symbols, opts);
  18402. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18403. }
  18404. return translated;
  18405. }
  18406. function hasContext(options) {
  18407. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18408. }
  18409. function needsPlural(options, lng) {
  18410. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18411. }
  18412. function needsIndefiniteArticle(options) {
  18413. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18414. }
  18415. function exists(key, options) {
  18416. options = options || {};
  18417. var notFound = _getDefaultValue(key, options)
  18418. , found = _find(key, options);
  18419. return found !== undefined || found === notFound;
  18420. }
  18421. function translate(key, options) {
  18422. options = options || {};
  18423. if (!initialized) {
  18424. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18425. return options.defaultValue || '';
  18426. };
  18427. replacementCounter = 0;
  18428. return _translate.apply(null, arguments);
  18429. }
  18430. function _getDefaultValue(key, options) {
  18431. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18432. }
  18433. function _injectSprintfProcessor() {
  18434. var values = [];
  18435. // mh: build array from second argument onwards
  18436. for (var i = 1; i < arguments.length; i++) {
  18437. values.push(arguments[i]);
  18438. }
  18439. return {
  18440. postProcess: 'sprintf',
  18441. sprintf: values
  18442. };
  18443. }
  18444. function _translate(potentialKeys, options) {
  18445. if (options && typeof options !== 'object') {
  18446. if (o.shortcutFunction === 'sprintf') {
  18447. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18448. options = _injectSprintfProcessor.apply(null, arguments);
  18449. } else if (o.shortcutFunction === 'defaultValue') {
  18450. options = {
  18451. defaultValue: options
  18452. }
  18453. }
  18454. } else {
  18455. options = options || {};
  18456. }
  18457. if (typeof o.defaultVariables === 'object') {
  18458. options = f.extend({}, o.defaultVariables, options);
  18459. }
  18460. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18461. if (typeof potentialKeys === 'string') {
  18462. potentialKeys = [potentialKeys];
  18463. }
  18464. var key = potentialKeys[0];
  18465. if (potentialKeys.length > 1) {
  18466. for (var i = 0; i < potentialKeys.length; i++) {
  18467. key = potentialKeys[i];
  18468. if (exists(key, options)) {
  18469. break;
  18470. }
  18471. }
  18472. }
  18473. var notFound = _getDefaultValue(key, options)
  18474. , found = _find(key, options)
  18475. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18476. , ns = options.ns || o.ns.defaultNs
  18477. , parts;
  18478. // split ns and key
  18479. if (key.indexOf(o.nsseparator) > -1) {
  18480. parts = key.split(o.nsseparator);
  18481. ns = parts[0];
  18482. key = parts[1];
  18483. }
  18484. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18485. if (options.lng) {
  18486. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18487. } else {
  18488. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18489. }
  18490. }
  18491. var postProcessor = options.postProcess || o.postProcess;
  18492. if (found !== undefined && postProcessor) {
  18493. if (postProcessors[postProcessor]) {
  18494. found = postProcessors[postProcessor](found, key, options);
  18495. }
  18496. }
  18497. // process notFound if function exists
  18498. var splitNotFound = notFound;
  18499. if (notFound.indexOf(o.nsseparator) > -1) {
  18500. parts = notFound.split(o.nsseparator);
  18501. splitNotFound = parts[1];
  18502. }
  18503. if (splitNotFound === key && o.parseMissingKey) {
  18504. notFound = o.parseMissingKey(notFound);
  18505. }
  18506. if (found === undefined) {
  18507. notFound = applyReplacement(notFound, options);
  18508. notFound = applyReuse(notFound, options);
  18509. if (postProcessor && postProcessors[postProcessor]) {
  18510. var val = _getDefaultValue(key, options);
  18511. found = postProcessors[postProcessor](val, key, options);
  18512. }
  18513. }
  18514. return (found !== undefined) ? found : notFound;
  18515. }
  18516. function _find(key, options) {
  18517. options = options || {};
  18518. var optionWithoutCount, translated
  18519. , notFound = _getDefaultValue(key, options)
  18520. , lngs = languages;
  18521. if (!resStore) { return notFound; } // no resStore to translate from
  18522. // CI mode
  18523. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18524. // passed in lng
  18525. if (options.lngs) lngs = options.lngs;
  18526. if (options.lng) {
  18527. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18528. if (!resStore[lngs[0]]) {
  18529. var oldAsync = o.getAsync;
  18530. o.getAsync = false;
  18531. i18n.sync.load(lngs, o, function(err, store) {
  18532. f.extend(resStore, store);
  18533. o.getAsync = oldAsync;
  18534. });
  18535. }
  18536. }
  18537. var ns = options.ns || o.ns.defaultNs;
  18538. if (key.indexOf(o.nsseparator) > -1) {
  18539. var parts = key.split(o.nsseparator);
  18540. ns = parts[0];
  18541. key = parts[1];
  18542. }
  18543. if (hasContext(options)) {
  18544. optionWithoutCount = f.extend({}, options);
  18545. delete optionWithoutCount.context;
  18546. optionWithoutCount.defaultValue = o.contextNotFound;
  18547. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18548. translated = translate(contextKey, optionWithoutCount);
  18549. if (translated != o.contextNotFound) {
  18550. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18551. } // else continue translation with original/nonContext key
  18552. }
  18553. if (needsPlural(options, lngs[0])) {
  18554. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18555. delete optionWithoutCount.count;
  18556. delete optionWithoutCount.lng;
  18557. optionWithoutCount.defaultValue = o.pluralNotFound;
  18558. var pluralKey;
  18559. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18560. pluralKey = ns + o.nsseparator + key;
  18561. } else {
  18562. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18563. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18564. if (pluralExtension >= 0) {
  18565. pluralKey = pluralKey + '_' + pluralExtension;
  18566. } else if (pluralExtension === 1) {
  18567. pluralKey = ns + o.nsseparator + key; // singular
  18568. }
  18569. }
  18570. translated = translate(pluralKey, optionWithoutCount);
  18571. if (translated != o.pluralNotFound) {
  18572. return applyReplacement(translated, {
  18573. count: options.count,
  18574. interpolationPrefix: options.interpolationPrefix,
  18575. interpolationSuffix: options.interpolationSuffix
  18576. }); // apply replacement for count only
  18577. } else if (lngs.length > 1) {
  18578. // remove failed lng
  18579. var clone = lngs.slice();
  18580. clone.shift();
  18581. options = f.extend(options, { lngs: clone });
  18582. delete options.lng;
  18583. // retry with fallbacks
  18584. translated = translate(ns + o.nsseparator + key, options);
  18585. if (translated != o.pluralNotFound) return translated;
  18586. } else {
  18587. return translated;
  18588. }
  18589. }
  18590. if (needsIndefiniteArticle(options)) {
  18591. var optionsWithoutIndef = f.extend({}, options);
  18592. delete optionsWithoutIndef.indefinite_article;
  18593. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18594. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18595. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18596. translated = translate(indefiniteKey, optionsWithoutIndef);
  18597. if (translated != o.indefiniteNotFound) {
  18598. return translated;
  18599. }
  18600. }
  18601. var found;
  18602. var keys = key.split(o.keyseparator);
  18603. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18604. if (found !== undefined) break;
  18605. var l = lngs[i];
  18606. var x = 0;
  18607. var value = resStore[l] && resStore[l][ns];
  18608. while (keys[x]) {
  18609. value = value && value[keys[x]];
  18610. x++;
  18611. }
  18612. if (value !== undefined) {
  18613. var valueType = Object.prototype.toString.apply(value);
  18614. if (typeof value === 'string') {
  18615. value = applyReplacement(value, options);
  18616. value = applyReuse(value, options);
  18617. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18618. value = value.join('\n');
  18619. value = applyReplacement(value, options);
  18620. value = applyReuse(value, options);
  18621. } else if (value === null && o.fallbackOnNull === true) {
  18622. value = undefined;
  18623. } else if (value !== null) {
  18624. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18625. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18626. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18627. } else {
  18628. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18629. 'returned an object instead of string.';
  18630. f.log(value);
  18631. }
  18632. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18633. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18634. f.each(value, function(m) {
  18635. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18636. });
  18637. value = copy;
  18638. }
  18639. }
  18640. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18641. value = undefined;
  18642. found = value;
  18643. }
  18644. }
  18645. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18646. // set flag for fallback lookup - avoid recursion
  18647. options.isFallbackLookup = true;
  18648. if (o.fallbackNS.length) {
  18649. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  18650. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  18651. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  18652. /* compare value without namespace */
  18653. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  18654. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  18655. if (foundValue !== notFoundValue) break;
  18656. }
  18657. }
  18658. } else {
  18659. found = _find(key, options); // fallback to default NS
  18660. }
  18661. options.isFallbackLookup = false;
  18662. }
  18663. return found;
  18664. }
  18665. function detectLanguage() {
  18666. var detectedLng;
  18667. var whitelist = o.lngWhitelist || [];
  18668. var userLngChoices = [];
  18669. // get from qs
  18670. var qsParm = [];
  18671. if (typeof window !== 'undefined') {
  18672. (function() {
  18673. var query = window.location.search.substring(1);
  18674. var params = query.split('&');
  18675. for (var i=0; i<params.length; i++) {
  18676. var pos = params[i].indexOf('=');
  18677. if (pos > 0) {
  18678. var key = params[i].substring(0,pos);
  18679. if (key == o.detectLngQS) {
  18680. userLngChoices.push(params[i].substring(pos+1));
  18681. }
  18682. }
  18683. }
  18684. })();
  18685. }
  18686. // get from cookie
  18687. if (o.useCookie && typeof document !== 'undefined') {
  18688. var c = f.cookie.read(o.cookieName);
  18689. if (c) userLngChoices.push(c);
  18690. }
  18691. // get from localStorage
  18692. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  18693. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  18694. }
  18695. // get from navigator
  18696. if (typeof navigator !== 'undefined') {
  18697. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  18698. for (var i=0;i<navigator.languages.length;i++) {
  18699. userLngChoices.push(navigator.languages[i]);
  18700. }
  18701. }
  18702. if (navigator.userLanguage) {
  18703. userLngChoices.push(navigator.userLanguage);
  18704. }
  18705. if (navigator.language) {
  18706. userLngChoices.push(navigator.language);
  18707. }
  18708. }
  18709. (function() {
  18710. for (var i=0;i<userLngChoices.length;i++) {
  18711. var lng = userLngChoices[i];
  18712. if (lng.indexOf('-') > -1) {
  18713. var parts = lng.split('-');
  18714. lng = o.lowerCaseLng ?
  18715. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18716. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18717. }
  18718. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  18719. detectedLng = lng;
  18720. break;
  18721. }
  18722. }
  18723. })();
  18724. //fallback
  18725. if (!detectedLng){
  18726. detectedLng = o.fallbackLng[0];
  18727. }
  18728. return detectedLng;
  18729. }
  18730. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  18731. /* [code, name, numbers, pluralsType] */
  18732. var _rules = [
  18733. ["ach", "Acholi", [1,2], 1],
  18734. ["af", "Afrikaans",[1,2], 2],
  18735. ["ak", "Akan", [1,2], 1],
  18736. ["am", "Amharic", [1,2], 1],
  18737. ["an", "Aragonese",[1,2], 2],
  18738. ["ar", "Arabic", [0,1,2,3,11,100],5],
  18739. ["arn", "Mapudungun",[1,2], 1],
  18740. ["ast", "Asturian", [1,2], 2],
  18741. ["ay", "Aymará", [1], 3],
  18742. ["az", "Azerbaijani",[1,2],2],
  18743. ["be", "Belarusian",[1,2,5],4],
  18744. ["bg", "Bulgarian",[1,2], 2],
  18745. ["bn", "Bengali", [1,2], 2],
  18746. ["bo", "Tibetan", [1], 3],
  18747. ["br", "Breton", [1,2], 1],
  18748. ["bs", "Bosnian", [1,2,5],4],
  18749. ["ca", "Catalan", [1,2], 2],
  18750. ["cgg", "Chiga", [1], 3],
  18751. ["cs", "Czech", [1,2,5],6],
  18752. ["csb", "Kashubian",[1,2,5],7],
  18753. ["cy", "Welsh", [1,2,3,8],8],
  18754. ["da", "Danish", [1,2], 2],
  18755. ["de", "German", [1,2], 2],
  18756. ["dev", "Development Fallback", [1,2], 2],
  18757. ["dz", "Dzongkha", [1], 3],
  18758. ["el", "Greek", [1,2], 2],
  18759. ["en", "English", [1,2], 2],
  18760. ["eo", "Esperanto",[1,2], 2],
  18761. ["es", "Spanish", [1,2], 2],
  18762. ["es_ar","Argentinean Spanish", [1,2], 2],
  18763. ["et", "Estonian", [1,2], 2],
  18764. ["eu", "Basque", [1,2], 2],
  18765. ["fa", "Persian", [1], 3],
  18766. ["fi", "Finnish", [1,2], 2],
  18767. ["fil", "Filipino", [1,2], 1],
  18768. ["fo", "Faroese", [1,2], 2],
  18769. ["fr", "French", [1,2], 9],
  18770. ["fur", "Friulian", [1,2], 2],
  18771. ["fy", "Frisian", [1,2], 2],
  18772. ["ga", "Irish", [1,2,3,7,11],10],
  18773. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  18774. ["gl", "Galician", [1,2], 2],
  18775. ["gu", "Gujarati", [1,2], 2],
  18776. ["gun", "Gun", [1,2], 1],
  18777. ["ha", "Hausa", [1,2], 2],
  18778. ["he", "Hebrew", [1,2], 2],
  18779. ["hi", "Hindi", [1,2], 2],
  18780. ["hr", "Croatian", [1,2,5],4],
  18781. ["hu", "Hungarian",[1,2], 2],
  18782. ["hy", "Armenian", [1,2], 2],
  18783. ["ia", "Interlingua",[1,2],2],
  18784. ["id", "Indonesian",[1], 3],
  18785. ["is", "Icelandic",[1,2], 12],
  18786. ["it", "Italian", [1,2], 2],
  18787. ["ja", "Japanese", [1], 3],
  18788. ["jbo", "Lojban", [1], 3],
  18789. ["jv", "Javanese", [0,1], 13],
  18790. ["ka", "Georgian", [1], 3],
  18791. ["kk", "Kazakh", [1], 3],
  18792. ["km", "Khmer", [1], 3],
  18793. ["kn", "Kannada", [1,2], 2],
  18794. ["ko", "Korean", [1], 3],
  18795. ["ku", "Kurdish", [1,2], 2],
  18796. ["kw", "Cornish", [1,2,3,4],14],
  18797. ["ky", "Kyrgyz", [1], 3],
  18798. ["lb", "Letzeburgesch",[1,2],2],
  18799. ["ln", "Lingala", [1,2], 1],
  18800. ["lo", "Lao", [1], 3],
  18801. ["lt", "Lithuanian",[1,2,10],15],
  18802. ["lv", "Latvian", [1,2,0],16],
  18803. ["mai", "Maithili", [1,2], 2],
  18804. ["mfe", "Mauritian Creole",[1,2],1],
  18805. ["mg", "Malagasy", [1,2], 1],
  18806. ["mi", "Maori", [1,2], 1],
  18807. ["mk", "Macedonian",[1,2],17],
  18808. ["ml", "Malayalam",[1,2], 2],
  18809. ["mn", "Mongolian",[1,2], 2],
  18810. ["mnk", "Mandinka", [0,1,2],18],
  18811. ["mr", "Marathi", [1,2], 2],
  18812. ["ms", "Malay", [1], 3],
  18813. ["mt", "Maltese", [1,2,11,20],19],
  18814. ["nah", "Nahuatl", [1,2], 2],
  18815. ["nap", "Neapolitan",[1,2], 2],
  18816. ["nb", "Norwegian Bokmal",[1,2],2],
  18817. ["ne", "Nepali", [1,2], 2],
  18818. ["nl", "Dutch", [1,2], 2],
  18819. ["nn", "Norwegian Nynorsk",[1,2],2],
  18820. ["no", "Norwegian",[1,2], 2],
  18821. ["nso", "Northern Sotho",[1,2],2],
  18822. ["oc", "Occitan", [1,2], 1],
  18823. ["or", "Oriya", [2,1], 2],
  18824. ["pa", "Punjabi", [1,2], 2],
  18825. ["pap", "Papiamento",[1,2], 2],
  18826. ["pl", "Polish", [1,2,5],7],
  18827. ["pms", "Piemontese",[1,2], 2],
  18828. ["ps", "Pashto", [1,2], 2],
  18829. ["pt", "Portuguese",[1,2], 2],
  18830. ["pt_br","Brazilian Portuguese",[1,2], 2],
  18831. ["rm", "Romansh", [1,2], 2],
  18832. ["ro", "Romanian", [1,2,20],20],
  18833. ["ru", "Russian", [1,2,5],4],
  18834. ["sah", "Yakut", [1], 3],
  18835. ["sco", "Scots", [1,2], 2],
  18836. ["se", "Northern Sami",[1,2], 2],
  18837. ["si", "Sinhala", [1,2], 2],
  18838. ["sk", "Slovak", [1,2,5],6],
  18839. ["sl", "Slovenian",[5,1,2,3],21],
  18840. ["so", "Somali", [1,2], 2],
  18841. ["son", "Songhay", [1,2], 2],
  18842. ["sq", "Albanian", [1,2], 2],
  18843. ["sr", "Serbian", [1,2,5],4],
  18844. ["su", "Sundanese",[1], 3],
  18845. ["sv", "Swedish", [1,2], 2],
  18846. ["sw", "Swahili", [1,2], 2],
  18847. ["ta", "Tamil", [1,2], 2],
  18848. ["te", "Telugu", [1,2], 2],
  18849. ["tg", "Tajik", [1,2], 1],
  18850. ["th", "Thai", [1], 3],
  18851. ["ti", "Tigrinya", [1,2], 1],
  18852. ["tk", "Turkmen", [1,2], 2],
  18853. ["tr", "Turkish", [1,2], 1],
  18854. ["tt", "Tatar", [1], 3],
  18855. ["ug", "Uyghur", [1], 3],
  18856. ["uk", "Ukrainian",[1,2,5],4],
  18857. ["ur", "Urdu", [1,2], 2],
  18858. ["uz", "Uzbek", [1,2], 1],
  18859. ["vi", "Vietnamese",[1], 3],
  18860. ["wa", "Walloon", [1,2], 1],
  18861. ["wo", "Wolof", [1], 3],
  18862. ["yo", "Yoruba", [1,2], 2],
  18863. ["zh", "Chinese", [1], 3]
  18864. ];
  18865. var _rulesPluralsTypes = {
  18866. 1: function(n) {return Number(n > 1);},
  18867. 2: function(n) {return Number(n != 1);},
  18868. 3: function(n) {return 0;},
  18869. 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);},
  18870. 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);},
  18871. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  18872. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18873. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  18874. 9: function(n) {return Number(n >= 2);},
  18875. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  18876. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  18877. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  18878. 13: function(n) {return Number(n !== 0);},
  18879. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  18880. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18881. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  18882. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  18883. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  18884. 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);},
  18885. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  18886. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  18887. };
  18888. var pluralExtensions = {
  18889. rules: (function () {
  18890. var l, rules = {};
  18891. for (l=_rules.length; l-- ;) {
  18892. rules[_rules[l][0]] = {
  18893. name: _rules[l][1],
  18894. numbers: _rules[l][2],
  18895. plurals: _rulesPluralsTypes[_rules[l][3]]
  18896. }
  18897. }
  18898. return rules;
  18899. }()),
  18900. // you can add your own pluralExtensions
  18901. addRule: function(lng, obj) {
  18902. pluralExtensions.rules[lng] = obj;
  18903. },
  18904. setCurrentLng: function(lng) {
  18905. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  18906. var parts = lng.split('-');
  18907. pluralExtensions.currentRule = {
  18908. lng: lng,
  18909. rule: pluralExtensions.rules[parts[0]]
  18910. };
  18911. }
  18912. },
  18913. needsPlural: function(lng, count) {
  18914. var parts = lng.split('-');
  18915. var ext;
  18916. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18917. ext = pluralExtensions.currentRule.rule;
  18918. } else {
  18919. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  18920. }
  18921. if (ext && ext.numbers.length <= 1) {
  18922. return false;
  18923. } else {
  18924. return this.get(lng, count) !== 1;
  18925. }
  18926. },
  18927. get: function(lng, count) {
  18928. var parts = lng.split('-');
  18929. function getResult(l, c) {
  18930. var ext;
  18931. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18932. ext = pluralExtensions.currentRule.rule;
  18933. } else {
  18934. ext = pluralExtensions.rules[l];
  18935. }
  18936. if (ext) {
  18937. var i;
  18938. if (ext.noAbs) {
  18939. i = ext.plurals(c);
  18940. } else {
  18941. i = ext.plurals(Math.abs(c));
  18942. }
  18943. var number = ext.numbers[i];
  18944. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  18945. if (number === 2) {
  18946. number = -1; // regular plural
  18947. } else if (number === 1) {
  18948. number = 1; // singular
  18949. }
  18950. }//console.log(count + '-' + number);
  18951. return number;
  18952. } else {
  18953. return c === 1 ? '1' : '-1';
  18954. }
  18955. }
  18956. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  18957. }
  18958. };
  18959. var postProcessors = {};
  18960. var addPostProcessor = function(name, fc) {
  18961. postProcessors[name] = fc;
  18962. };
  18963. // sprintf support
  18964. var sprintf = (function() {
  18965. function get_type(variable) {
  18966. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  18967. }
  18968. function str_repeat(input, multiplier) {
  18969. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  18970. return output.join('');
  18971. }
  18972. var str_format = function() {
  18973. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  18974. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  18975. }
  18976. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  18977. };
  18978. str_format.format = function(parse_tree, argv) {
  18979. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  18980. for (i = 0; i < tree_length; i++) {
  18981. node_type = get_type(parse_tree[i]);
  18982. if (node_type === 'string') {
  18983. output.push(parse_tree[i]);
  18984. }
  18985. else if (node_type === 'array') {
  18986. match = parse_tree[i]; // convenience purposes only
  18987. if (match[2]) { // keyword argument
  18988. arg = argv[cursor];
  18989. for (k = 0; k < match[2].length; k++) {
  18990. if (!arg.hasOwnProperty(match[2][k])) {
  18991. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  18992. }
  18993. arg = arg[match[2][k]];
  18994. }
  18995. }
  18996. else if (match[1]) { // positional argument (explicit)
  18997. arg = argv[match[1]];
  18998. }
  18999. else { // positional argument (implicit)
  19000. arg = argv[cursor++];
  19001. }
  19002. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19003. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19004. }
  19005. switch (match[8]) {
  19006. case 'b': arg = arg.toString(2); break;
  19007. case 'c': arg = String.fromCharCode(arg); break;
  19008. case 'd': arg = parseInt(arg, 10); break;
  19009. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19010. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19011. case 'o': arg = arg.toString(8); break;
  19012. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19013. case 'u': arg = Math.abs(arg); break;
  19014. case 'x': arg = arg.toString(16); break;
  19015. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19016. }
  19017. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19018. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19019. pad_length = match[6] - String(arg).length;
  19020. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19021. output.push(match[5] ? arg + pad : pad + arg);
  19022. }
  19023. }
  19024. return output.join('');
  19025. };
  19026. str_format.cache = {};
  19027. str_format.parse = function(fmt) {
  19028. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19029. while (_fmt) {
  19030. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19031. parse_tree.push(match[0]);
  19032. }
  19033. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19034. parse_tree.push('%');
  19035. }
  19036. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19037. if (match[2]) {
  19038. arg_names |= 1;
  19039. var field_list = [], replacement_field = match[2], field_match = [];
  19040. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19041. field_list.push(field_match[1]);
  19042. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19043. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19044. field_list.push(field_match[1]);
  19045. }
  19046. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19047. field_list.push(field_match[1]);
  19048. }
  19049. else {
  19050. throw('[sprintf] huh?');
  19051. }
  19052. }
  19053. }
  19054. else {
  19055. throw('[sprintf] huh?');
  19056. }
  19057. match[2] = field_list;
  19058. }
  19059. else {
  19060. arg_names |= 2;
  19061. }
  19062. if (arg_names === 3) {
  19063. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19064. }
  19065. parse_tree.push(match);
  19066. }
  19067. else {
  19068. throw('[sprintf] huh?');
  19069. }
  19070. _fmt = _fmt.substring(match[0].length);
  19071. }
  19072. return parse_tree;
  19073. };
  19074. return str_format;
  19075. })();
  19076. var vsprintf = function(fmt, argv) {
  19077. argv.unshift(fmt);
  19078. return sprintf.apply(null, argv);
  19079. };
  19080. addPostProcessor("sprintf", function(val, key, opts) {
  19081. if (!opts.sprintf) return val;
  19082. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19083. return vsprintf(val, opts.sprintf);
  19084. } else if (typeof opts.sprintf === 'object') {
  19085. return sprintf(val, opts.sprintf);
  19086. }
  19087. return val;
  19088. });
  19089. // public api interface
  19090. i18n.init = init;
  19091. i18n.setLng = setLng;
  19092. i18n.preload = preload;
  19093. i18n.addResourceBundle = addResourceBundle;
  19094. i18n.hasResourceBundle = hasResourceBundle;
  19095. i18n.addResource = addResource;
  19096. i18n.addResources = addResources;
  19097. i18n.removeResourceBundle = removeResourceBundle;
  19098. i18n.loadNamespace = loadNamespace;
  19099. i18n.loadNamespaces = loadNamespaces;
  19100. i18n.setDefaultNamespace = setDefaultNamespace;
  19101. i18n.t = translate;
  19102. i18n.translate = translate;
  19103. i18n.exists = exists;
  19104. i18n.detectLanguage = f.detectLanguage;
  19105. i18n.pluralExtensions = pluralExtensions;
  19106. i18n.sync = sync;
  19107. i18n.functions = f;
  19108. i18n.lng = lng;
  19109. i18n.addPostProcessor = addPostProcessor;
  19110. i18n.options = o;
  19111. })();
  19112. },{"jquery":"jquery"}],69:[function(require,module,exports){
  19113. // Top level file is just a mixin of submodules & constants
  19114. 'use strict';
  19115. var assign = require('./lib/utils/common').assign;
  19116. var deflate = require('./lib/deflate');
  19117. var inflate = require('./lib/inflate');
  19118. var constants = require('./lib/zlib/constants');
  19119. var pako = {};
  19120. assign(pako, deflate, inflate, constants);
  19121. module.exports = pako;
  19122. },{"./lib/deflate":70,"./lib/inflate":71,"./lib/utils/common":72,"./lib/zlib/constants":75}],70:[function(require,module,exports){
  19123. 'use strict';
  19124. var zlib_deflate = require('./zlib/deflate.js');
  19125. var utils = require('./utils/common');
  19126. var strings = require('./utils/strings');
  19127. var msg = require('./zlib/messages');
  19128. var zstream = require('./zlib/zstream');
  19129. var toString = Object.prototype.toString;
  19130. /* Public constants ==========================================================*/
  19131. /* ===========================================================================*/
  19132. var Z_NO_FLUSH = 0;
  19133. var Z_FINISH = 4;
  19134. var Z_OK = 0;
  19135. var Z_STREAM_END = 1;
  19136. var Z_SYNC_FLUSH = 2;
  19137. var Z_DEFAULT_COMPRESSION = -1;
  19138. var Z_DEFAULT_STRATEGY = 0;
  19139. var Z_DEFLATED = 8;
  19140. /* ===========================================================================*/
  19141. /**
  19142. * class Deflate
  19143. *
  19144. * Generic JS-style wrapper for zlib calls. If you don't need
  19145. * streaming behaviour - use more simple functions: [[deflate]],
  19146. * [[deflateRaw]] and [[gzip]].
  19147. **/
  19148. /* internal
  19149. * Deflate.chunks -> Array
  19150. *
  19151. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19152. **/
  19153. /**
  19154. * Deflate.result -> Uint8Array|Array
  19155. *
  19156. * Compressed result, generated by default [[Deflate#onData]]
  19157. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19158. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19159. * push a chunk with explicit flush (call [[Deflate#push]] with
  19160. * `Z_SYNC_FLUSH` param).
  19161. **/
  19162. /**
  19163. * Deflate.err -> Number
  19164. *
  19165. * Error code after deflate finished. 0 (Z_OK) on success.
  19166. * You will not need it in real life, because deflate errors
  19167. * are possible only on wrong options or bad `onData` / `onEnd`
  19168. * custom handlers.
  19169. **/
  19170. /**
  19171. * Deflate.msg -> String
  19172. *
  19173. * Error message, if [[Deflate.err]] != 0
  19174. **/
  19175. /**
  19176. * new Deflate(options)
  19177. * - options (Object): zlib deflate options.
  19178. *
  19179. * Creates new deflator instance with specified params. Throws exception
  19180. * on bad params. Supported options:
  19181. *
  19182. * - `level`
  19183. * - `windowBits`
  19184. * - `memLevel`
  19185. * - `strategy`
  19186. *
  19187. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19188. * for more information on these.
  19189. *
  19190. * Additional options, for internal needs:
  19191. *
  19192. * - `chunkSize` - size of generated data chunks (16K by default)
  19193. * - `raw` (Boolean) - do raw deflate
  19194. * - `gzip` (Boolean) - create gzip wrapper
  19195. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19196. * (each char code [0..255])
  19197. * - `header` (Object) - custom header for gzip
  19198. * - `text` (Boolean) - true if compressed data believed to be text
  19199. * - `time` (Number) - modification time, unix timestamp
  19200. * - `os` (Number) - operation system code
  19201. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19202. * - `name` (String) - file name (binary string)
  19203. * - `comment` (String) - comment (binary string)
  19204. * - `hcrc` (Boolean) - true if header crc should be added
  19205. *
  19206. * ##### Example:
  19207. *
  19208. * ```javascript
  19209. * var pako = require('pako')
  19210. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19211. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19212. *
  19213. * var deflate = new pako.Deflate({ level: 3});
  19214. *
  19215. * deflate.push(chunk1, false);
  19216. * deflate.push(chunk2, true); // true -> last chunk
  19217. *
  19218. * if (deflate.err) { throw new Error(deflate.err); }
  19219. *
  19220. * console.log(deflate.result);
  19221. * ```
  19222. **/
  19223. var Deflate = function(options) {
  19224. this.options = utils.assign({
  19225. level: Z_DEFAULT_COMPRESSION,
  19226. method: Z_DEFLATED,
  19227. chunkSize: 16384,
  19228. windowBits: 15,
  19229. memLevel: 8,
  19230. strategy: Z_DEFAULT_STRATEGY,
  19231. to: ''
  19232. }, options || {});
  19233. var opt = this.options;
  19234. if (opt.raw && (opt.windowBits > 0)) {
  19235. opt.windowBits = -opt.windowBits;
  19236. }
  19237. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19238. opt.windowBits += 16;
  19239. }
  19240. this.err = 0; // error code, if happens (0 = Z_OK)
  19241. this.msg = ''; // error message
  19242. this.ended = false; // used to avoid multiple onEnd() calls
  19243. this.chunks = []; // chunks of compressed data
  19244. this.strm = new zstream();
  19245. this.strm.avail_out = 0;
  19246. var status = zlib_deflate.deflateInit2(
  19247. this.strm,
  19248. opt.level,
  19249. opt.method,
  19250. opt.windowBits,
  19251. opt.memLevel,
  19252. opt.strategy
  19253. );
  19254. if (status !== Z_OK) {
  19255. throw new Error(msg[status]);
  19256. }
  19257. if (opt.header) {
  19258. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19259. }
  19260. };
  19261. /**
  19262. * Deflate#push(data[, mode]) -> Boolean
  19263. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19264. * converted to utf8 byte sequence.
  19265. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19266. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19267. *
  19268. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19269. * new compressed chunks. Returns `true` on success. The last data block must have
  19270. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19271. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19272. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19273. *
  19274. * On fail call [[Deflate#onEnd]] with error code and return false.
  19275. *
  19276. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19277. * array format is detected automatically). Also, don't skip last param and always
  19278. * use the same type in your code (boolean or number). That will improve JS speed.
  19279. *
  19280. * For regular `Array`-s make sure all elements are [0..255].
  19281. *
  19282. * ##### Example
  19283. *
  19284. * ```javascript
  19285. * push(chunk, false); // push one of data chunks
  19286. * ...
  19287. * push(chunk, true); // push last chunk
  19288. * ```
  19289. **/
  19290. Deflate.prototype.push = function(data, mode) {
  19291. var strm = this.strm;
  19292. var chunkSize = this.options.chunkSize;
  19293. var status, _mode;
  19294. if (this.ended) { return false; }
  19295. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19296. // Convert data if needed
  19297. if (typeof data === 'string') {
  19298. // If we need to compress text, change encoding to utf8.
  19299. strm.input = strings.string2buf(data);
  19300. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19301. strm.input = new Uint8Array(data);
  19302. } else {
  19303. strm.input = data;
  19304. }
  19305. strm.next_in = 0;
  19306. strm.avail_in = strm.input.length;
  19307. do {
  19308. if (strm.avail_out === 0) {
  19309. strm.output = new utils.Buf8(chunkSize);
  19310. strm.next_out = 0;
  19311. strm.avail_out = chunkSize;
  19312. }
  19313. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19314. if (status !== Z_STREAM_END && status !== Z_OK) {
  19315. this.onEnd(status);
  19316. this.ended = true;
  19317. return false;
  19318. }
  19319. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19320. if (this.options.to === 'string') {
  19321. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19322. } else {
  19323. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19324. }
  19325. }
  19326. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19327. // Finalize on the last chunk.
  19328. if (_mode === Z_FINISH) {
  19329. status = zlib_deflate.deflateEnd(this.strm);
  19330. this.onEnd(status);
  19331. this.ended = true;
  19332. return status === Z_OK;
  19333. }
  19334. // callback interim results if Z_SYNC_FLUSH.
  19335. if (_mode === Z_SYNC_FLUSH) {
  19336. this.onEnd(Z_OK);
  19337. strm.avail_out = 0;
  19338. return true;
  19339. }
  19340. return true;
  19341. };
  19342. /**
  19343. * Deflate#onData(chunk) -> Void
  19344. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19345. * on js engine support. When string output requested, each chunk
  19346. * will be string.
  19347. *
  19348. * By default, stores data blocks in `chunks[]` property and glue
  19349. * those in `onEnd`. Override this handler, if you need another behaviour.
  19350. **/
  19351. Deflate.prototype.onData = function(chunk) {
  19352. this.chunks.push(chunk);
  19353. };
  19354. /**
  19355. * Deflate#onEnd(status) -> Void
  19356. * - status (Number): deflate status. 0 (Z_OK) on success,
  19357. * other if not.
  19358. *
  19359. * Called once after you tell deflate that the input stream is
  19360. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19361. * or if an error happened. By default - join collected chunks,
  19362. * free memory and fill `results` / `err` properties.
  19363. **/
  19364. Deflate.prototype.onEnd = function(status) {
  19365. // On success - join
  19366. if (status === Z_OK) {
  19367. if (this.options.to === 'string') {
  19368. this.result = this.chunks.join('');
  19369. } else {
  19370. this.result = utils.flattenChunks(this.chunks);
  19371. }
  19372. }
  19373. this.chunks = [];
  19374. this.err = status;
  19375. this.msg = this.strm.msg;
  19376. };
  19377. /**
  19378. * deflate(data[, options]) -> Uint8Array|Array|String
  19379. * - data (Uint8Array|Array|String): input data to compress.
  19380. * - options (Object): zlib deflate options.
  19381. *
  19382. * Compress `data` with deflate alrorythm and `options`.
  19383. *
  19384. * Supported options are:
  19385. *
  19386. * - level
  19387. * - windowBits
  19388. * - memLevel
  19389. * - strategy
  19390. *
  19391. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19392. * for more information on these.
  19393. *
  19394. * Sugar (options):
  19395. *
  19396. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19397. * negative windowBits implicitly.
  19398. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19399. * (each char code [0..255])
  19400. *
  19401. * ##### Example:
  19402. *
  19403. * ```javascript
  19404. * var pako = require('pako')
  19405. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19406. *
  19407. * console.log(pako.deflate(data));
  19408. * ```
  19409. **/
  19410. function deflate(input, options) {
  19411. var deflator = new Deflate(options);
  19412. deflator.push(input, true);
  19413. // That will never happens, if you don't cheat with options :)
  19414. if (deflator.err) { throw deflator.msg; }
  19415. return deflator.result;
  19416. }
  19417. /**
  19418. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19419. * - data (Uint8Array|Array|String): input data to compress.
  19420. * - options (Object): zlib deflate options.
  19421. *
  19422. * The same as [[deflate]], but creates raw data, without wrapper
  19423. * (header and adler32 crc).
  19424. **/
  19425. function deflateRaw(input, options) {
  19426. options = options || {};
  19427. options.raw = true;
  19428. return deflate(input, options);
  19429. }
  19430. /**
  19431. * gzip(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 create gzip wrapper instead of
  19436. * deflate one.
  19437. **/
  19438. function gzip(input, options) {
  19439. options = options || {};
  19440. options.gzip = true;
  19441. return deflate(input, options);
  19442. }
  19443. exports.Deflate = Deflate;
  19444. exports.deflate = deflate;
  19445. exports.deflateRaw = deflateRaw;
  19446. exports.gzip = gzip;
  19447. },{"./utils/common":72,"./utils/strings":73,"./zlib/deflate.js":77,"./zlib/messages":82,"./zlib/zstream":84}],71:[function(require,module,exports){
  19448. 'use strict';
  19449. var zlib_inflate = require('./zlib/inflate.js');
  19450. var utils = require('./utils/common');
  19451. var strings = require('./utils/strings');
  19452. var c = require('./zlib/constants');
  19453. var msg = require('./zlib/messages');
  19454. var zstream = require('./zlib/zstream');
  19455. var gzheader = require('./zlib/gzheader');
  19456. var toString = Object.prototype.toString;
  19457. /**
  19458. * class Inflate
  19459. *
  19460. * Generic JS-style wrapper for zlib calls. If you don't need
  19461. * streaming behaviour - use more simple functions: [[inflate]]
  19462. * and [[inflateRaw]].
  19463. **/
  19464. /* internal
  19465. * inflate.chunks -> Array
  19466. *
  19467. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19468. **/
  19469. /**
  19470. * Inflate.result -> Uint8Array|Array|String
  19471. *
  19472. * Uncompressed result, generated by default [[Inflate#onData]]
  19473. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19474. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19475. * push a chunk with explicit flush (call [[Inflate#push]] with
  19476. * `Z_SYNC_FLUSH` param).
  19477. **/
  19478. /**
  19479. * Inflate.err -> Number
  19480. *
  19481. * Error code after inflate finished. 0 (Z_OK) on success.
  19482. * Should be checked if broken data possible.
  19483. **/
  19484. /**
  19485. * Inflate.msg -> String
  19486. *
  19487. * Error message, if [[Inflate.err]] != 0
  19488. **/
  19489. /**
  19490. * new Inflate(options)
  19491. * - options (Object): zlib inflate options.
  19492. *
  19493. * Creates new inflator instance with specified params. Throws exception
  19494. * on bad params. Supported options:
  19495. *
  19496. * - `windowBits`
  19497. *
  19498. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19499. * for more information on these.
  19500. *
  19501. * Additional options, for internal needs:
  19502. *
  19503. * - `chunkSize` - size of generated data chunks (16K by default)
  19504. * - `raw` (Boolean) - do raw inflate
  19505. * - `to` (String) - if equal to 'string', then result will be converted
  19506. * from utf8 to utf16 (javascript) string. When string output requested,
  19507. * chunk length can differ from `chunkSize`, depending on content.
  19508. *
  19509. * By default, when no options set, autodetect deflate/gzip data format via
  19510. * wrapper header.
  19511. *
  19512. * ##### Example:
  19513. *
  19514. * ```javascript
  19515. * var pako = require('pako')
  19516. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19517. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19518. *
  19519. * var inflate = new pako.Inflate({ level: 3});
  19520. *
  19521. * inflate.push(chunk1, false);
  19522. * inflate.push(chunk2, true); // true -> last chunk
  19523. *
  19524. * if (inflate.err) { throw new Error(inflate.err); }
  19525. *
  19526. * console.log(inflate.result);
  19527. * ```
  19528. **/
  19529. var Inflate = function(options) {
  19530. this.options = utils.assign({
  19531. chunkSize: 16384,
  19532. windowBits: 0,
  19533. to: ''
  19534. }, options || {});
  19535. var opt = this.options;
  19536. // Force window size for `raw` data, if not set directly,
  19537. // because we have no header for autodetect.
  19538. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19539. opt.windowBits = -opt.windowBits;
  19540. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19541. }
  19542. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19543. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19544. !(options && options.windowBits)) {
  19545. opt.windowBits += 32;
  19546. }
  19547. // Gzip header has no info about windows size, we can do autodetect only
  19548. // for deflate. So, if window size not set, force it to max when gzip possible
  19549. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19550. // bit 3 (16) -> gzipped data
  19551. // bit 4 (32) -> autodetect gzip/deflate
  19552. if ((opt.windowBits & 15) === 0) {
  19553. opt.windowBits |= 15;
  19554. }
  19555. }
  19556. this.err = 0; // error code, if happens (0 = Z_OK)
  19557. this.msg = ''; // error message
  19558. this.ended = false; // used to avoid multiple onEnd() calls
  19559. this.chunks = []; // chunks of compressed data
  19560. this.strm = new zstream();
  19561. this.strm.avail_out = 0;
  19562. var status = zlib_inflate.inflateInit2(
  19563. this.strm,
  19564. opt.windowBits
  19565. );
  19566. if (status !== c.Z_OK) {
  19567. throw new Error(msg[status]);
  19568. }
  19569. this.header = new gzheader();
  19570. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19571. };
  19572. /**
  19573. * Inflate#push(data[, mode]) -> Boolean
  19574. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19575. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19576. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19577. *
  19578. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19579. * new output chunks. Returns `true` on success. The last data block must have
  19580. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19581. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19582. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  19583. *
  19584. * On fail call [[Inflate#onEnd]] with error code and return false.
  19585. *
  19586. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19587. * format is detected automatically). Also, don't skip last param and always
  19588. * use the same type in your code (boolean or number). That will improve JS speed.
  19589. *
  19590. * For regular `Array`-s make sure all elements are [0..255].
  19591. *
  19592. * ##### Example
  19593. *
  19594. * ```javascript
  19595. * push(chunk, false); // push one of data chunks
  19596. * ...
  19597. * push(chunk, true); // push last chunk
  19598. * ```
  19599. **/
  19600. Inflate.prototype.push = function(data, mode) {
  19601. var strm = this.strm;
  19602. var chunkSize = this.options.chunkSize;
  19603. var status, _mode;
  19604. var next_out_utf8, tail, utf8str;
  19605. if (this.ended) { return false; }
  19606. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19607. // Convert data if needed
  19608. if (typeof data === 'string') {
  19609. // Only binary strings can be decompressed on practice
  19610. strm.input = strings.binstring2buf(data);
  19611. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19612. strm.input = new Uint8Array(data);
  19613. } else {
  19614. strm.input = data;
  19615. }
  19616. strm.next_in = 0;
  19617. strm.avail_in = strm.input.length;
  19618. do {
  19619. if (strm.avail_out === 0) {
  19620. strm.output = new utils.Buf8(chunkSize);
  19621. strm.next_out = 0;
  19622. strm.avail_out = chunkSize;
  19623. }
  19624. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19625. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19626. this.onEnd(status);
  19627. this.ended = true;
  19628. return false;
  19629. }
  19630. if (strm.next_out) {
  19631. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  19632. if (this.options.to === 'string') {
  19633. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19634. tail = strm.next_out - next_out_utf8;
  19635. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19636. // move tail
  19637. strm.next_out = tail;
  19638. strm.avail_out = chunkSize - tail;
  19639. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19640. this.onData(utf8str);
  19641. } else {
  19642. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19643. }
  19644. }
  19645. }
  19646. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19647. if (status === c.Z_STREAM_END) {
  19648. _mode = c.Z_FINISH;
  19649. }
  19650. // Finalize on the last chunk.
  19651. if (_mode === c.Z_FINISH) {
  19652. status = zlib_inflate.inflateEnd(this.strm);
  19653. this.onEnd(status);
  19654. this.ended = true;
  19655. return status === c.Z_OK;
  19656. }
  19657. // callback interim results if Z_SYNC_FLUSH.
  19658. if (_mode === c.Z_SYNC_FLUSH) {
  19659. this.onEnd(c.Z_OK);
  19660. strm.avail_out = 0;
  19661. return true;
  19662. }
  19663. return true;
  19664. };
  19665. /**
  19666. * Inflate#onData(chunk) -> Void
  19667. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19668. * on js engine support. When string output requested, each chunk
  19669. * will be string.
  19670. *
  19671. * By default, stores data blocks in `chunks[]` property and glue
  19672. * those in `onEnd`. Override this handler, if you need another behaviour.
  19673. **/
  19674. Inflate.prototype.onData = function(chunk) {
  19675. this.chunks.push(chunk);
  19676. };
  19677. /**
  19678. * Inflate#onEnd(status) -> Void
  19679. * - status (Number): inflate status. 0 (Z_OK) on success,
  19680. * other if not.
  19681. *
  19682. * Called either after you tell inflate that the input stream is
  19683. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19684. * or if an error happened. By default - join collected chunks,
  19685. * free memory and fill `results` / `err` properties.
  19686. **/
  19687. Inflate.prototype.onEnd = function(status) {
  19688. // On success - join
  19689. if (status === c.Z_OK) {
  19690. if (this.options.to === 'string') {
  19691. // Glue & convert here, until we teach pako to send
  19692. // utf8 alligned strings to onData
  19693. this.result = this.chunks.join('');
  19694. } else {
  19695. this.result = utils.flattenChunks(this.chunks);
  19696. }
  19697. }
  19698. this.chunks = [];
  19699. this.err = status;
  19700. this.msg = this.strm.msg;
  19701. };
  19702. /**
  19703. * inflate(data[, options]) -> Uint8Array|Array|String
  19704. * - data (Uint8Array|Array|String): input data to decompress.
  19705. * - options (Object): zlib inflate options.
  19706. *
  19707. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19708. * format via wrapper header by default. That's why we don't provide
  19709. * separate `ungzip` method.
  19710. *
  19711. * Supported options are:
  19712. *
  19713. * - windowBits
  19714. *
  19715. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19716. * for more information.
  19717. *
  19718. * Sugar (options):
  19719. *
  19720. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19721. * negative windowBits implicitly.
  19722. * - `to` (String) - if equal to 'string', then result will be converted
  19723. * from utf8 to utf16 (javascript) string. When string output requested,
  19724. * chunk length can differ from `chunkSize`, depending on content.
  19725. *
  19726. *
  19727. * ##### Example:
  19728. *
  19729. * ```javascript
  19730. * var pako = require('pako')
  19731. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19732. * , output;
  19733. *
  19734. * try {
  19735. * output = pako.inflate(input);
  19736. * } catch (err)
  19737. * console.log(err);
  19738. * }
  19739. * ```
  19740. **/
  19741. function inflate(input, options) {
  19742. var inflator = new Inflate(options);
  19743. inflator.push(input, true);
  19744. // That will never happens, if you don't cheat with options :)
  19745. if (inflator.err) { throw inflator.msg; }
  19746. return inflator.result;
  19747. }
  19748. /**
  19749. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19750. * - data (Uint8Array|Array|String): input data to decompress.
  19751. * - options (Object): zlib inflate options.
  19752. *
  19753. * The same as [[inflate]], but creates raw data, without wrapper
  19754. * (header and adler32 crc).
  19755. **/
  19756. function inflateRaw(input, options) {
  19757. options = options || {};
  19758. options.raw = true;
  19759. return inflate(input, options);
  19760. }
  19761. /**
  19762. * ungzip(data[, options]) -> Uint8Array|Array|String
  19763. * - data (Uint8Array|Array|String): input data to decompress.
  19764. * - options (Object): zlib inflate options.
  19765. *
  19766. * Just shortcut to [[inflate]], because it autodetects format
  19767. * by header.content. Done for convenience.
  19768. **/
  19769. exports.Inflate = Inflate;
  19770. exports.inflate = inflate;
  19771. exports.inflateRaw = inflateRaw;
  19772. exports.ungzip = inflate;
  19773. },{"./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){
  19774. 'use strict';
  19775. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19776. (typeof Uint16Array !== 'undefined') &&
  19777. (typeof Int32Array !== 'undefined');
  19778. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19779. var sources = Array.prototype.slice.call(arguments, 1);
  19780. while (sources.length) {
  19781. var source = sources.shift();
  19782. if (!source) { continue; }
  19783. if (typeof source !== 'object') {
  19784. throw new TypeError(source + 'must be non-object');
  19785. }
  19786. for (var p in source) {
  19787. if (source.hasOwnProperty(p)) {
  19788. obj[p] = source[p];
  19789. }
  19790. }
  19791. }
  19792. return obj;
  19793. };
  19794. // reduce buffer size, avoiding mem copy
  19795. exports.shrinkBuf = function (buf, size) {
  19796. if (buf.length === size) { return buf; }
  19797. if (buf.subarray) { return buf.subarray(0, size); }
  19798. buf.length = size;
  19799. return buf;
  19800. };
  19801. var fnTyped = {
  19802. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19803. if (src.subarray && dest.subarray) {
  19804. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19805. return;
  19806. }
  19807. // Fallback to ordinary array
  19808. for (var i=0; i<len; i++) {
  19809. dest[dest_offs + i] = src[src_offs + i];
  19810. }
  19811. },
  19812. // Join array of chunks to single array.
  19813. flattenChunks: function(chunks) {
  19814. var i, l, len, pos, chunk, result;
  19815. // calculate data length
  19816. len = 0;
  19817. for (i=0, l=chunks.length; i<l; i++) {
  19818. len += chunks[i].length;
  19819. }
  19820. // join chunks
  19821. result = new Uint8Array(len);
  19822. pos = 0;
  19823. for (i=0, l=chunks.length; i<l; i++) {
  19824. chunk = chunks[i];
  19825. result.set(chunk, pos);
  19826. pos += chunk.length;
  19827. }
  19828. return result;
  19829. }
  19830. };
  19831. var fnUntyped = {
  19832. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19833. for (var i=0; i<len; i++) {
  19834. dest[dest_offs + i] = src[src_offs + i];
  19835. }
  19836. },
  19837. // Join array of chunks to single array.
  19838. flattenChunks: function(chunks) {
  19839. return [].concat.apply([], chunks);
  19840. }
  19841. };
  19842. // Enable/Disable typed arrays use, for testing
  19843. //
  19844. exports.setTyped = function (on) {
  19845. if (on) {
  19846. exports.Buf8 = Uint8Array;
  19847. exports.Buf16 = Uint16Array;
  19848. exports.Buf32 = Int32Array;
  19849. exports.assign(exports, fnTyped);
  19850. } else {
  19851. exports.Buf8 = Array;
  19852. exports.Buf16 = Array;
  19853. exports.Buf32 = Array;
  19854. exports.assign(exports, fnUntyped);
  19855. }
  19856. };
  19857. exports.setTyped(TYPED_OK);
  19858. },{}],73:[function(require,module,exports){
  19859. // String encode/decode helpers
  19860. 'use strict';
  19861. var utils = require('./common');
  19862. // Quick check if we can use fast array to bin string conversion
  19863. //
  19864. // - apply(Array) can fail on Android 2.2
  19865. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19866. //
  19867. var STR_APPLY_OK = true;
  19868. var STR_APPLY_UIA_OK = true;
  19869. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19870. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  19871. // Table with utf8 lengths (calculated by first byte of sequence)
  19872. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  19873. // because max possible codepoint is 0x10ffff
  19874. var _utf8len = new utils.Buf8(256);
  19875. for (var q=0; q<256; q++) {
  19876. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  19877. }
  19878. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  19879. // convert string to array (typed, when possible)
  19880. exports.string2buf = function (str) {
  19881. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  19882. // count binary size
  19883. for (m_pos = 0; m_pos < str_len; m_pos++) {
  19884. c = str.charCodeAt(m_pos);
  19885. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19886. c2 = str.charCodeAt(m_pos+1);
  19887. if ((c2 & 0xfc00) === 0xdc00) {
  19888. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19889. m_pos++;
  19890. }
  19891. }
  19892. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  19893. }
  19894. // allocate buffer
  19895. buf = new utils.Buf8(buf_len);
  19896. // convert
  19897. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  19898. c = str.charCodeAt(m_pos);
  19899. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19900. c2 = str.charCodeAt(m_pos+1);
  19901. if ((c2 & 0xfc00) === 0xdc00) {
  19902. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19903. m_pos++;
  19904. }
  19905. }
  19906. if (c < 0x80) {
  19907. /* one byte */
  19908. buf[i++] = c;
  19909. } else if (c < 0x800) {
  19910. /* two bytes */
  19911. buf[i++] = 0xC0 | (c >>> 6);
  19912. buf[i++] = 0x80 | (c & 0x3f);
  19913. } else if (c < 0x10000) {
  19914. /* three bytes */
  19915. buf[i++] = 0xE0 | (c >>> 12);
  19916. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19917. buf[i++] = 0x80 | (c & 0x3f);
  19918. } else {
  19919. /* four bytes */
  19920. buf[i++] = 0xf0 | (c >>> 18);
  19921. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  19922. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19923. buf[i++] = 0x80 | (c & 0x3f);
  19924. }
  19925. }
  19926. return buf;
  19927. };
  19928. // Helper (used in 2 places)
  19929. function buf2binstring(buf, len) {
  19930. // use fallback for big arrays to avoid stack overflow
  19931. if (len < 65537) {
  19932. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  19933. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  19934. }
  19935. }
  19936. var result = '';
  19937. for (var i=0; i < len; i++) {
  19938. result += String.fromCharCode(buf[i]);
  19939. }
  19940. return result;
  19941. }
  19942. // Convert byte array to binary string
  19943. exports.buf2binstring = function(buf) {
  19944. return buf2binstring(buf, buf.length);
  19945. };
  19946. // Convert binary string (typed, when possible)
  19947. exports.binstring2buf = function(str) {
  19948. var buf = new utils.Buf8(str.length);
  19949. for (var i=0, len=buf.length; i < len; i++) {
  19950. buf[i] = str.charCodeAt(i);
  19951. }
  19952. return buf;
  19953. };
  19954. // convert array to string
  19955. exports.buf2string = function (buf, max) {
  19956. var i, out, c, c_len;
  19957. var len = max || buf.length;
  19958. // Reserve max possible length (2 words per char)
  19959. // NB: by unknown reasons, Array is significantly faster for
  19960. // String.fromCharCode.apply than Uint16Array.
  19961. var utf16buf = new Array(len*2);
  19962. for (out=0, i=0; i<len;) {
  19963. c = buf[i++];
  19964. // quick process ascii
  19965. if (c < 0x80) { utf16buf[out++] = c; continue; }
  19966. c_len = _utf8len[c];
  19967. // skip 5 & 6 byte codes
  19968. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  19969. // apply mask on first byte
  19970. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  19971. // join the rest
  19972. while (c_len > 1 && i < len) {
  19973. c = (c << 6) | (buf[i++] & 0x3f);
  19974. c_len--;
  19975. }
  19976. // terminated by end of string?
  19977. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  19978. if (c < 0x10000) {
  19979. utf16buf[out++] = c;
  19980. } else {
  19981. c -= 0x10000;
  19982. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  19983. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  19984. }
  19985. }
  19986. return buf2binstring(utf16buf, out);
  19987. };
  19988. // Calculate max possible position in utf8 buffer,
  19989. // that will not break sequence. If that's not possible
  19990. // - (very small limits) return max size as is.
  19991. //
  19992. // buf[] - utf8 bytes array
  19993. // max - length limit (mandatory);
  19994. exports.utf8border = function(buf, max) {
  19995. var pos;
  19996. max = max || buf.length;
  19997. if (max > buf.length) { max = buf.length; }
  19998. // go back from last position, until start of sequence found
  19999. pos = max-1;
  20000. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20001. // Fuckup - very small and broken sequence,
  20002. // return max, because we should return something anyway.
  20003. if (pos < 0) { return max; }
  20004. // If we came to start of buffer - that means vuffer is too small,
  20005. // return max too.
  20006. if (pos === 0) { return max; }
  20007. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20008. };
  20009. },{"./common":72}],74:[function(require,module,exports){
  20010. 'use strict';
  20011. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20012. // It doesn't worth to make additional optimizationa as in original.
  20013. // Small size is preferable.
  20014. function adler32(adler, buf, len, pos) {
  20015. var s1 = (adler & 0xffff) |0,
  20016. s2 = ((adler >>> 16) & 0xffff) |0,
  20017. n = 0;
  20018. while (len !== 0) {
  20019. // Set limit ~ twice less than 5552, to keep
  20020. // s2 in 31-bits, because we force signed ints.
  20021. // in other case %= will fail.
  20022. n = len > 2000 ? 2000 : len;
  20023. len -= n;
  20024. do {
  20025. s1 = (s1 + buf[pos++]) |0;
  20026. s2 = (s2 + s1) |0;
  20027. } while (--n);
  20028. s1 %= 65521;
  20029. s2 %= 65521;
  20030. }
  20031. return (s1 | (s2 << 16)) |0;
  20032. }
  20033. module.exports = adler32;
  20034. },{}],75:[function(require,module,exports){
  20035. module.exports = {
  20036. /* Allowed flush values; see deflate() and inflate() below for details */
  20037. Z_NO_FLUSH: 0,
  20038. Z_PARTIAL_FLUSH: 1,
  20039. Z_SYNC_FLUSH: 2,
  20040. Z_FULL_FLUSH: 3,
  20041. Z_FINISH: 4,
  20042. Z_BLOCK: 5,
  20043. Z_TREES: 6,
  20044. /* Return codes for the compression/decompression functions. Negative values
  20045. * are errors, positive values are used for special but normal events.
  20046. */
  20047. Z_OK: 0,
  20048. Z_STREAM_END: 1,
  20049. Z_NEED_DICT: 2,
  20050. Z_ERRNO: -1,
  20051. Z_STREAM_ERROR: -2,
  20052. Z_DATA_ERROR: -3,
  20053. //Z_MEM_ERROR: -4,
  20054. Z_BUF_ERROR: -5,
  20055. //Z_VERSION_ERROR: -6,
  20056. /* compression levels */
  20057. Z_NO_COMPRESSION: 0,
  20058. Z_BEST_SPEED: 1,
  20059. Z_BEST_COMPRESSION: 9,
  20060. Z_DEFAULT_COMPRESSION: -1,
  20061. Z_FILTERED: 1,
  20062. Z_HUFFMAN_ONLY: 2,
  20063. Z_RLE: 3,
  20064. Z_FIXED: 4,
  20065. Z_DEFAULT_STRATEGY: 0,
  20066. /* Possible values of the data_type field (though see inflate()) */
  20067. Z_BINARY: 0,
  20068. Z_TEXT: 1,
  20069. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20070. Z_UNKNOWN: 2,
  20071. /* The deflate compression method */
  20072. Z_DEFLATED: 8
  20073. //Z_NULL: null // Use -1 or null inline, depending on var type
  20074. };
  20075. },{}],76:[function(require,module,exports){
  20076. 'use strict';
  20077. // Note: we can't get significant speed boost here.
  20078. // So write code to minimize size - no pregenerated tables
  20079. // and array tools dependencies.
  20080. // Use ordinary array, since untyped makes no boost here
  20081. function makeTable() {
  20082. var c, table = [];
  20083. for (var n =0; n < 256; n++) {
  20084. c = n;
  20085. for (var k =0; k < 8; k++) {
  20086. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20087. }
  20088. table[n] = c;
  20089. }
  20090. return table;
  20091. }
  20092. // Create table on load. Just 255 signed longs. Not a problem.
  20093. var crcTable = makeTable();
  20094. function crc32(crc, buf, len, pos) {
  20095. var t = crcTable,
  20096. end = pos + len;
  20097. crc = crc ^ (-1);
  20098. for (var i = pos; i < end; i++) {
  20099. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20100. }
  20101. return (crc ^ (-1)); // >>> 0;
  20102. }
  20103. module.exports = crc32;
  20104. },{}],77:[function(require,module,exports){
  20105. 'use strict';
  20106. var utils = require('../utils/common');
  20107. var trees = require('./trees');
  20108. var adler32 = require('./adler32');
  20109. var crc32 = require('./crc32');
  20110. var msg = require('./messages');
  20111. /* Public constants ==========================================================*/
  20112. /* ===========================================================================*/
  20113. /* Allowed flush values; see deflate() and inflate() below for details */
  20114. var Z_NO_FLUSH = 0;
  20115. var Z_PARTIAL_FLUSH = 1;
  20116. //var Z_SYNC_FLUSH = 2;
  20117. var Z_FULL_FLUSH = 3;
  20118. var Z_FINISH = 4;
  20119. var Z_BLOCK = 5;
  20120. //var Z_TREES = 6;
  20121. /* Return codes for the compression/decompression functions. Negative values
  20122. * are errors, positive values are used for special but normal events.
  20123. */
  20124. var Z_OK = 0;
  20125. var Z_STREAM_END = 1;
  20126. //var Z_NEED_DICT = 2;
  20127. //var Z_ERRNO = -1;
  20128. var Z_STREAM_ERROR = -2;
  20129. var Z_DATA_ERROR = -3;
  20130. //var Z_MEM_ERROR = -4;
  20131. var Z_BUF_ERROR = -5;
  20132. //var Z_VERSION_ERROR = -6;
  20133. /* compression levels */
  20134. //var Z_NO_COMPRESSION = 0;
  20135. //var Z_BEST_SPEED = 1;
  20136. //var Z_BEST_COMPRESSION = 9;
  20137. var Z_DEFAULT_COMPRESSION = -1;
  20138. var Z_FILTERED = 1;
  20139. var Z_HUFFMAN_ONLY = 2;
  20140. var Z_RLE = 3;
  20141. var Z_FIXED = 4;
  20142. var Z_DEFAULT_STRATEGY = 0;
  20143. /* Possible values of the data_type field (though see inflate()) */
  20144. //var Z_BINARY = 0;
  20145. //var Z_TEXT = 1;
  20146. //var Z_ASCII = 1; // = Z_TEXT
  20147. var Z_UNKNOWN = 2;
  20148. /* The deflate compression method */
  20149. var Z_DEFLATED = 8;
  20150. /*============================================================================*/
  20151. var MAX_MEM_LEVEL = 9;
  20152. /* Maximum value for memLevel in deflateInit2 */
  20153. var MAX_WBITS = 15;
  20154. /* 32K LZ77 window */
  20155. var DEF_MEM_LEVEL = 8;
  20156. var LENGTH_CODES = 29;
  20157. /* number of length codes, not counting the special END_BLOCK code */
  20158. var LITERALS = 256;
  20159. /* number of literal bytes 0..255 */
  20160. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20161. /* number of Literal or Length codes, including the END_BLOCK code */
  20162. var D_CODES = 30;
  20163. /* number of distance codes */
  20164. var BL_CODES = 19;
  20165. /* number of codes used to transfer the bit lengths */
  20166. var HEAP_SIZE = 2*L_CODES + 1;
  20167. /* maximum heap size */
  20168. var MAX_BITS = 15;
  20169. /* All codes must not exceed MAX_BITS bits */
  20170. var MIN_MATCH = 3;
  20171. var MAX_MATCH = 258;
  20172. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20173. var PRESET_DICT = 0x20;
  20174. var INIT_STATE = 42;
  20175. var EXTRA_STATE = 69;
  20176. var NAME_STATE = 73;
  20177. var COMMENT_STATE = 91;
  20178. var HCRC_STATE = 103;
  20179. var BUSY_STATE = 113;
  20180. var FINISH_STATE = 666;
  20181. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20182. var BS_BLOCK_DONE = 2; /* block flush performed */
  20183. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20184. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20185. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20186. function err(strm, errorCode) {
  20187. strm.msg = msg[errorCode];
  20188. return errorCode;
  20189. }
  20190. function rank(f) {
  20191. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20192. }
  20193. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20194. /* =========================================================================
  20195. * Flush as much pending output as possible. All deflate() output goes
  20196. * through this function so some applications may wish to modify it
  20197. * to avoid allocating a large strm->output buffer and copying into it.
  20198. * (See also read_buf()).
  20199. */
  20200. function flush_pending(strm) {
  20201. var s = strm.state;
  20202. //_tr_flush_bits(s);
  20203. var len = s.pending;
  20204. if (len > strm.avail_out) {
  20205. len = strm.avail_out;
  20206. }
  20207. if (len === 0) { return; }
  20208. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20209. strm.next_out += len;
  20210. s.pending_out += len;
  20211. strm.total_out += len;
  20212. strm.avail_out -= len;
  20213. s.pending -= len;
  20214. if (s.pending === 0) {
  20215. s.pending_out = 0;
  20216. }
  20217. }
  20218. function flush_block_only (s, last) {
  20219. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20220. s.block_start = s.strstart;
  20221. flush_pending(s.strm);
  20222. }
  20223. function put_byte(s, b) {
  20224. s.pending_buf[s.pending++] = b;
  20225. }
  20226. /* =========================================================================
  20227. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20228. * IN assertion: the stream state is correct and there is enough room in
  20229. * pending_buf.
  20230. */
  20231. function putShortMSB(s, b) {
  20232. // put_byte(s, (Byte)(b >> 8));
  20233. // put_byte(s, (Byte)(b & 0xff));
  20234. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20235. s.pending_buf[s.pending++] = b & 0xff;
  20236. }
  20237. /* ===========================================================================
  20238. * Read a new buffer from the current input stream, update the adler32
  20239. * and total number of bytes read. All deflate() input goes through
  20240. * this function so some applications may wish to modify it to avoid
  20241. * allocating a large strm->input buffer and copying from it.
  20242. * (See also flush_pending()).
  20243. */
  20244. function read_buf(strm, buf, start, size) {
  20245. var len = strm.avail_in;
  20246. if (len > size) { len = size; }
  20247. if (len === 0) { return 0; }
  20248. strm.avail_in -= len;
  20249. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20250. if (strm.state.wrap === 1) {
  20251. strm.adler = adler32(strm.adler, buf, len, start);
  20252. }
  20253. else if (strm.state.wrap === 2) {
  20254. strm.adler = crc32(strm.adler, buf, len, start);
  20255. }
  20256. strm.next_in += len;
  20257. strm.total_in += len;
  20258. return len;
  20259. }
  20260. /* ===========================================================================
  20261. * Set match_start to the longest match starting at the given string and
  20262. * return its length. Matches shorter or equal to prev_length are discarded,
  20263. * in which case the result is equal to prev_length and match_start is
  20264. * garbage.
  20265. * IN assertions: cur_match is the head of the hash chain for the current
  20266. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20267. * OUT assertion: the match length is not greater than s->lookahead.
  20268. */
  20269. function longest_match(s, cur_match) {
  20270. var chain_length = s.max_chain_length; /* max hash chain length */
  20271. var scan = s.strstart; /* current string */
  20272. var match; /* matched string */
  20273. var len; /* length of current match */
  20274. var best_len = s.prev_length; /* best match length so far */
  20275. var nice_match = s.nice_match; /* stop if match long enough */
  20276. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20277. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20278. var _win = s.window; // shortcut
  20279. var wmask = s.w_mask;
  20280. var prev = s.prev;
  20281. /* Stop when cur_match becomes <= limit. To simplify the code,
  20282. * we prevent matches with the string of window index 0.
  20283. */
  20284. var strend = s.strstart + MAX_MATCH;
  20285. var scan_end1 = _win[scan + best_len - 1];
  20286. var scan_end = _win[scan + best_len];
  20287. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20288. * It is easy to get rid of this optimization if necessary.
  20289. */
  20290. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20291. /* Do not waste too much time if we already have a good match: */
  20292. if (s.prev_length >= s.good_match) {
  20293. chain_length >>= 2;
  20294. }
  20295. /* Do not look for matches beyond the end of the input. This is necessary
  20296. * to make deflate deterministic.
  20297. */
  20298. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20299. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20300. do {
  20301. // Assert(cur_match < s->strstart, "no future");
  20302. match = cur_match;
  20303. /* Skip to next match if the match length cannot increase
  20304. * or if the match length is less than 2. Note that the checks below
  20305. * for insufficient lookahead only occur occasionally for performance
  20306. * reasons. Therefore uninitialized memory will be accessed, and
  20307. * conditional jumps will be made that depend on those values.
  20308. * However the length of the match is limited to the lookahead, so
  20309. * the output of deflate is not affected by the uninitialized values.
  20310. */
  20311. if (_win[match + best_len] !== scan_end ||
  20312. _win[match + best_len - 1] !== scan_end1 ||
  20313. _win[match] !== _win[scan] ||
  20314. _win[++match] !== _win[scan + 1]) {
  20315. continue;
  20316. }
  20317. /* The check at best_len-1 can be removed because it will be made
  20318. * again later. (This heuristic is not always a win.)
  20319. * It is not necessary to compare scan[2] and match[2] since they
  20320. * are always equal when the other bytes match, given that
  20321. * the hash keys are equal and that HASH_BITS >= 8.
  20322. */
  20323. scan += 2;
  20324. match++;
  20325. // Assert(*scan == *match, "match[2]?");
  20326. /* We check for insufficient lookahead only every 8th comparison;
  20327. * the 256th check will be made at strstart+258.
  20328. */
  20329. do {
  20330. /*jshint noempty:false*/
  20331. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20332. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20333. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20334. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20335. scan < strend);
  20336. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20337. len = MAX_MATCH - (strend - scan);
  20338. scan = strend - MAX_MATCH;
  20339. if (len > best_len) {
  20340. s.match_start = cur_match;
  20341. best_len = len;
  20342. if (len >= nice_match) {
  20343. break;
  20344. }
  20345. scan_end1 = _win[scan + best_len - 1];
  20346. scan_end = _win[scan + best_len];
  20347. }
  20348. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20349. if (best_len <= s.lookahead) {
  20350. return best_len;
  20351. }
  20352. return s.lookahead;
  20353. }
  20354. /* ===========================================================================
  20355. * Fill the window when the lookahead becomes insufficient.
  20356. * Updates strstart and lookahead.
  20357. *
  20358. * IN assertion: lookahead < MIN_LOOKAHEAD
  20359. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20360. * At least one byte has been read, or avail_in == 0; reads are
  20361. * performed for at least two bytes (required for the zip translate_eol
  20362. * option -- not supported here).
  20363. */
  20364. function fill_window(s) {
  20365. var _w_size = s.w_size;
  20366. var p, n, m, more, str;
  20367. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20368. do {
  20369. more = s.window_size - s.lookahead - s.strstart;
  20370. // JS ints have 32 bit, block below not needed
  20371. /* Deal with !@#$% 64K limit: */
  20372. //if (sizeof(int) <= 2) {
  20373. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20374. // more = wsize;
  20375. //
  20376. // } else if (more == (unsigned)(-1)) {
  20377. // /* Very unlikely, but possible on 16 bit machine if
  20378. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20379. // */
  20380. // more--;
  20381. // }
  20382. //}
  20383. /* If the window is almost full and there is insufficient lookahead,
  20384. * move the upper half to the lower one to make room in the upper half.
  20385. */
  20386. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20387. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20388. s.match_start -= _w_size;
  20389. s.strstart -= _w_size;
  20390. /* we now have strstart >= MAX_DIST */
  20391. s.block_start -= _w_size;
  20392. /* Slide the hash table (could be avoided with 32 bit values
  20393. at the expense of memory usage). We slide even when level == 0
  20394. to keep the hash table consistent if we switch back to level > 0
  20395. later. (Using level 0 permanently is not an optimal usage of
  20396. zlib, so we don't care about this pathological case.)
  20397. */
  20398. n = s.hash_size;
  20399. p = n;
  20400. do {
  20401. m = s.head[--p];
  20402. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20403. } while (--n);
  20404. n = _w_size;
  20405. p = n;
  20406. do {
  20407. m = s.prev[--p];
  20408. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20409. /* If n is not on any hash chain, prev[n] is garbage but
  20410. * its value will never be used.
  20411. */
  20412. } while (--n);
  20413. more += _w_size;
  20414. }
  20415. if (s.strm.avail_in === 0) {
  20416. break;
  20417. }
  20418. /* If there was no sliding:
  20419. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20420. * more == window_size - lookahead - strstart
  20421. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20422. * => more >= window_size - 2*WSIZE + 2
  20423. * In the BIG_MEM or MMAP case (not yet supported),
  20424. * window_size == input_size + MIN_LOOKAHEAD &&
  20425. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20426. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20427. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20428. */
  20429. //Assert(more >= 2, "more < 2");
  20430. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20431. s.lookahead += n;
  20432. /* Initialize the hash value now that we have some input: */
  20433. if (s.lookahead + s.insert >= MIN_MATCH) {
  20434. str = s.strstart - s.insert;
  20435. s.ins_h = s.window[str];
  20436. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20437. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20438. //#if MIN_MATCH != 3
  20439. // Call update_hash() MIN_MATCH-3 more times
  20440. //#endif
  20441. while (s.insert) {
  20442. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20443. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20444. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20445. s.head[s.ins_h] = str;
  20446. str++;
  20447. s.insert--;
  20448. if (s.lookahead + s.insert < MIN_MATCH) {
  20449. break;
  20450. }
  20451. }
  20452. }
  20453. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20454. * but this is not important since only literal bytes will be emitted.
  20455. */
  20456. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20457. /* If the WIN_INIT bytes after the end of the current data have never been
  20458. * written, then zero those bytes in order to avoid memory check reports of
  20459. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20460. * the longest match routines. Update the high water mark for the next
  20461. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20462. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20463. */
  20464. // if (s.high_water < s.window_size) {
  20465. // var curr = s.strstart + s.lookahead;
  20466. // var init = 0;
  20467. //
  20468. // if (s.high_water < curr) {
  20469. // /* Previous high water mark below current data -- zero WIN_INIT
  20470. // * bytes or up to end of window, whichever is less.
  20471. // */
  20472. // init = s.window_size - curr;
  20473. // if (init > WIN_INIT)
  20474. // init = WIN_INIT;
  20475. // zmemzero(s->window + curr, (unsigned)init);
  20476. // s->high_water = curr + init;
  20477. // }
  20478. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20479. // /* High water mark at or above current data, but below current data
  20480. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20481. // * to end of window, whichever is less.
  20482. // */
  20483. // init = (ulg)curr + WIN_INIT - s->high_water;
  20484. // if (init > s->window_size - s->high_water)
  20485. // init = s->window_size - s->high_water;
  20486. // zmemzero(s->window + s->high_water, (unsigned)init);
  20487. // s->high_water += init;
  20488. // }
  20489. // }
  20490. //
  20491. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20492. // "not enough room for search");
  20493. }
  20494. /* ===========================================================================
  20495. * Copy without compression as much as possible from the input stream, return
  20496. * the current block state.
  20497. * This function does not insert new strings in the dictionary since
  20498. * uncompressible data is probably not useful. This function is used
  20499. * only for the level=0 compression option.
  20500. * NOTE: this function should be optimized to avoid extra copying from
  20501. * window to pending_buf.
  20502. */
  20503. function deflate_stored(s, flush) {
  20504. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20505. * to pending_buf_size, and each stored block has a 5 byte header:
  20506. */
  20507. var max_block_size = 0xffff;
  20508. if (max_block_size > s.pending_buf_size - 5) {
  20509. max_block_size = s.pending_buf_size - 5;
  20510. }
  20511. /* Copy as much as possible from input to output: */
  20512. for (;;) {
  20513. /* Fill the window as much as possible: */
  20514. if (s.lookahead <= 1) {
  20515. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20516. // s->block_start >= (long)s->w_size, "slide too late");
  20517. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20518. // s.block_start >= s.w_size)) {
  20519. // throw new Error("slide too late");
  20520. // }
  20521. fill_window(s);
  20522. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20523. return BS_NEED_MORE;
  20524. }
  20525. if (s.lookahead === 0) {
  20526. break;
  20527. }
  20528. /* flush the current block */
  20529. }
  20530. //Assert(s->block_start >= 0L, "block gone");
  20531. // if (s.block_start < 0) throw new Error("block gone");
  20532. s.strstart += s.lookahead;
  20533. s.lookahead = 0;
  20534. /* Emit a stored block if pending_buf will be full: */
  20535. var max_start = s.block_start + max_block_size;
  20536. if (s.strstart === 0 || s.strstart >= max_start) {
  20537. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20538. s.lookahead = s.strstart - max_start;
  20539. s.strstart = max_start;
  20540. /*** FLUSH_BLOCK(s, 0); ***/
  20541. flush_block_only(s, false);
  20542. if (s.strm.avail_out === 0) {
  20543. return BS_NEED_MORE;
  20544. }
  20545. /***/
  20546. }
  20547. /* Flush if we may have to slide, otherwise block_start may become
  20548. * negative and the data will be gone:
  20549. */
  20550. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20551. /*** FLUSH_BLOCK(s, 0); ***/
  20552. flush_block_only(s, false);
  20553. if (s.strm.avail_out === 0) {
  20554. return BS_NEED_MORE;
  20555. }
  20556. /***/
  20557. }
  20558. }
  20559. s.insert = 0;
  20560. if (flush === Z_FINISH) {
  20561. /*** FLUSH_BLOCK(s, 1); ***/
  20562. flush_block_only(s, true);
  20563. if (s.strm.avail_out === 0) {
  20564. return BS_FINISH_STARTED;
  20565. }
  20566. /***/
  20567. return BS_FINISH_DONE;
  20568. }
  20569. if (s.strstart > s.block_start) {
  20570. /*** FLUSH_BLOCK(s, 0); ***/
  20571. flush_block_only(s, false);
  20572. if (s.strm.avail_out === 0) {
  20573. return BS_NEED_MORE;
  20574. }
  20575. /***/
  20576. }
  20577. return BS_NEED_MORE;
  20578. }
  20579. /* ===========================================================================
  20580. * Compress as much as possible from the input stream, return the current
  20581. * block state.
  20582. * This function does not perform lazy evaluation of matches and inserts
  20583. * new strings in the dictionary only for unmatched strings or for short
  20584. * matches. It is used only for the fast compression options.
  20585. */
  20586. function deflate_fast(s, flush) {
  20587. var hash_head; /* head of the hash chain */
  20588. var bflush; /* set if current block must be flushed */
  20589. for (;;) {
  20590. /* Make sure that we always have enough lookahead, except
  20591. * at the end of the input file. We need MAX_MATCH bytes
  20592. * for the next match, plus MIN_MATCH bytes to insert the
  20593. * string following the next match.
  20594. */
  20595. if (s.lookahead < MIN_LOOKAHEAD) {
  20596. fill_window(s);
  20597. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20598. return BS_NEED_MORE;
  20599. }
  20600. if (s.lookahead === 0) {
  20601. break; /* flush the current block */
  20602. }
  20603. }
  20604. /* Insert the string window[strstart .. strstart+2] in the
  20605. * dictionary, and set hash_head to the head of the hash chain:
  20606. */
  20607. hash_head = 0/*NIL*/;
  20608. if (s.lookahead >= MIN_MATCH) {
  20609. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20610. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20611. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20612. s.head[s.ins_h] = s.strstart;
  20613. /***/
  20614. }
  20615. /* Find the longest match, discarding those <= prev_length.
  20616. * At this point we have always match_length < MIN_MATCH
  20617. */
  20618. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20619. /* To simplify the code, we prevent matches with the string
  20620. * of window index 0 (in particular we have to avoid a match
  20621. * of the string with itself at the start of the input file).
  20622. */
  20623. s.match_length = longest_match(s, hash_head);
  20624. /* longest_match() sets match_start */
  20625. }
  20626. if (s.match_length >= MIN_MATCH) {
  20627. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20628. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20629. s.match_length - MIN_MATCH, bflush); ***/
  20630. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20631. s.lookahead -= s.match_length;
  20632. /* Insert new strings in the hash table only if the match length
  20633. * is not too large. This saves time but degrades compression.
  20634. */
  20635. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20636. s.match_length--; /* string at strstart already in table */
  20637. do {
  20638. s.strstart++;
  20639. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20640. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20641. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20642. s.head[s.ins_h] = s.strstart;
  20643. /***/
  20644. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20645. * always MIN_MATCH bytes ahead.
  20646. */
  20647. } while (--s.match_length !== 0);
  20648. s.strstart++;
  20649. } else
  20650. {
  20651. s.strstart += s.match_length;
  20652. s.match_length = 0;
  20653. s.ins_h = s.window[s.strstart];
  20654. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20655. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20656. //#if MIN_MATCH != 3
  20657. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20658. //#endif
  20659. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20660. * matter since it will be recomputed at next deflate call.
  20661. */
  20662. }
  20663. } else {
  20664. /* No match, output a literal byte */
  20665. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20666. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20667. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20668. s.lookahead--;
  20669. s.strstart++;
  20670. }
  20671. if (bflush) {
  20672. /*** FLUSH_BLOCK(s, 0); ***/
  20673. flush_block_only(s, false);
  20674. if (s.strm.avail_out === 0) {
  20675. return BS_NEED_MORE;
  20676. }
  20677. /***/
  20678. }
  20679. }
  20680. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20681. if (flush === Z_FINISH) {
  20682. /*** FLUSH_BLOCK(s, 1); ***/
  20683. flush_block_only(s, true);
  20684. if (s.strm.avail_out === 0) {
  20685. return BS_FINISH_STARTED;
  20686. }
  20687. /***/
  20688. return BS_FINISH_DONE;
  20689. }
  20690. if (s.last_lit) {
  20691. /*** FLUSH_BLOCK(s, 0); ***/
  20692. flush_block_only(s, false);
  20693. if (s.strm.avail_out === 0) {
  20694. return BS_NEED_MORE;
  20695. }
  20696. /***/
  20697. }
  20698. return BS_BLOCK_DONE;
  20699. }
  20700. /* ===========================================================================
  20701. * Same as above, but achieves better compression. We use a lazy
  20702. * evaluation for matches: a match is finally adopted only if there is
  20703. * no better match at the next window position.
  20704. */
  20705. function deflate_slow(s, flush) {
  20706. var hash_head; /* head of hash chain */
  20707. var bflush; /* set if current block must be flushed */
  20708. var max_insert;
  20709. /* Process the input block. */
  20710. for (;;) {
  20711. /* Make sure that we always have enough lookahead, except
  20712. * at the end of the input file. We need MAX_MATCH bytes
  20713. * for the next match, plus MIN_MATCH bytes to insert the
  20714. * string following the next match.
  20715. */
  20716. if (s.lookahead < MIN_LOOKAHEAD) {
  20717. fill_window(s);
  20718. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20719. return BS_NEED_MORE;
  20720. }
  20721. if (s.lookahead === 0) { break; } /* flush the current block */
  20722. }
  20723. /* Insert the string window[strstart .. strstart+2] in the
  20724. * dictionary, and set hash_head to the head of the hash chain:
  20725. */
  20726. hash_head = 0/*NIL*/;
  20727. if (s.lookahead >= MIN_MATCH) {
  20728. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20729. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20730. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20731. s.head[s.ins_h] = s.strstart;
  20732. /***/
  20733. }
  20734. /* Find the longest match, discarding those <= prev_length.
  20735. */
  20736. s.prev_length = s.match_length;
  20737. s.prev_match = s.match_start;
  20738. s.match_length = MIN_MATCH-1;
  20739. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20740. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20741. /* To simplify the code, we prevent matches with the string
  20742. * of window index 0 (in particular we have to avoid a match
  20743. * of the string with itself at the start of the input file).
  20744. */
  20745. s.match_length = longest_match(s, hash_head);
  20746. /* longest_match() sets match_start */
  20747. if (s.match_length <= 5 &&
  20748. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20749. /* If prev_match is also MIN_MATCH, match_start is garbage
  20750. * but we will ignore the current match anyway.
  20751. */
  20752. s.match_length = MIN_MATCH-1;
  20753. }
  20754. }
  20755. /* If there was a match at the previous step and the current
  20756. * match is not better, output the previous match:
  20757. */
  20758. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20759. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20760. /* Do not insert strings in hash table beyond this. */
  20761. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20762. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20763. s.prev_length - MIN_MATCH, bflush);***/
  20764. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20765. /* Insert in hash table all strings up to the end of the match.
  20766. * strstart-1 and strstart are already inserted. If there is not
  20767. * enough lookahead, the last two strings are not inserted in
  20768. * the hash table.
  20769. */
  20770. s.lookahead -= s.prev_length-1;
  20771. s.prev_length -= 2;
  20772. do {
  20773. if (++s.strstart <= max_insert) {
  20774. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20775. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20776. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20777. s.head[s.ins_h] = s.strstart;
  20778. /***/
  20779. }
  20780. } while (--s.prev_length !== 0);
  20781. s.match_available = 0;
  20782. s.match_length = MIN_MATCH-1;
  20783. s.strstart++;
  20784. if (bflush) {
  20785. /*** FLUSH_BLOCK(s, 0); ***/
  20786. flush_block_only(s, false);
  20787. if (s.strm.avail_out === 0) {
  20788. return BS_NEED_MORE;
  20789. }
  20790. /***/
  20791. }
  20792. } else if (s.match_available) {
  20793. /* If there was no match at the previous position, output a
  20794. * single literal. If there was a match but the current match
  20795. * is longer, truncate the previous match to a single literal.
  20796. */
  20797. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20798. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20799. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20800. if (bflush) {
  20801. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20802. flush_block_only(s, false);
  20803. /***/
  20804. }
  20805. s.strstart++;
  20806. s.lookahead--;
  20807. if (s.strm.avail_out === 0) {
  20808. return BS_NEED_MORE;
  20809. }
  20810. } else {
  20811. /* There is no previous match to compare with, wait for
  20812. * the next step to decide.
  20813. */
  20814. s.match_available = 1;
  20815. s.strstart++;
  20816. s.lookahead--;
  20817. }
  20818. }
  20819. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20820. if (s.match_available) {
  20821. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20822. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20823. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20824. s.match_available = 0;
  20825. }
  20826. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20827. if (flush === Z_FINISH) {
  20828. /*** FLUSH_BLOCK(s, 1); ***/
  20829. flush_block_only(s, true);
  20830. if (s.strm.avail_out === 0) {
  20831. return BS_FINISH_STARTED;
  20832. }
  20833. /***/
  20834. return BS_FINISH_DONE;
  20835. }
  20836. if (s.last_lit) {
  20837. /*** FLUSH_BLOCK(s, 0); ***/
  20838. flush_block_only(s, false);
  20839. if (s.strm.avail_out === 0) {
  20840. return BS_NEED_MORE;
  20841. }
  20842. /***/
  20843. }
  20844. return BS_BLOCK_DONE;
  20845. }
  20846. /* ===========================================================================
  20847. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20848. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20849. * deflate switches away from Z_RLE.)
  20850. */
  20851. function deflate_rle(s, flush) {
  20852. var bflush; /* set if current block must be flushed */
  20853. var prev; /* byte at distance one to match */
  20854. var scan, strend; /* scan goes up to strend for length of run */
  20855. var _win = s.window;
  20856. for (;;) {
  20857. /* Make sure that we always have enough lookahead, except
  20858. * at the end of the input file. We need MAX_MATCH bytes
  20859. * for the longest run, plus one for the unrolled loop.
  20860. */
  20861. if (s.lookahead <= MAX_MATCH) {
  20862. fill_window(s);
  20863. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20864. return BS_NEED_MORE;
  20865. }
  20866. if (s.lookahead === 0) { break; } /* flush the current block */
  20867. }
  20868. /* See how many times the previous byte repeats */
  20869. s.match_length = 0;
  20870. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  20871. scan = s.strstart - 1;
  20872. prev = _win[scan];
  20873. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  20874. strend = s.strstart + MAX_MATCH;
  20875. do {
  20876. /*jshint noempty:false*/
  20877. } while (prev === _win[++scan] && prev === _win[++scan] &&
  20878. prev === _win[++scan] && prev === _win[++scan] &&
  20879. prev === _win[++scan] && prev === _win[++scan] &&
  20880. prev === _win[++scan] && prev === _win[++scan] &&
  20881. scan < strend);
  20882. s.match_length = MAX_MATCH - (strend - scan);
  20883. if (s.match_length > s.lookahead) {
  20884. s.match_length = s.lookahead;
  20885. }
  20886. }
  20887. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  20888. }
  20889. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  20890. if (s.match_length >= MIN_MATCH) {
  20891. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  20892. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  20893. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  20894. s.lookahead -= s.match_length;
  20895. s.strstart += s.match_length;
  20896. s.match_length = 0;
  20897. } else {
  20898. /* No match, output a literal byte */
  20899. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20900. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20901. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20902. s.lookahead--;
  20903. s.strstart++;
  20904. }
  20905. if (bflush) {
  20906. /*** FLUSH_BLOCK(s, 0); ***/
  20907. flush_block_only(s, false);
  20908. if (s.strm.avail_out === 0) {
  20909. return BS_NEED_MORE;
  20910. }
  20911. /***/
  20912. }
  20913. }
  20914. s.insert = 0;
  20915. if (flush === Z_FINISH) {
  20916. /*** FLUSH_BLOCK(s, 1); ***/
  20917. flush_block_only(s, true);
  20918. if (s.strm.avail_out === 0) {
  20919. return BS_FINISH_STARTED;
  20920. }
  20921. /***/
  20922. return BS_FINISH_DONE;
  20923. }
  20924. if (s.last_lit) {
  20925. /*** FLUSH_BLOCK(s, 0); ***/
  20926. flush_block_only(s, false);
  20927. if (s.strm.avail_out === 0) {
  20928. return BS_NEED_MORE;
  20929. }
  20930. /***/
  20931. }
  20932. return BS_BLOCK_DONE;
  20933. }
  20934. /* ===========================================================================
  20935. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  20936. * (It will be regenerated if this run of deflate switches away from Huffman.)
  20937. */
  20938. function deflate_huff(s, flush) {
  20939. var bflush; /* set if current block must be flushed */
  20940. for (;;) {
  20941. /* Make sure that we have a literal to write. */
  20942. if (s.lookahead === 0) {
  20943. fill_window(s);
  20944. if (s.lookahead === 0) {
  20945. if (flush === Z_NO_FLUSH) {
  20946. return BS_NEED_MORE;
  20947. }
  20948. break; /* flush the current block */
  20949. }
  20950. }
  20951. /* Output a literal byte */
  20952. s.match_length = 0;
  20953. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20954. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20955. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20956. s.lookahead--;
  20957. s.strstart++;
  20958. if (bflush) {
  20959. /*** FLUSH_BLOCK(s, 0); ***/
  20960. flush_block_only(s, false);
  20961. if (s.strm.avail_out === 0) {
  20962. return BS_NEED_MORE;
  20963. }
  20964. /***/
  20965. }
  20966. }
  20967. s.insert = 0;
  20968. if (flush === Z_FINISH) {
  20969. /*** FLUSH_BLOCK(s, 1); ***/
  20970. flush_block_only(s, true);
  20971. if (s.strm.avail_out === 0) {
  20972. return BS_FINISH_STARTED;
  20973. }
  20974. /***/
  20975. return BS_FINISH_DONE;
  20976. }
  20977. if (s.last_lit) {
  20978. /*** FLUSH_BLOCK(s, 0); ***/
  20979. flush_block_only(s, false);
  20980. if (s.strm.avail_out === 0) {
  20981. return BS_NEED_MORE;
  20982. }
  20983. /***/
  20984. }
  20985. return BS_BLOCK_DONE;
  20986. }
  20987. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  20988. * the desired pack level (0..9). The values given below have been tuned to
  20989. * exclude worst case performance for pathological files. Better values may be
  20990. * found for specific files.
  20991. */
  20992. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  20993. this.good_length = good_length;
  20994. this.max_lazy = max_lazy;
  20995. this.nice_length = nice_length;
  20996. this.max_chain = max_chain;
  20997. this.func = func;
  20998. };
  20999. var configuration_table;
  21000. configuration_table = [
  21001. /* good lazy nice chain */
  21002. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21003. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21004. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21005. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21006. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21007. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21008. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21009. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21010. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21011. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21012. ];
  21013. /* ===========================================================================
  21014. * Initialize the "longest match" routines for a new zlib stream
  21015. */
  21016. function lm_init(s) {
  21017. s.window_size = 2 * s.w_size;
  21018. /*** CLEAR_HASH(s); ***/
  21019. zero(s.head); // Fill with NIL (= 0);
  21020. /* Set the default configuration parameters:
  21021. */
  21022. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21023. s.good_match = configuration_table[s.level].good_length;
  21024. s.nice_match = configuration_table[s.level].nice_length;
  21025. s.max_chain_length = configuration_table[s.level].max_chain;
  21026. s.strstart = 0;
  21027. s.block_start = 0;
  21028. s.lookahead = 0;
  21029. s.insert = 0;
  21030. s.match_length = s.prev_length = MIN_MATCH - 1;
  21031. s.match_available = 0;
  21032. s.ins_h = 0;
  21033. }
  21034. function DeflateState() {
  21035. this.strm = null; /* pointer back to this zlib stream */
  21036. this.status = 0; /* as the name implies */
  21037. this.pending_buf = null; /* output still pending */
  21038. this.pending_buf_size = 0; /* size of pending_buf */
  21039. this.pending_out = 0; /* next pending byte to output to the stream */
  21040. this.pending = 0; /* nb of bytes in the pending buffer */
  21041. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21042. this.gzhead = null; /* gzip header information to write */
  21043. this.gzindex = 0; /* where in extra, name, or comment */
  21044. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21045. this.last_flush = -1; /* value of flush param for previous deflate call */
  21046. this.w_size = 0; /* LZ77 window size (32K by default) */
  21047. this.w_bits = 0; /* log2(w_size) (8..16) */
  21048. this.w_mask = 0; /* w_size - 1 */
  21049. this.window = null;
  21050. /* Sliding window. Input bytes are read into the second half of the window,
  21051. * and move to the first half later to keep a dictionary of at least wSize
  21052. * bytes. With this organization, matches are limited to a distance of
  21053. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21054. * performed with a length multiple of the block size.
  21055. */
  21056. this.window_size = 0;
  21057. /* Actual size of window: 2*wSize, except when the user input buffer
  21058. * is directly used as sliding window.
  21059. */
  21060. this.prev = null;
  21061. /* Link to older string with same hash index. To limit the size of this
  21062. * array to 64K, this link is maintained only for the last 32K strings.
  21063. * An index in this array is thus a window index modulo 32K.
  21064. */
  21065. this.head = null; /* Heads of the hash chains or NIL. */
  21066. this.ins_h = 0; /* hash index of string to be inserted */
  21067. this.hash_size = 0; /* number of elements in hash table */
  21068. this.hash_bits = 0; /* log2(hash_size) */
  21069. this.hash_mask = 0; /* hash_size-1 */
  21070. this.hash_shift = 0;
  21071. /* Number of bits by which ins_h must be shifted at each input
  21072. * step. It must be such that after MIN_MATCH steps, the oldest
  21073. * byte no longer takes part in the hash key, that is:
  21074. * hash_shift * MIN_MATCH >= hash_bits
  21075. */
  21076. this.block_start = 0;
  21077. /* Window position at the beginning of the current output block. Gets
  21078. * negative when the window is moved backwards.
  21079. */
  21080. this.match_length = 0; /* length of best match */
  21081. this.prev_match = 0; /* previous match */
  21082. this.match_available = 0; /* set if previous match exists */
  21083. this.strstart = 0; /* start of string to insert */
  21084. this.match_start = 0; /* start of matching string */
  21085. this.lookahead = 0; /* number of valid bytes ahead in window */
  21086. this.prev_length = 0;
  21087. /* Length of the best match at previous step. Matches not greater than this
  21088. * are discarded. This is used in the lazy match evaluation.
  21089. */
  21090. this.max_chain_length = 0;
  21091. /* To speed up deflation, hash chains are never searched beyond this
  21092. * length. A higher limit improves compression ratio but degrades the
  21093. * speed.
  21094. */
  21095. this.max_lazy_match = 0;
  21096. /* Attempt to find a better match only when the current match is strictly
  21097. * smaller than this value. This mechanism is used only for compression
  21098. * levels >= 4.
  21099. */
  21100. // That's alias to max_lazy_match, don't use directly
  21101. //this.max_insert_length = 0;
  21102. /* Insert new strings in the hash table only if the match length is not
  21103. * greater than this length. This saves time but degrades compression.
  21104. * max_insert_length is used only for compression levels <= 3.
  21105. */
  21106. this.level = 0; /* compression level (1..9) */
  21107. this.strategy = 0; /* favor or force Huffman coding*/
  21108. this.good_match = 0;
  21109. /* Use a faster search when the previous match is longer than this */
  21110. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21111. /* used by trees.c: */
  21112. /* Didn't use ct_data typedef below to suppress compiler warning */
  21113. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21114. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21115. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21116. // Use flat array of DOUBLE size, with interleaved fata,
  21117. // because JS does not support effective
  21118. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21119. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21120. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21121. zero(this.dyn_ltree);
  21122. zero(this.dyn_dtree);
  21123. zero(this.bl_tree);
  21124. this.l_desc = null; /* desc. for literal tree */
  21125. this.d_desc = null; /* desc. for distance tree */
  21126. this.bl_desc = null; /* desc. for bit length tree */
  21127. //ush bl_count[MAX_BITS+1];
  21128. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21129. /* number of codes at each bit length for an optimal tree */
  21130. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21131. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21132. zero(this.heap);
  21133. this.heap_len = 0; /* number of elements in the heap */
  21134. this.heap_max = 0; /* element of largest frequency */
  21135. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21136. * The same heap array is used to build all trees.
  21137. */
  21138. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21139. zero(this.depth);
  21140. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21141. */
  21142. this.l_buf = 0; /* buffer index for literals or lengths */
  21143. this.lit_bufsize = 0;
  21144. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21145. * limiting lit_bufsize to 64K:
  21146. * - frequencies can be kept in 16 bit counters
  21147. * - if compression is not successful for the first block, all input
  21148. * data is still in the window so we can still emit a stored block even
  21149. * when input comes from standard input. (This can also be done for
  21150. * all blocks if lit_bufsize is not greater than 32K.)
  21151. * - if compression is not successful for a file smaller than 64K, we can
  21152. * even emit a stored file instead of a stored block (saving 5 bytes).
  21153. * This is applicable only for zip (not gzip or zlib).
  21154. * - creating new Huffman trees less frequently may not provide fast
  21155. * adaptation to changes in the input data statistics. (Take for
  21156. * example a binary file with poorly compressible code followed by
  21157. * a highly compressible string table.) Smaller buffer sizes give
  21158. * fast adaptation but have of course the overhead of transmitting
  21159. * trees more frequently.
  21160. * - I can't count above 4
  21161. */
  21162. this.last_lit = 0; /* running index in l_buf */
  21163. this.d_buf = 0;
  21164. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21165. * the same number of elements. To use different lengths, an extra flag
  21166. * array would be necessary.
  21167. */
  21168. this.opt_len = 0; /* bit length of current block with optimal trees */
  21169. this.static_len = 0; /* bit length of current block with static trees */
  21170. this.matches = 0; /* number of string matches in current block */
  21171. this.insert = 0; /* bytes at end of window left to insert */
  21172. this.bi_buf = 0;
  21173. /* Output buffer. bits are inserted starting at the bottom (least
  21174. * significant bits).
  21175. */
  21176. this.bi_valid = 0;
  21177. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21178. * are always zero.
  21179. */
  21180. // Used for window memory init. We safely ignore it for JS. That makes
  21181. // sense only for pointers and memory check tools.
  21182. //this.high_water = 0;
  21183. /* High water mark offset in window for initialized bytes -- bytes above
  21184. * this are set to zero in order to avoid memory check warnings when
  21185. * longest match routines access bytes past the input. This is then
  21186. * updated to the new high water mark.
  21187. */
  21188. }
  21189. function deflateResetKeep(strm) {
  21190. var s;
  21191. if (!strm || !strm.state) {
  21192. return err(strm, Z_STREAM_ERROR);
  21193. }
  21194. strm.total_in = strm.total_out = 0;
  21195. strm.data_type = Z_UNKNOWN;
  21196. s = strm.state;
  21197. s.pending = 0;
  21198. s.pending_out = 0;
  21199. if (s.wrap < 0) {
  21200. s.wrap = -s.wrap;
  21201. /* was made negative by deflate(..., Z_FINISH); */
  21202. }
  21203. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21204. strm.adler = (s.wrap === 2) ?
  21205. 0 // crc32(0, Z_NULL, 0)
  21206. :
  21207. 1; // adler32(0, Z_NULL, 0)
  21208. s.last_flush = Z_NO_FLUSH;
  21209. trees._tr_init(s);
  21210. return Z_OK;
  21211. }
  21212. function deflateReset(strm) {
  21213. var ret = deflateResetKeep(strm);
  21214. if (ret === Z_OK) {
  21215. lm_init(strm.state);
  21216. }
  21217. return ret;
  21218. }
  21219. function deflateSetHeader(strm, head) {
  21220. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21221. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21222. strm.state.gzhead = head;
  21223. return Z_OK;
  21224. }
  21225. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21226. if (!strm) { // === Z_NULL
  21227. return Z_STREAM_ERROR;
  21228. }
  21229. var wrap = 1;
  21230. if (level === Z_DEFAULT_COMPRESSION) {
  21231. level = 6;
  21232. }
  21233. if (windowBits < 0) { /* suppress zlib wrapper */
  21234. wrap = 0;
  21235. windowBits = -windowBits;
  21236. }
  21237. else if (windowBits > 15) {
  21238. wrap = 2; /* write gzip wrapper instead */
  21239. windowBits -= 16;
  21240. }
  21241. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21242. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21243. strategy < 0 || strategy > Z_FIXED) {
  21244. return err(strm, Z_STREAM_ERROR);
  21245. }
  21246. if (windowBits === 8) {
  21247. windowBits = 9;
  21248. }
  21249. /* until 256-byte window bug fixed */
  21250. var s = new DeflateState();
  21251. strm.state = s;
  21252. s.strm = strm;
  21253. s.wrap = wrap;
  21254. s.gzhead = null;
  21255. s.w_bits = windowBits;
  21256. s.w_size = 1 << s.w_bits;
  21257. s.w_mask = s.w_size - 1;
  21258. s.hash_bits = memLevel + 7;
  21259. s.hash_size = 1 << s.hash_bits;
  21260. s.hash_mask = s.hash_size - 1;
  21261. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21262. s.window = new utils.Buf8(s.w_size * 2);
  21263. s.head = new utils.Buf16(s.hash_size);
  21264. s.prev = new utils.Buf16(s.w_size);
  21265. // Don't need mem init magic for JS.
  21266. //s.high_water = 0; /* nothing written to s->window yet */
  21267. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21268. s.pending_buf_size = s.lit_bufsize * 4;
  21269. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21270. s.d_buf = s.lit_bufsize >> 1;
  21271. s.l_buf = (1 + 2) * s.lit_bufsize;
  21272. s.level = level;
  21273. s.strategy = strategy;
  21274. s.method = method;
  21275. return deflateReset(strm);
  21276. }
  21277. function deflateInit(strm, level) {
  21278. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21279. }
  21280. function deflate(strm, flush) {
  21281. var old_flush, s;
  21282. var beg, val; // for gzip header write only
  21283. if (!strm || !strm.state ||
  21284. flush > Z_BLOCK || flush < 0) {
  21285. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21286. }
  21287. s = strm.state;
  21288. if (!strm.output ||
  21289. (!strm.input && strm.avail_in !== 0) ||
  21290. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21291. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21292. }
  21293. s.strm = strm; /* just in case */
  21294. old_flush = s.last_flush;
  21295. s.last_flush = flush;
  21296. /* Write the header */
  21297. if (s.status === INIT_STATE) {
  21298. if (s.wrap === 2) { // GZIP header
  21299. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21300. put_byte(s, 31);
  21301. put_byte(s, 139);
  21302. put_byte(s, 8);
  21303. if (!s.gzhead) { // s->gzhead == Z_NULL
  21304. put_byte(s, 0);
  21305. put_byte(s, 0);
  21306. put_byte(s, 0);
  21307. put_byte(s, 0);
  21308. put_byte(s, 0);
  21309. put_byte(s, s.level === 9 ? 2 :
  21310. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21311. 4 : 0));
  21312. put_byte(s, OS_CODE);
  21313. s.status = BUSY_STATE;
  21314. }
  21315. else {
  21316. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21317. (s.gzhead.hcrc ? 2 : 0) +
  21318. (!s.gzhead.extra ? 0 : 4) +
  21319. (!s.gzhead.name ? 0 : 8) +
  21320. (!s.gzhead.comment ? 0 : 16)
  21321. );
  21322. put_byte(s, s.gzhead.time & 0xff);
  21323. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21324. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21325. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21326. put_byte(s, s.level === 9 ? 2 :
  21327. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21328. 4 : 0));
  21329. put_byte(s, s.gzhead.os & 0xff);
  21330. if (s.gzhead.extra && s.gzhead.extra.length) {
  21331. put_byte(s, s.gzhead.extra.length & 0xff);
  21332. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21333. }
  21334. if (s.gzhead.hcrc) {
  21335. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21336. }
  21337. s.gzindex = 0;
  21338. s.status = EXTRA_STATE;
  21339. }
  21340. }
  21341. else // DEFLATE header
  21342. {
  21343. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21344. var level_flags = -1;
  21345. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21346. level_flags = 0;
  21347. } else if (s.level < 6) {
  21348. level_flags = 1;
  21349. } else if (s.level === 6) {
  21350. level_flags = 2;
  21351. } else {
  21352. level_flags = 3;
  21353. }
  21354. header |= (level_flags << 6);
  21355. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21356. header += 31 - (header % 31);
  21357. s.status = BUSY_STATE;
  21358. putShortMSB(s, header);
  21359. /* Save the adler32 of the preset dictionary: */
  21360. if (s.strstart !== 0) {
  21361. putShortMSB(s, strm.adler >>> 16);
  21362. putShortMSB(s, strm.adler & 0xffff);
  21363. }
  21364. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21365. }
  21366. }
  21367. //#ifdef GZIP
  21368. if (s.status === EXTRA_STATE) {
  21369. if (s.gzhead.extra/* != Z_NULL*/) {
  21370. beg = s.pending; /* start of bytes to update crc */
  21371. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21372. if (s.pending === s.pending_buf_size) {
  21373. if (s.gzhead.hcrc && s.pending > beg) {
  21374. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21375. }
  21376. flush_pending(strm);
  21377. beg = s.pending;
  21378. if (s.pending === s.pending_buf_size) {
  21379. break;
  21380. }
  21381. }
  21382. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21383. s.gzindex++;
  21384. }
  21385. if (s.gzhead.hcrc && s.pending > beg) {
  21386. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21387. }
  21388. if (s.gzindex === s.gzhead.extra.length) {
  21389. s.gzindex = 0;
  21390. s.status = NAME_STATE;
  21391. }
  21392. }
  21393. else {
  21394. s.status = NAME_STATE;
  21395. }
  21396. }
  21397. if (s.status === NAME_STATE) {
  21398. if (s.gzhead.name/* != Z_NULL*/) {
  21399. beg = s.pending; /* start of bytes to update crc */
  21400. //int val;
  21401. do {
  21402. if (s.pending === s.pending_buf_size) {
  21403. if (s.gzhead.hcrc && s.pending > beg) {
  21404. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21405. }
  21406. flush_pending(strm);
  21407. beg = s.pending;
  21408. if (s.pending === s.pending_buf_size) {
  21409. val = 1;
  21410. break;
  21411. }
  21412. }
  21413. // JS specific: little magic to add zero terminator to end of string
  21414. if (s.gzindex < s.gzhead.name.length) {
  21415. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21416. } else {
  21417. val = 0;
  21418. }
  21419. put_byte(s, val);
  21420. } while (val !== 0);
  21421. if (s.gzhead.hcrc && s.pending > beg) {
  21422. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21423. }
  21424. if (val === 0) {
  21425. s.gzindex = 0;
  21426. s.status = COMMENT_STATE;
  21427. }
  21428. }
  21429. else {
  21430. s.status = COMMENT_STATE;
  21431. }
  21432. }
  21433. if (s.status === COMMENT_STATE) {
  21434. if (s.gzhead.comment/* != Z_NULL*/) {
  21435. beg = s.pending; /* start of bytes to update crc */
  21436. //int val;
  21437. do {
  21438. if (s.pending === s.pending_buf_size) {
  21439. if (s.gzhead.hcrc && s.pending > beg) {
  21440. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21441. }
  21442. flush_pending(strm);
  21443. beg = s.pending;
  21444. if (s.pending === s.pending_buf_size) {
  21445. val = 1;
  21446. break;
  21447. }
  21448. }
  21449. // JS specific: little magic to add zero terminator to end of string
  21450. if (s.gzindex < s.gzhead.comment.length) {
  21451. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21452. } else {
  21453. val = 0;
  21454. }
  21455. put_byte(s, val);
  21456. } while (val !== 0);
  21457. if (s.gzhead.hcrc && s.pending > beg) {
  21458. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21459. }
  21460. if (val === 0) {
  21461. s.status = HCRC_STATE;
  21462. }
  21463. }
  21464. else {
  21465. s.status = HCRC_STATE;
  21466. }
  21467. }
  21468. if (s.status === HCRC_STATE) {
  21469. if (s.gzhead.hcrc) {
  21470. if (s.pending + 2 > s.pending_buf_size) {
  21471. flush_pending(strm);
  21472. }
  21473. if (s.pending + 2 <= s.pending_buf_size) {
  21474. put_byte(s, strm.adler & 0xff);
  21475. put_byte(s, (strm.adler >> 8) & 0xff);
  21476. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21477. s.status = BUSY_STATE;
  21478. }
  21479. }
  21480. else {
  21481. s.status = BUSY_STATE;
  21482. }
  21483. }
  21484. //#endif
  21485. /* Flush as much pending output as possible */
  21486. if (s.pending !== 0) {
  21487. flush_pending(strm);
  21488. if (strm.avail_out === 0) {
  21489. /* Since avail_out is 0, deflate will be called again with
  21490. * more output space, but possibly with both pending and
  21491. * avail_in equal to zero. There won't be anything to do,
  21492. * but this is not an error situation so make sure we
  21493. * return OK instead of BUF_ERROR at next call of deflate:
  21494. */
  21495. s.last_flush = -1;
  21496. return Z_OK;
  21497. }
  21498. /* Make sure there is something to do and avoid duplicate consecutive
  21499. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21500. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21501. */
  21502. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21503. flush !== Z_FINISH) {
  21504. return err(strm, Z_BUF_ERROR);
  21505. }
  21506. /* User must not provide more input after the first FINISH: */
  21507. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21508. return err(strm, Z_BUF_ERROR);
  21509. }
  21510. /* Start a new block or continue the current one.
  21511. */
  21512. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21513. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21514. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21515. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21516. configuration_table[s.level].func(s, flush));
  21517. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21518. s.status = FINISH_STATE;
  21519. }
  21520. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21521. if (strm.avail_out === 0) {
  21522. s.last_flush = -1;
  21523. /* avoid BUF_ERROR next call, see above */
  21524. }
  21525. return Z_OK;
  21526. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21527. * of deflate should use the same flush parameter to make sure
  21528. * that the flush is complete. So we don't have to output an
  21529. * empty block here, this will be done at next call. This also
  21530. * ensures that for a very small output buffer, we emit at most
  21531. * one empty block.
  21532. */
  21533. }
  21534. if (bstate === BS_BLOCK_DONE) {
  21535. if (flush === Z_PARTIAL_FLUSH) {
  21536. trees._tr_align(s);
  21537. }
  21538. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21539. trees._tr_stored_block(s, 0, 0, false);
  21540. /* For a full flush, this empty block will be recognized
  21541. * as a special marker by inflate_sync().
  21542. */
  21543. if (flush === Z_FULL_FLUSH) {
  21544. /*** CLEAR_HASH(s); ***/ /* forget history */
  21545. zero(s.head); // Fill with NIL (= 0);
  21546. if (s.lookahead === 0) {
  21547. s.strstart = 0;
  21548. s.block_start = 0;
  21549. s.insert = 0;
  21550. }
  21551. }
  21552. }
  21553. flush_pending(strm);
  21554. if (strm.avail_out === 0) {
  21555. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21556. return Z_OK;
  21557. }
  21558. }
  21559. }
  21560. //Assert(strm->avail_out > 0, "bug2");
  21561. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21562. if (flush !== Z_FINISH) { return Z_OK; }
  21563. if (s.wrap <= 0) { return Z_STREAM_END; }
  21564. /* Write the trailer */
  21565. if (s.wrap === 2) {
  21566. put_byte(s, strm.adler & 0xff);
  21567. put_byte(s, (strm.adler >> 8) & 0xff);
  21568. put_byte(s, (strm.adler >> 16) & 0xff);
  21569. put_byte(s, (strm.adler >> 24) & 0xff);
  21570. put_byte(s, strm.total_in & 0xff);
  21571. put_byte(s, (strm.total_in >> 8) & 0xff);
  21572. put_byte(s, (strm.total_in >> 16) & 0xff);
  21573. put_byte(s, (strm.total_in >> 24) & 0xff);
  21574. }
  21575. else
  21576. {
  21577. putShortMSB(s, strm.adler >>> 16);
  21578. putShortMSB(s, strm.adler & 0xffff);
  21579. }
  21580. flush_pending(strm);
  21581. /* If avail_out is zero, the application will call deflate again
  21582. * to flush the rest.
  21583. */
  21584. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21585. /* write the trailer only once! */
  21586. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21587. }
  21588. function deflateEnd(strm) {
  21589. var status;
  21590. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21591. return Z_STREAM_ERROR;
  21592. }
  21593. status = strm.state.status;
  21594. if (status !== INIT_STATE &&
  21595. status !== EXTRA_STATE &&
  21596. status !== NAME_STATE &&
  21597. status !== COMMENT_STATE &&
  21598. status !== HCRC_STATE &&
  21599. status !== BUSY_STATE &&
  21600. status !== FINISH_STATE
  21601. ) {
  21602. return err(strm, Z_STREAM_ERROR);
  21603. }
  21604. strm.state = null;
  21605. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21606. }
  21607. /* =========================================================================
  21608. * Copy the source state to the destination state
  21609. */
  21610. //function deflateCopy(dest, source) {
  21611. //
  21612. //}
  21613. exports.deflateInit = deflateInit;
  21614. exports.deflateInit2 = deflateInit2;
  21615. exports.deflateReset = deflateReset;
  21616. exports.deflateResetKeep = deflateResetKeep;
  21617. exports.deflateSetHeader = deflateSetHeader;
  21618. exports.deflate = deflate;
  21619. exports.deflateEnd = deflateEnd;
  21620. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21621. /* Not implemented
  21622. exports.deflateBound = deflateBound;
  21623. exports.deflateCopy = deflateCopy;
  21624. exports.deflateSetDictionary = deflateSetDictionary;
  21625. exports.deflateParams = deflateParams;
  21626. exports.deflatePending = deflatePending;
  21627. exports.deflatePrime = deflatePrime;
  21628. exports.deflateTune = deflateTune;
  21629. */
  21630. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./messages":82,"./trees":83}],78:[function(require,module,exports){
  21631. 'use strict';
  21632. function GZheader() {
  21633. /* true if compressed data believed to be text */
  21634. this.text = 0;
  21635. /* modification time */
  21636. this.time = 0;
  21637. /* extra flags (not used when writing a gzip file) */
  21638. this.xflags = 0;
  21639. /* operating system */
  21640. this.os = 0;
  21641. /* pointer to extra field or Z_NULL if none */
  21642. this.extra = null;
  21643. /* extra field length (valid if extra != Z_NULL) */
  21644. this.extra_len = 0; // Actually, we don't need it in JS,
  21645. // but leave for few code modifications
  21646. //
  21647. // Setup limits is not necessary because in js we should not preallocate memory
  21648. // for inflate use constant limit in 65536 bytes
  21649. //
  21650. /* space at extra (only when reading header) */
  21651. // this.extra_max = 0;
  21652. /* pointer to zero-terminated file name or Z_NULL */
  21653. this.name = '';
  21654. /* space at name (only when reading header) */
  21655. // this.name_max = 0;
  21656. /* pointer to zero-terminated comment or Z_NULL */
  21657. this.comment = '';
  21658. /* space at comment (only when reading header) */
  21659. // this.comm_max = 0;
  21660. /* true if there was or will be a header crc */
  21661. this.hcrc = 0;
  21662. /* true when done reading gzip header (not used when writing a gzip file) */
  21663. this.done = false;
  21664. }
  21665. module.exports = GZheader;
  21666. },{}],79:[function(require,module,exports){
  21667. 'use strict';
  21668. // See state defs from inflate.js
  21669. var BAD = 30; /* got a data error -- remain here until reset */
  21670. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21671. /*
  21672. Decode literal, length, and distance codes and write out the resulting
  21673. literal and match bytes until either not enough input or output is
  21674. available, an end-of-block is encountered, or a data error is encountered.
  21675. When large enough input and output buffers are supplied to inflate(), for
  21676. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21677. inflate execution time is spent in this routine.
  21678. Entry assumptions:
  21679. state.mode === LEN
  21680. strm.avail_in >= 6
  21681. strm.avail_out >= 258
  21682. start >= strm.avail_out
  21683. state.bits < 8
  21684. On return, state.mode is one of:
  21685. LEN -- ran out of enough output space or enough available input
  21686. TYPE -- reached end of block code, inflate() to interpret next block
  21687. BAD -- error in block data
  21688. Notes:
  21689. - The maximum input bits used by a length/distance pair is 15 bits for the
  21690. length code, 5 bits for the length extra, 15 bits for the distance code,
  21691. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21692. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21693. checking for available input while decoding.
  21694. - The maximum bytes that a single length/distance pair can output is 258
  21695. bytes, which is the maximum length that can be coded. inflate_fast()
  21696. requires strm.avail_out >= 258 for each loop to avoid checking for
  21697. output space.
  21698. */
  21699. module.exports = function inflate_fast(strm, start) {
  21700. var state;
  21701. var _in; /* local strm.input */
  21702. var last; /* have enough input while in < last */
  21703. var _out; /* local strm.output */
  21704. var beg; /* inflate()'s initial strm.output */
  21705. var end; /* while out < end, enough space available */
  21706. //#ifdef INFLATE_STRICT
  21707. var dmax; /* maximum distance from zlib header */
  21708. //#endif
  21709. var wsize; /* window size or zero if not using window */
  21710. var whave; /* valid bytes in the window */
  21711. var wnext; /* window write index */
  21712. var window; /* allocated sliding window, if wsize != 0 */
  21713. var hold; /* local strm.hold */
  21714. var bits; /* local strm.bits */
  21715. var lcode; /* local strm.lencode */
  21716. var dcode; /* local strm.distcode */
  21717. var lmask; /* mask for first level of length codes */
  21718. var dmask; /* mask for first level of distance codes */
  21719. var here; /* retrieved table entry */
  21720. var op; /* code bits, operation, extra bits, or */
  21721. /* window position, window bytes to copy */
  21722. var len; /* match length, unused bytes */
  21723. var dist; /* match distance */
  21724. var from; /* where to copy match from */
  21725. var from_source;
  21726. var input, output; // JS specific, because we have no pointers
  21727. /* copy state to local variables */
  21728. state = strm.state;
  21729. //here = state.here;
  21730. _in = strm.next_in;
  21731. input = strm.input;
  21732. last = _in + (strm.avail_in - 5);
  21733. _out = strm.next_out;
  21734. output = strm.output;
  21735. beg = _out - (start - strm.avail_out);
  21736. end = _out + (strm.avail_out - 257);
  21737. //#ifdef INFLATE_STRICT
  21738. dmax = state.dmax;
  21739. //#endif
  21740. wsize = state.wsize;
  21741. whave = state.whave;
  21742. wnext = state.wnext;
  21743. window = state.window;
  21744. hold = state.hold;
  21745. bits = state.bits;
  21746. lcode = state.lencode;
  21747. dcode = state.distcode;
  21748. lmask = (1 << state.lenbits) - 1;
  21749. dmask = (1 << state.distbits) - 1;
  21750. /* decode literals and length/distances until end-of-block or not enough
  21751. input data or output space */
  21752. top:
  21753. do {
  21754. if (bits < 15) {
  21755. hold += input[_in++] << bits;
  21756. bits += 8;
  21757. hold += input[_in++] << bits;
  21758. bits += 8;
  21759. }
  21760. here = lcode[hold & lmask];
  21761. dolen:
  21762. for (;;) { // Goto emulation
  21763. op = here >>> 24/*here.bits*/;
  21764. hold >>>= op;
  21765. bits -= op;
  21766. op = (here >>> 16) & 0xff/*here.op*/;
  21767. if (op === 0) { /* literal */
  21768. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21769. // "inflate: literal '%c'\n" :
  21770. // "inflate: literal 0x%02x\n", here.val));
  21771. output[_out++] = here & 0xffff/*here.val*/;
  21772. }
  21773. else if (op & 16) { /* length base */
  21774. len = here & 0xffff/*here.val*/;
  21775. op &= 15; /* number of extra bits */
  21776. if (op) {
  21777. if (bits < op) {
  21778. hold += input[_in++] << bits;
  21779. bits += 8;
  21780. }
  21781. len += hold & ((1 << op) - 1);
  21782. hold >>>= op;
  21783. bits -= op;
  21784. }
  21785. //Tracevv((stderr, "inflate: length %u\n", len));
  21786. if (bits < 15) {
  21787. hold += input[_in++] << bits;
  21788. bits += 8;
  21789. hold += input[_in++] << bits;
  21790. bits += 8;
  21791. }
  21792. here = dcode[hold & dmask];
  21793. dodist:
  21794. for (;;) { // goto emulation
  21795. op = here >>> 24/*here.bits*/;
  21796. hold >>>= op;
  21797. bits -= op;
  21798. op = (here >>> 16) & 0xff/*here.op*/;
  21799. if (op & 16) { /* distance base */
  21800. dist = here & 0xffff/*here.val*/;
  21801. op &= 15; /* number of extra bits */
  21802. if (bits < op) {
  21803. hold += input[_in++] << bits;
  21804. bits += 8;
  21805. if (bits < op) {
  21806. hold += input[_in++] << bits;
  21807. bits += 8;
  21808. }
  21809. }
  21810. dist += hold & ((1 << op) - 1);
  21811. //#ifdef INFLATE_STRICT
  21812. if (dist > dmax) {
  21813. strm.msg = 'invalid distance too far back';
  21814. state.mode = BAD;
  21815. break top;
  21816. }
  21817. //#endif
  21818. hold >>>= op;
  21819. bits -= op;
  21820. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21821. op = _out - beg; /* max distance in output */
  21822. if (dist > op) { /* see if copy from window */
  21823. op = dist - op; /* distance back in window */
  21824. if (op > whave) {
  21825. if (state.sane) {
  21826. strm.msg = 'invalid distance too far back';
  21827. state.mode = BAD;
  21828. break top;
  21829. }
  21830. // (!) This block is disabled in zlib defailts,
  21831. // don't enable it for binary compatibility
  21832. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21833. // if (len <= op - whave) {
  21834. // do {
  21835. // output[_out++] = 0;
  21836. // } while (--len);
  21837. // continue top;
  21838. // }
  21839. // len -= op - whave;
  21840. // do {
  21841. // output[_out++] = 0;
  21842. // } while (--op > whave);
  21843. // if (op === 0) {
  21844. // from = _out - dist;
  21845. // do {
  21846. // output[_out++] = output[from++];
  21847. // } while (--len);
  21848. // continue top;
  21849. // }
  21850. //#endif
  21851. }
  21852. from = 0; // window index
  21853. from_source = window;
  21854. if (wnext === 0) { /* very common case */
  21855. from += wsize - op;
  21856. if (op < len) { /* some from window */
  21857. len -= op;
  21858. do {
  21859. output[_out++] = window[from++];
  21860. } while (--op);
  21861. from = _out - dist; /* rest from output */
  21862. from_source = output;
  21863. }
  21864. }
  21865. else if (wnext < op) { /* wrap around window */
  21866. from += wsize + wnext - op;
  21867. op -= wnext;
  21868. if (op < len) { /* some from end of window */
  21869. len -= op;
  21870. do {
  21871. output[_out++] = window[from++];
  21872. } while (--op);
  21873. from = 0;
  21874. if (wnext < len) { /* some from start of window */
  21875. op = wnext;
  21876. len -= op;
  21877. do {
  21878. output[_out++] = window[from++];
  21879. } while (--op);
  21880. from = _out - dist; /* rest from output */
  21881. from_source = output;
  21882. }
  21883. }
  21884. }
  21885. else { /* contiguous in window */
  21886. from += wnext - op;
  21887. if (op < len) { /* some from window */
  21888. len -= op;
  21889. do {
  21890. output[_out++] = window[from++];
  21891. } while (--op);
  21892. from = _out - dist; /* rest from output */
  21893. from_source = output;
  21894. }
  21895. }
  21896. while (len > 2) {
  21897. output[_out++] = from_source[from++];
  21898. output[_out++] = from_source[from++];
  21899. output[_out++] = from_source[from++];
  21900. len -= 3;
  21901. }
  21902. if (len) {
  21903. output[_out++] = from_source[from++];
  21904. if (len > 1) {
  21905. output[_out++] = from_source[from++];
  21906. }
  21907. }
  21908. }
  21909. else {
  21910. from = _out - dist; /* copy direct from output */
  21911. do { /* minimum length is three */
  21912. output[_out++] = output[from++];
  21913. output[_out++] = output[from++];
  21914. output[_out++] = output[from++];
  21915. len -= 3;
  21916. } while (len > 2);
  21917. if (len) {
  21918. output[_out++] = output[from++];
  21919. if (len > 1) {
  21920. output[_out++] = output[from++];
  21921. }
  21922. }
  21923. }
  21924. }
  21925. else if ((op & 64) === 0) { /* 2nd level distance code */
  21926. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21927. continue dodist;
  21928. }
  21929. else {
  21930. strm.msg = 'invalid distance code';
  21931. state.mode = BAD;
  21932. break top;
  21933. }
  21934. break; // need to emulate goto via "continue"
  21935. }
  21936. }
  21937. else if ((op & 64) === 0) { /* 2nd level length code */
  21938. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21939. continue dolen;
  21940. }
  21941. else if (op & 32) { /* end-of-block */
  21942. //Tracevv((stderr, "inflate: end of block\n"));
  21943. state.mode = TYPE;
  21944. break top;
  21945. }
  21946. else {
  21947. strm.msg = 'invalid literal/length code';
  21948. state.mode = BAD;
  21949. break top;
  21950. }
  21951. break; // need to emulate goto via "continue"
  21952. }
  21953. } while (_in < last && _out < end);
  21954. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  21955. len = bits >> 3;
  21956. _in -= len;
  21957. bits -= len << 3;
  21958. hold &= (1 << bits) - 1;
  21959. /* update state and return */
  21960. strm.next_in = _in;
  21961. strm.next_out = _out;
  21962. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  21963. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  21964. state.hold = hold;
  21965. state.bits = bits;
  21966. return;
  21967. };
  21968. },{}],80:[function(require,module,exports){
  21969. 'use strict';
  21970. var utils = require('../utils/common');
  21971. var adler32 = require('./adler32');
  21972. var crc32 = require('./crc32');
  21973. var inflate_fast = require('./inffast');
  21974. var inflate_table = require('./inftrees');
  21975. var CODES = 0;
  21976. var LENS = 1;
  21977. var DISTS = 2;
  21978. /* Public constants ==========================================================*/
  21979. /* ===========================================================================*/
  21980. /* Allowed flush values; see deflate() and inflate() below for details */
  21981. //var Z_NO_FLUSH = 0;
  21982. //var Z_PARTIAL_FLUSH = 1;
  21983. //var Z_SYNC_FLUSH = 2;
  21984. //var Z_FULL_FLUSH = 3;
  21985. var Z_FINISH = 4;
  21986. var Z_BLOCK = 5;
  21987. var Z_TREES = 6;
  21988. /* Return codes for the compression/decompression functions. Negative values
  21989. * are errors, positive values are used for special but normal events.
  21990. */
  21991. var Z_OK = 0;
  21992. var Z_STREAM_END = 1;
  21993. var Z_NEED_DICT = 2;
  21994. //var Z_ERRNO = -1;
  21995. var Z_STREAM_ERROR = -2;
  21996. var Z_DATA_ERROR = -3;
  21997. var Z_MEM_ERROR = -4;
  21998. var Z_BUF_ERROR = -5;
  21999. //var Z_VERSION_ERROR = -6;
  22000. /* The deflate compression method */
  22001. var Z_DEFLATED = 8;
  22002. /* STATES ====================================================================*/
  22003. /* ===========================================================================*/
  22004. var HEAD = 1; /* i: waiting for magic header */
  22005. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22006. var TIME = 3; /* i: waiting for modification time (gzip) */
  22007. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22008. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22009. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22010. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22011. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22012. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22013. var DICTID = 10; /* i: waiting for dictionary check value */
  22014. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22015. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22016. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22017. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22018. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22019. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22020. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22021. var LENLENS = 18; /* i: waiting for code length code lengths */
  22022. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22023. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22024. var LEN = 21; /* i: waiting for length/lit/eob code */
  22025. var LENEXT = 22; /* i: waiting for length extra bits */
  22026. var DIST = 23; /* i: waiting for distance code */
  22027. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22028. var MATCH = 25; /* o: waiting for output space to copy string */
  22029. var LIT = 26; /* o: waiting for output space to write literal */
  22030. var CHECK = 27; /* i: waiting for 32-bit check value */
  22031. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22032. var DONE = 29; /* finished check, done -- remain here until reset */
  22033. var BAD = 30; /* got a data error -- remain here until reset */
  22034. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22035. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22036. /* ===========================================================================*/
  22037. var ENOUGH_LENS = 852;
  22038. var ENOUGH_DISTS = 592;
  22039. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22040. var MAX_WBITS = 15;
  22041. /* 32K LZ77 window */
  22042. var DEF_WBITS = MAX_WBITS;
  22043. function ZSWAP32(q) {
  22044. return (((q >>> 24) & 0xff) +
  22045. ((q >>> 8) & 0xff00) +
  22046. ((q & 0xff00) << 8) +
  22047. ((q & 0xff) << 24));
  22048. }
  22049. function InflateState() {
  22050. this.mode = 0; /* current inflate mode */
  22051. this.last = false; /* true if processing last block */
  22052. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22053. this.havedict = false; /* true if dictionary provided */
  22054. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22055. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22056. this.check = 0; /* protected copy of check value */
  22057. this.total = 0; /* protected copy of output count */
  22058. // TODO: may be {}
  22059. this.head = null; /* where to save gzip header information */
  22060. /* sliding window */
  22061. this.wbits = 0; /* log base 2 of requested window size */
  22062. this.wsize = 0; /* window size or zero if not using window */
  22063. this.whave = 0; /* valid bytes in the window */
  22064. this.wnext = 0; /* window write index */
  22065. this.window = null; /* allocated sliding window, if needed */
  22066. /* bit accumulator */
  22067. this.hold = 0; /* input bit accumulator */
  22068. this.bits = 0; /* number of bits in "in" */
  22069. /* for string and stored block copying */
  22070. this.length = 0; /* literal or length of data to copy */
  22071. this.offset = 0; /* distance back to copy string from */
  22072. /* for table and code decoding */
  22073. this.extra = 0; /* extra bits needed */
  22074. /* fixed and dynamic code tables */
  22075. this.lencode = null; /* starting table for length/literal codes */
  22076. this.distcode = null; /* starting table for distance codes */
  22077. this.lenbits = 0; /* index bits for lencode */
  22078. this.distbits = 0; /* index bits for distcode */
  22079. /* dynamic table building */
  22080. this.ncode = 0; /* number of code length code lengths */
  22081. this.nlen = 0; /* number of length code lengths */
  22082. this.ndist = 0; /* number of distance code lengths */
  22083. this.have = 0; /* number of code lengths in lens[] */
  22084. this.next = null; /* next available space in codes[] */
  22085. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22086. this.work = new utils.Buf16(288); /* work area for code table building */
  22087. /*
  22088. because we don't have pointers in js, we use lencode and distcode directly
  22089. as buffers so we don't need codes
  22090. */
  22091. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22092. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22093. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22094. this.sane = 0; /* if false, allow invalid distance too far */
  22095. this.back = 0; /* bits back of last unprocessed length/lit */
  22096. this.was = 0; /* initial length of match */
  22097. }
  22098. function inflateResetKeep(strm) {
  22099. var state;
  22100. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22101. state = strm.state;
  22102. strm.total_in = strm.total_out = state.total = 0;
  22103. strm.msg = ''; /*Z_NULL*/
  22104. if (state.wrap) { /* to support ill-conceived Java test suite */
  22105. strm.adler = state.wrap & 1;
  22106. }
  22107. state.mode = HEAD;
  22108. state.last = 0;
  22109. state.havedict = 0;
  22110. state.dmax = 32768;
  22111. state.head = null/*Z_NULL*/;
  22112. state.hold = 0;
  22113. state.bits = 0;
  22114. //state.lencode = state.distcode = state.next = state.codes;
  22115. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22116. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22117. state.sane = 1;
  22118. state.back = -1;
  22119. //Tracev((stderr, "inflate: reset\n"));
  22120. return Z_OK;
  22121. }
  22122. function inflateReset(strm) {
  22123. var state;
  22124. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22125. state = strm.state;
  22126. state.wsize = 0;
  22127. state.whave = 0;
  22128. state.wnext = 0;
  22129. return inflateResetKeep(strm);
  22130. }
  22131. function inflateReset2(strm, windowBits) {
  22132. var wrap;
  22133. var state;
  22134. /* get the state */
  22135. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22136. state = strm.state;
  22137. /* extract wrap request from windowBits parameter */
  22138. if (windowBits < 0) {
  22139. wrap = 0;
  22140. windowBits = -windowBits;
  22141. }
  22142. else {
  22143. wrap = (windowBits >> 4) + 1;
  22144. if (windowBits < 48) {
  22145. windowBits &= 15;
  22146. }
  22147. }
  22148. /* set number of window bits, free window if different */
  22149. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22150. return Z_STREAM_ERROR;
  22151. }
  22152. if (state.window !== null && state.wbits !== windowBits) {
  22153. state.window = null;
  22154. }
  22155. /* update state and reset the rest of it */
  22156. state.wrap = wrap;
  22157. state.wbits = windowBits;
  22158. return inflateReset(strm);
  22159. }
  22160. function inflateInit2(strm, windowBits) {
  22161. var ret;
  22162. var state;
  22163. if (!strm) { return Z_STREAM_ERROR; }
  22164. //strm.msg = Z_NULL; /* in case we return an error */
  22165. state = new InflateState();
  22166. //if (state === Z_NULL) return Z_MEM_ERROR;
  22167. //Tracev((stderr, "inflate: allocated\n"));
  22168. strm.state = state;
  22169. state.window = null/*Z_NULL*/;
  22170. ret = inflateReset2(strm, windowBits);
  22171. if (ret !== Z_OK) {
  22172. strm.state = null/*Z_NULL*/;
  22173. }
  22174. return ret;
  22175. }
  22176. function inflateInit(strm) {
  22177. return inflateInit2(strm, DEF_WBITS);
  22178. }
  22179. /*
  22180. Return state with length and distance decoding tables and index sizes set to
  22181. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22182. If BUILDFIXED is defined, then instead this routine builds the tables the
  22183. first time it's called, and returns those tables the first time and
  22184. thereafter. This reduces the size of the code by about 2K bytes, in
  22185. exchange for a little execution time. However, BUILDFIXED should not be
  22186. used for threaded applications, since the rewriting of the tables and virgin
  22187. may not be thread-safe.
  22188. */
  22189. var virgin = true;
  22190. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22191. function fixedtables(state) {
  22192. /* build fixed huffman tables if first call (may not be thread safe) */
  22193. if (virgin) {
  22194. var sym;
  22195. lenfix = new utils.Buf32(512);
  22196. distfix = new utils.Buf32(32);
  22197. /* literal/length table */
  22198. sym = 0;
  22199. while (sym < 144) { state.lens[sym++] = 8; }
  22200. while (sym < 256) { state.lens[sym++] = 9; }
  22201. while (sym < 280) { state.lens[sym++] = 7; }
  22202. while (sym < 288) { state.lens[sym++] = 8; }
  22203. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22204. /* distance table */
  22205. sym = 0;
  22206. while (sym < 32) { state.lens[sym++] = 5; }
  22207. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22208. /* do this just once */
  22209. virgin = false;
  22210. }
  22211. state.lencode = lenfix;
  22212. state.lenbits = 9;
  22213. state.distcode = distfix;
  22214. state.distbits = 5;
  22215. }
  22216. /*
  22217. Update the window with the last wsize (normally 32K) bytes written before
  22218. returning. If window does not exist yet, create it. This is only called
  22219. when a window is already in use, or when output has been written during this
  22220. inflate call, but the end of the deflate stream has not been reached yet.
  22221. It is also called to create a window for dictionary data when a dictionary
  22222. is loaded.
  22223. Providing output buffers larger than 32K to inflate() should provide a speed
  22224. advantage, since only the last 32K of output is copied to the sliding window
  22225. upon return from inflate(), and since all distances after the first 32K of
  22226. output will fall in the output data, making match copies simpler and faster.
  22227. The advantage may be dependent on the size of the processor's data caches.
  22228. */
  22229. function updatewindow(strm, src, end, copy) {
  22230. var dist;
  22231. var state = strm.state;
  22232. /* if it hasn't been done already, allocate space for the window */
  22233. if (state.window === null) {
  22234. state.wsize = 1 << state.wbits;
  22235. state.wnext = 0;
  22236. state.whave = 0;
  22237. state.window = new utils.Buf8(state.wsize);
  22238. }
  22239. /* copy state->wsize or less output bytes into the circular window */
  22240. if (copy >= state.wsize) {
  22241. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22242. state.wnext = 0;
  22243. state.whave = state.wsize;
  22244. }
  22245. else {
  22246. dist = state.wsize - state.wnext;
  22247. if (dist > copy) {
  22248. dist = copy;
  22249. }
  22250. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22251. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22252. copy -= dist;
  22253. if (copy) {
  22254. //zmemcpy(state->window, end - copy, copy);
  22255. utils.arraySet(state.window,src, end - copy, copy, 0);
  22256. state.wnext = copy;
  22257. state.whave = state.wsize;
  22258. }
  22259. else {
  22260. state.wnext += dist;
  22261. if (state.wnext === state.wsize) { state.wnext = 0; }
  22262. if (state.whave < state.wsize) { state.whave += dist; }
  22263. }
  22264. }
  22265. return 0;
  22266. }
  22267. function inflate(strm, flush) {
  22268. var state;
  22269. var input, output; // input/output buffers
  22270. var next; /* next input INDEX */
  22271. var put; /* next output INDEX */
  22272. var have, left; /* available input and output */
  22273. var hold; /* bit buffer */
  22274. var bits; /* bits in bit buffer */
  22275. var _in, _out; /* save starting available input and output */
  22276. var copy; /* number of stored or match bytes to copy */
  22277. var from; /* where to copy match bytes from */
  22278. var from_source;
  22279. var here = 0; /* current decoding table entry */
  22280. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22281. //var last; /* parent table entry */
  22282. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22283. var len; /* length to copy for repeats, bits to drop */
  22284. var ret; /* return code */
  22285. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22286. var opts;
  22287. var n; // temporary var for NEED_BITS
  22288. var order = /* permutation of code lengths */
  22289. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22290. if (!strm || !strm.state || !strm.output ||
  22291. (!strm.input && strm.avail_in !== 0)) {
  22292. return Z_STREAM_ERROR;
  22293. }
  22294. state = strm.state;
  22295. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22296. //--- LOAD() ---
  22297. put = strm.next_out;
  22298. output = strm.output;
  22299. left = strm.avail_out;
  22300. next = strm.next_in;
  22301. input = strm.input;
  22302. have = strm.avail_in;
  22303. hold = state.hold;
  22304. bits = state.bits;
  22305. //---
  22306. _in = have;
  22307. _out = left;
  22308. ret = Z_OK;
  22309. inf_leave: // goto emulation
  22310. for (;;) {
  22311. switch (state.mode) {
  22312. case HEAD:
  22313. if (state.wrap === 0) {
  22314. state.mode = TYPEDO;
  22315. break;
  22316. }
  22317. //=== NEEDBITS(16);
  22318. while (bits < 16) {
  22319. if (have === 0) { break inf_leave; }
  22320. have--;
  22321. hold += input[next++] << bits;
  22322. bits += 8;
  22323. }
  22324. //===//
  22325. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22326. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22327. //=== CRC2(state.check, hold);
  22328. hbuf[0] = hold & 0xff;
  22329. hbuf[1] = (hold >>> 8) & 0xff;
  22330. state.check = crc32(state.check, hbuf, 2, 0);
  22331. //===//
  22332. //=== INITBITS();
  22333. hold = 0;
  22334. bits = 0;
  22335. //===//
  22336. state.mode = FLAGS;
  22337. break;
  22338. }
  22339. state.flags = 0; /* expect zlib header */
  22340. if (state.head) {
  22341. state.head.done = false;
  22342. }
  22343. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22344. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22345. strm.msg = 'incorrect header check';
  22346. state.mode = BAD;
  22347. break;
  22348. }
  22349. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22350. strm.msg = 'unknown compression method';
  22351. state.mode = BAD;
  22352. break;
  22353. }
  22354. //--- DROPBITS(4) ---//
  22355. hold >>>= 4;
  22356. bits -= 4;
  22357. //---//
  22358. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22359. if (state.wbits === 0) {
  22360. state.wbits = len;
  22361. }
  22362. else if (len > state.wbits) {
  22363. strm.msg = 'invalid window size';
  22364. state.mode = BAD;
  22365. break;
  22366. }
  22367. state.dmax = 1 << len;
  22368. //Tracev((stderr, "inflate: zlib header ok\n"));
  22369. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22370. state.mode = hold & 0x200 ? DICTID : TYPE;
  22371. //=== INITBITS();
  22372. hold = 0;
  22373. bits = 0;
  22374. //===//
  22375. break;
  22376. case FLAGS:
  22377. //=== NEEDBITS(16); */
  22378. while (bits < 16) {
  22379. if (have === 0) { break inf_leave; }
  22380. have--;
  22381. hold += input[next++] << bits;
  22382. bits += 8;
  22383. }
  22384. //===//
  22385. state.flags = hold;
  22386. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22387. strm.msg = 'unknown compression method';
  22388. state.mode = BAD;
  22389. break;
  22390. }
  22391. if (state.flags & 0xe000) {
  22392. strm.msg = 'unknown header flags set';
  22393. state.mode = BAD;
  22394. break;
  22395. }
  22396. if (state.head) {
  22397. state.head.text = ((hold >> 8) & 1);
  22398. }
  22399. if (state.flags & 0x0200) {
  22400. //=== CRC2(state.check, hold);
  22401. hbuf[0] = hold & 0xff;
  22402. hbuf[1] = (hold >>> 8) & 0xff;
  22403. state.check = crc32(state.check, hbuf, 2, 0);
  22404. //===//
  22405. }
  22406. //=== INITBITS();
  22407. hold = 0;
  22408. bits = 0;
  22409. //===//
  22410. state.mode = TIME;
  22411. /* falls through */
  22412. case TIME:
  22413. //=== NEEDBITS(32); */
  22414. while (bits < 32) {
  22415. if (have === 0) { break inf_leave; }
  22416. have--;
  22417. hold += input[next++] << bits;
  22418. bits += 8;
  22419. }
  22420. //===//
  22421. if (state.head) {
  22422. state.head.time = hold;
  22423. }
  22424. if (state.flags & 0x0200) {
  22425. //=== CRC4(state.check, hold)
  22426. hbuf[0] = hold & 0xff;
  22427. hbuf[1] = (hold >>> 8) & 0xff;
  22428. hbuf[2] = (hold >>> 16) & 0xff;
  22429. hbuf[3] = (hold >>> 24) & 0xff;
  22430. state.check = crc32(state.check, hbuf, 4, 0);
  22431. //===
  22432. }
  22433. //=== INITBITS();
  22434. hold = 0;
  22435. bits = 0;
  22436. //===//
  22437. state.mode = OS;
  22438. /* falls through */
  22439. case OS:
  22440. //=== NEEDBITS(16); */
  22441. while (bits < 16) {
  22442. if (have === 0) { break inf_leave; }
  22443. have--;
  22444. hold += input[next++] << bits;
  22445. bits += 8;
  22446. }
  22447. //===//
  22448. if (state.head) {
  22449. state.head.xflags = (hold & 0xff);
  22450. state.head.os = (hold >> 8);
  22451. }
  22452. if (state.flags & 0x0200) {
  22453. //=== CRC2(state.check, hold);
  22454. hbuf[0] = hold & 0xff;
  22455. hbuf[1] = (hold >>> 8) & 0xff;
  22456. state.check = crc32(state.check, hbuf, 2, 0);
  22457. //===//
  22458. }
  22459. //=== INITBITS();
  22460. hold = 0;
  22461. bits = 0;
  22462. //===//
  22463. state.mode = EXLEN;
  22464. /* falls through */
  22465. case EXLEN:
  22466. if (state.flags & 0x0400) {
  22467. //=== NEEDBITS(16); */
  22468. while (bits < 16) {
  22469. if (have === 0) { break inf_leave; }
  22470. have--;
  22471. hold += input[next++] << bits;
  22472. bits += 8;
  22473. }
  22474. //===//
  22475. state.length = hold;
  22476. if (state.head) {
  22477. state.head.extra_len = hold;
  22478. }
  22479. if (state.flags & 0x0200) {
  22480. //=== CRC2(state.check, hold);
  22481. hbuf[0] = hold & 0xff;
  22482. hbuf[1] = (hold >>> 8) & 0xff;
  22483. state.check = crc32(state.check, hbuf, 2, 0);
  22484. //===//
  22485. }
  22486. //=== INITBITS();
  22487. hold = 0;
  22488. bits = 0;
  22489. //===//
  22490. }
  22491. else if (state.head) {
  22492. state.head.extra = null/*Z_NULL*/;
  22493. }
  22494. state.mode = EXTRA;
  22495. /* falls through */
  22496. case EXTRA:
  22497. if (state.flags & 0x0400) {
  22498. copy = state.length;
  22499. if (copy > have) { copy = have; }
  22500. if (copy) {
  22501. if (state.head) {
  22502. len = state.head.extra_len - state.length;
  22503. if (!state.head.extra) {
  22504. // Use untyped array for more conveniend processing later
  22505. state.head.extra = new Array(state.head.extra_len);
  22506. }
  22507. utils.arraySet(
  22508. state.head.extra,
  22509. input,
  22510. next,
  22511. // extra field is limited to 65536 bytes
  22512. // - no need for additional size check
  22513. copy,
  22514. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22515. len
  22516. );
  22517. //zmemcpy(state.head.extra + len, next,
  22518. // len + copy > state.head.extra_max ?
  22519. // state.head.extra_max - len : copy);
  22520. }
  22521. if (state.flags & 0x0200) {
  22522. state.check = crc32(state.check, input, copy, next);
  22523. }
  22524. have -= copy;
  22525. next += copy;
  22526. state.length -= copy;
  22527. }
  22528. if (state.length) { break inf_leave; }
  22529. }
  22530. state.length = 0;
  22531. state.mode = NAME;
  22532. /* falls through */
  22533. case NAME:
  22534. if (state.flags & 0x0800) {
  22535. if (have === 0) { break inf_leave; }
  22536. copy = 0;
  22537. do {
  22538. // TODO: 2 or 1 bytes?
  22539. len = input[next + copy++];
  22540. /* use constant limit because in js we should not preallocate memory */
  22541. if (state.head && len &&
  22542. (state.length < 65536 /*state.head.name_max*/)) {
  22543. state.head.name += String.fromCharCode(len);
  22544. }
  22545. } while (len && copy < have);
  22546. if (state.flags & 0x0200) {
  22547. state.check = crc32(state.check, input, copy, next);
  22548. }
  22549. have -= copy;
  22550. next += copy;
  22551. if (len) { break inf_leave; }
  22552. }
  22553. else if (state.head) {
  22554. state.head.name = null;
  22555. }
  22556. state.length = 0;
  22557. state.mode = COMMENT;
  22558. /* falls through */
  22559. case COMMENT:
  22560. if (state.flags & 0x1000) {
  22561. if (have === 0) { break inf_leave; }
  22562. copy = 0;
  22563. do {
  22564. len = input[next + copy++];
  22565. /* use constant limit because in js we should not preallocate memory */
  22566. if (state.head && len &&
  22567. (state.length < 65536 /*state.head.comm_max*/)) {
  22568. state.head.comment += String.fromCharCode(len);
  22569. }
  22570. } while (len && copy < have);
  22571. if (state.flags & 0x0200) {
  22572. state.check = crc32(state.check, input, copy, next);
  22573. }
  22574. have -= copy;
  22575. next += copy;
  22576. if (len) { break inf_leave; }
  22577. }
  22578. else if (state.head) {
  22579. state.head.comment = null;
  22580. }
  22581. state.mode = HCRC;
  22582. /* falls through */
  22583. case HCRC:
  22584. if (state.flags & 0x0200) {
  22585. //=== NEEDBITS(16); */
  22586. while (bits < 16) {
  22587. if (have === 0) { break inf_leave; }
  22588. have--;
  22589. hold += input[next++] << bits;
  22590. bits += 8;
  22591. }
  22592. //===//
  22593. if (hold !== (state.check & 0xffff)) {
  22594. strm.msg = 'header crc mismatch';
  22595. state.mode = BAD;
  22596. break;
  22597. }
  22598. //=== INITBITS();
  22599. hold = 0;
  22600. bits = 0;
  22601. //===//
  22602. }
  22603. if (state.head) {
  22604. state.head.hcrc = ((state.flags >> 9) & 1);
  22605. state.head.done = true;
  22606. }
  22607. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22608. state.mode = TYPE;
  22609. break;
  22610. case DICTID:
  22611. //=== NEEDBITS(32); */
  22612. while (bits < 32) {
  22613. if (have === 0) { break inf_leave; }
  22614. have--;
  22615. hold += input[next++] << bits;
  22616. bits += 8;
  22617. }
  22618. //===//
  22619. strm.adler = state.check = ZSWAP32(hold);
  22620. //=== INITBITS();
  22621. hold = 0;
  22622. bits = 0;
  22623. //===//
  22624. state.mode = DICT;
  22625. /* falls through */
  22626. case DICT:
  22627. if (state.havedict === 0) {
  22628. //--- RESTORE() ---
  22629. strm.next_out = put;
  22630. strm.avail_out = left;
  22631. strm.next_in = next;
  22632. strm.avail_in = have;
  22633. state.hold = hold;
  22634. state.bits = bits;
  22635. //---
  22636. return Z_NEED_DICT;
  22637. }
  22638. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22639. state.mode = TYPE;
  22640. /* falls through */
  22641. case TYPE:
  22642. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22643. /* falls through */
  22644. case TYPEDO:
  22645. if (state.last) {
  22646. //--- BYTEBITS() ---//
  22647. hold >>>= bits & 7;
  22648. bits -= bits & 7;
  22649. //---//
  22650. state.mode = CHECK;
  22651. break;
  22652. }
  22653. //=== NEEDBITS(3); */
  22654. while (bits < 3) {
  22655. if (have === 0) { break inf_leave; }
  22656. have--;
  22657. hold += input[next++] << bits;
  22658. bits += 8;
  22659. }
  22660. //===//
  22661. state.last = (hold & 0x01)/*BITS(1)*/;
  22662. //--- DROPBITS(1) ---//
  22663. hold >>>= 1;
  22664. bits -= 1;
  22665. //---//
  22666. switch ((hold & 0x03)/*BITS(2)*/) {
  22667. case 0: /* stored block */
  22668. //Tracev((stderr, "inflate: stored block%s\n",
  22669. // state.last ? " (last)" : ""));
  22670. state.mode = STORED;
  22671. break;
  22672. case 1: /* fixed block */
  22673. fixedtables(state);
  22674. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22675. // state.last ? " (last)" : ""));
  22676. state.mode = LEN_; /* decode codes */
  22677. if (flush === Z_TREES) {
  22678. //--- DROPBITS(2) ---//
  22679. hold >>>= 2;
  22680. bits -= 2;
  22681. //---//
  22682. break inf_leave;
  22683. }
  22684. break;
  22685. case 2: /* dynamic block */
  22686. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22687. // state.last ? " (last)" : ""));
  22688. state.mode = TABLE;
  22689. break;
  22690. case 3:
  22691. strm.msg = 'invalid block type';
  22692. state.mode = BAD;
  22693. }
  22694. //--- DROPBITS(2) ---//
  22695. hold >>>= 2;
  22696. bits -= 2;
  22697. //---//
  22698. break;
  22699. case STORED:
  22700. //--- BYTEBITS() ---// /* go to byte boundary */
  22701. hold >>>= bits & 7;
  22702. bits -= bits & 7;
  22703. //---//
  22704. //=== NEEDBITS(32); */
  22705. while (bits < 32) {
  22706. if (have === 0) { break inf_leave; }
  22707. have--;
  22708. hold += input[next++] << bits;
  22709. bits += 8;
  22710. }
  22711. //===//
  22712. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22713. strm.msg = 'invalid stored block lengths';
  22714. state.mode = BAD;
  22715. break;
  22716. }
  22717. state.length = hold & 0xffff;
  22718. //Tracev((stderr, "inflate: stored length %u\n",
  22719. // state.length));
  22720. //=== INITBITS();
  22721. hold = 0;
  22722. bits = 0;
  22723. //===//
  22724. state.mode = COPY_;
  22725. if (flush === Z_TREES) { break inf_leave; }
  22726. /* falls through */
  22727. case COPY_:
  22728. state.mode = COPY;
  22729. /* falls through */
  22730. case COPY:
  22731. copy = state.length;
  22732. if (copy) {
  22733. if (copy > have) { copy = have; }
  22734. if (copy > left) { copy = left; }
  22735. if (copy === 0) { break inf_leave; }
  22736. //--- zmemcpy(put, next, copy); ---
  22737. utils.arraySet(output, input, next, copy, put);
  22738. //---//
  22739. have -= copy;
  22740. next += copy;
  22741. left -= copy;
  22742. put += copy;
  22743. state.length -= copy;
  22744. break;
  22745. }
  22746. //Tracev((stderr, "inflate: stored end\n"));
  22747. state.mode = TYPE;
  22748. break;
  22749. case TABLE:
  22750. //=== NEEDBITS(14); */
  22751. while (bits < 14) {
  22752. if (have === 0) { break inf_leave; }
  22753. have--;
  22754. hold += input[next++] << bits;
  22755. bits += 8;
  22756. }
  22757. //===//
  22758. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22759. //--- DROPBITS(5) ---//
  22760. hold >>>= 5;
  22761. bits -= 5;
  22762. //---//
  22763. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22764. //--- DROPBITS(5) ---//
  22765. hold >>>= 5;
  22766. bits -= 5;
  22767. //---//
  22768. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22769. //--- DROPBITS(4) ---//
  22770. hold >>>= 4;
  22771. bits -= 4;
  22772. //---//
  22773. //#ifndef PKZIP_BUG_WORKAROUND
  22774. if (state.nlen > 286 || state.ndist > 30) {
  22775. strm.msg = 'too many length or distance symbols';
  22776. state.mode = BAD;
  22777. break;
  22778. }
  22779. //#endif
  22780. //Tracev((stderr, "inflate: table sizes ok\n"));
  22781. state.have = 0;
  22782. state.mode = LENLENS;
  22783. /* falls through */
  22784. case LENLENS:
  22785. while (state.have < state.ncode) {
  22786. //=== NEEDBITS(3);
  22787. while (bits < 3) {
  22788. if (have === 0) { break inf_leave; }
  22789. have--;
  22790. hold += input[next++] << bits;
  22791. bits += 8;
  22792. }
  22793. //===//
  22794. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22795. //--- DROPBITS(3) ---//
  22796. hold >>>= 3;
  22797. bits -= 3;
  22798. //---//
  22799. }
  22800. while (state.have < 19) {
  22801. state.lens[order[state.have++]] = 0;
  22802. }
  22803. // We have separate tables & no pointers. 2 commented lines below not needed.
  22804. //state.next = state.codes;
  22805. //state.lencode = state.next;
  22806. // Switch to use dynamic table
  22807. state.lencode = state.lendyn;
  22808. state.lenbits = 7;
  22809. opts = {bits: state.lenbits};
  22810. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22811. state.lenbits = opts.bits;
  22812. if (ret) {
  22813. strm.msg = 'invalid code lengths set';
  22814. state.mode = BAD;
  22815. break;
  22816. }
  22817. //Tracev((stderr, "inflate: code lengths ok\n"));
  22818. state.have = 0;
  22819. state.mode = CODELENS;
  22820. /* falls through */
  22821. case CODELENS:
  22822. while (state.have < state.nlen + state.ndist) {
  22823. for (;;) {
  22824. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22825. here_bits = here >>> 24;
  22826. here_op = (here >>> 16) & 0xff;
  22827. here_val = here & 0xffff;
  22828. if ((here_bits) <= bits) { break; }
  22829. //--- PULLBYTE() ---//
  22830. if (have === 0) { break inf_leave; }
  22831. have--;
  22832. hold += input[next++] << bits;
  22833. bits += 8;
  22834. //---//
  22835. }
  22836. if (here_val < 16) {
  22837. //--- DROPBITS(here.bits) ---//
  22838. hold >>>= here_bits;
  22839. bits -= here_bits;
  22840. //---//
  22841. state.lens[state.have++] = here_val;
  22842. }
  22843. else {
  22844. if (here_val === 16) {
  22845. //=== NEEDBITS(here.bits + 2);
  22846. n = here_bits + 2;
  22847. while (bits < n) {
  22848. if (have === 0) { break inf_leave; }
  22849. have--;
  22850. hold += input[next++] << bits;
  22851. bits += 8;
  22852. }
  22853. //===//
  22854. //--- DROPBITS(here.bits) ---//
  22855. hold >>>= here_bits;
  22856. bits -= here_bits;
  22857. //---//
  22858. if (state.have === 0) {
  22859. strm.msg = 'invalid bit length repeat';
  22860. state.mode = BAD;
  22861. break;
  22862. }
  22863. len = state.lens[state.have - 1];
  22864. copy = 3 + (hold & 0x03);//BITS(2);
  22865. //--- DROPBITS(2) ---//
  22866. hold >>>= 2;
  22867. bits -= 2;
  22868. //---//
  22869. }
  22870. else if (here_val === 17) {
  22871. //=== NEEDBITS(here.bits + 3);
  22872. n = here_bits + 3;
  22873. while (bits < n) {
  22874. if (have === 0) { break inf_leave; }
  22875. have--;
  22876. hold += input[next++] << bits;
  22877. bits += 8;
  22878. }
  22879. //===//
  22880. //--- DROPBITS(here.bits) ---//
  22881. hold >>>= here_bits;
  22882. bits -= here_bits;
  22883. //---//
  22884. len = 0;
  22885. copy = 3 + (hold & 0x07);//BITS(3);
  22886. //--- DROPBITS(3) ---//
  22887. hold >>>= 3;
  22888. bits -= 3;
  22889. //---//
  22890. }
  22891. else {
  22892. //=== NEEDBITS(here.bits + 7);
  22893. n = here_bits + 7;
  22894. while (bits < n) {
  22895. if (have === 0) { break inf_leave; }
  22896. have--;
  22897. hold += input[next++] << bits;
  22898. bits += 8;
  22899. }
  22900. //===//
  22901. //--- DROPBITS(here.bits) ---//
  22902. hold >>>= here_bits;
  22903. bits -= here_bits;
  22904. //---//
  22905. len = 0;
  22906. copy = 11 + (hold & 0x7f);//BITS(7);
  22907. //--- DROPBITS(7) ---//
  22908. hold >>>= 7;
  22909. bits -= 7;
  22910. //---//
  22911. }
  22912. if (state.have + copy > state.nlen + state.ndist) {
  22913. strm.msg = 'invalid bit length repeat';
  22914. state.mode = BAD;
  22915. break;
  22916. }
  22917. while (copy--) {
  22918. state.lens[state.have++] = len;
  22919. }
  22920. }
  22921. }
  22922. /* handle error breaks in while */
  22923. if (state.mode === BAD) { break; }
  22924. /* check for end-of-block code (better have one) */
  22925. if (state.lens[256] === 0) {
  22926. strm.msg = 'invalid code -- missing end-of-block';
  22927. state.mode = BAD;
  22928. break;
  22929. }
  22930. /* build code tables -- note: do not change the lenbits or distbits
  22931. values here (9 and 6) without reading the comments in inftrees.h
  22932. concerning the ENOUGH constants, which depend on those values */
  22933. state.lenbits = 9;
  22934. opts = {bits: state.lenbits};
  22935. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  22936. // We have separate tables & no pointers. 2 commented lines below not needed.
  22937. // state.next_index = opts.table_index;
  22938. state.lenbits = opts.bits;
  22939. // state.lencode = state.next;
  22940. if (ret) {
  22941. strm.msg = 'invalid literal/lengths set';
  22942. state.mode = BAD;
  22943. break;
  22944. }
  22945. state.distbits = 6;
  22946. //state.distcode.copy(state.codes);
  22947. // Switch to use dynamic table
  22948. state.distcode = state.distdyn;
  22949. opts = {bits: state.distbits};
  22950. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  22951. // We have separate tables & no pointers. 2 commented lines below not needed.
  22952. // state.next_index = opts.table_index;
  22953. state.distbits = opts.bits;
  22954. // state.distcode = state.next;
  22955. if (ret) {
  22956. strm.msg = 'invalid distances set';
  22957. state.mode = BAD;
  22958. break;
  22959. }
  22960. //Tracev((stderr, 'inflate: codes ok\n'));
  22961. state.mode = LEN_;
  22962. if (flush === Z_TREES) { break inf_leave; }
  22963. /* falls through */
  22964. case LEN_:
  22965. state.mode = LEN;
  22966. /* falls through */
  22967. case LEN:
  22968. if (have >= 6 && left >= 258) {
  22969. //--- RESTORE() ---
  22970. strm.next_out = put;
  22971. strm.avail_out = left;
  22972. strm.next_in = next;
  22973. strm.avail_in = have;
  22974. state.hold = hold;
  22975. state.bits = bits;
  22976. //---
  22977. inflate_fast(strm, _out);
  22978. //--- LOAD() ---
  22979. put = strm.next_out;
  22980. output = strm.output;
  22981. left = strm.avail_out;
  22982. next = strm.next_in;
  22983. input = strm.input;
  22984. have = strm.avail_in;
  22985. hold = state.hold;
  22986. bits = state.bits;
  22987. //---
  22988. if (state.mode === TYPE) {
  22989. state.back = -1;
  22990. }
  22991. break;
  22992. }
  22993. state.back = 0;
  22994. for (;;) {
  22995. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  22996. here_bits = here >>> 24;
  22997. here_op = (here >>> 16) & 0xff;
  22998. here_val = here & 0xffff;
  22999. if (here_bits <= bits) { break; }
  23000. //--- PULLBYTE() ---//
  23001. if (have === 0) { break inf_leave; }
  23002. have--;
  23003. hold += input[next++] << bits;
  23004. bits += 8;
  23005. //---//
  23006. }
  23007. if (here_op && (here_op & 0xf0) === 0) {
  23008. last_bits = here_bits;
  23009. last_op = here_op;
  23010. last_val = here_val;
  23011. for (;;) {
  23012. here = state.lencode[last_val +
  23013. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23014. here_bits = here >>> 24;
  23015. here_op = (here >>> 16) & 0xff;
  23016. here_val = here & 0xffff;
  23017. if ((last_bits + here_bits) <= bits) { break; }
  23018. //--- PULLBYTE() ---//
  23019. if (have === 0) { break inf_leave; }
  23020. have--;
  23021. hold += input[next++] << bits;
  23022. bits += 8;
  23023. //---//
  23024. }
  23025. //--- DROPBITS(last.bits) ---//
  23026. hold >>>= last_bits;
  23027. bits -= last_bits;
  23028. //---//
  23029. state.back += last_bits;
  23030. }
  23031. //--- DROPBITS(here.bits) ---//
  23032. hold >>>= here_bits;
  23033. bits -= here_bits;
  23034. //---//
  23035. state.back += here_bits;
  23036. state.length = here_val;
  23037. if (here_op === 0) {
  23038. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23039. // "inflate: literal '%c'\n" :
  23040. // "inflate: literal 0x%02x\n", here.val));
  23041. state.mode = LIT;
  23042. break;
  23043. }
  23044. if (here_op & 32) {
  23045. //Tracevv((stderr, "inflate: end of block\n"));
  23046. state.back = -1;
  23047. state.mode = TYPE;
  23048. break;
  23049. }
  23050. if (here_op & 64) {
  23051. strm.msg = 'invalid literal/length code';
  23052. state.mode = BAD;
  23053. break;
  23054. }
  23055. state.extra = here_op & 15;
  23056. state.mode = LENEXT;
  23057. /* falls through */
  23058. case LENEXT:
  23059. if (state.extra) {
  23060. //=== NEEDBITS(state.extra);
  23061. n = state.extra;
  23062. while (bits < n) {
  23063. if (have === 0) { break inf_leave; }
  23064. have--;
  23065. hold += input[next++] << bits;
  23066. bits += 8;
  23067. }
  23068. //===//
  23069. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23070. //--- DROPBITS(state.extra) ---//
  23071. hold >>>= state.extra;
  23072. bits -= state.extra;
  23073. //---//
  23074. state.back += state.extra;
  23075. }
  23076. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23077. state.was = state.length;
  23078. state.mode = DIST;
  23079. /* falls through */
  23080. case DIST:
  23081. for (;;) {
  23082. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23083. here_bits = here >>> 24;
  23084. here_op = (here >>> 16) & 0xff;
  23085. here_val = here & 0xffff;
  23086. if ((here_bits) <= bits) { break; }
  23087. //--- PULLBYTE() ---//
  23088. if (have === 0) { break inf_leave; }
  23089. have--;
  23090. hold += input[next++] << bits;
  23091. bits += 8;
  23092. //---//
  23093. }
  23094. if ((here_op & 0xf0) === 0) {
  23095. last_bits = here_bits;
  23096. last_op = here_op;
  23097. last_val = here_val;
  23098. for (;;) {
  23099. here = state.distcode[last_val +
  23100. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23101. here_bits = here >>> 24;
  23102. here_op = (here >>> 16) & 0xff;
  23103. here_val = here & 0xffff;
  23104. if ((last_bits + here_bits) <= bits) { break; }
  23105. //--- PULLBYTE() ---//
  23106. if (have === 0) { break inf_leave; }
  23107. have--;
  23108. hold += input[next++] << bits;
  23109. bits += 8;
  23110. //---//
  23111. }
  23112. //--- DROPBITS(last.bits) ---//
  23113. hold >>>= last_bits;
  23114. bits -= last_bits;
  23115. //---//
  23116. state.back += last_bits;
  23117. }
  23118. //--- DROPBITS(here.bits) ---//
  23119. hold >>>= here_bits;
  23120. bits -= here_bits;
  23121. //---//
  23122. state.back += here_bits;
  23123. if (here_op & 64) {
  23124. strm.msg = 'invalid distance code';
  23125. state.mode = BAD;
  23126. break;
  23127. }
  23128. state.offset = here_val;
  23129. state.extra = (here_op) & 15;
  23130. state.mode = DISTEXT;
  23131. /* falls through */
  23132. case DISTEXT:
  23133. if (state.extra) {
  23134. //=== NEEDBITS(state.extra);
  23135. n = state.extra;
  23136. while (bits < n) {
  23137. if (have === 0) { break inf_leave; }
  23138. have--;
  23139. hold += input[next++] << bits;
  23140. bits += 8;
  23141. }
  23142. //===//
  23143. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23144. //--- DROPBITS(state.extra) ---//
  23145. hold >>>= state.extra;
  23146. bits -= state.extra;
  23147. //---//
  23148. state.back += state.extra;
  23149. }
  23150. //#ifdef INFLATE_STRICT
  23151. if (state.offset > state.dmax) {
  23152. strm.msg = 'invalid distance too far back';
  23153. state.mode = BAD;
  23154. break;
  23155. }
  23156. //#endif
  23157. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23158. state.mode = MATCH;
  23159. /* falls through */
  23160. case MATCH:
  23161. if (left === 0) { break inf_leave; }
  23162. copy = _out - left;
  23163. if (state.offset > copy) { /* copy from window */
  23164. copy = state.offset - copy;
  23165. if (copy > state.whave) {
  23166. if (state.sane) {
  23167. strm.msg = 'invalid distance too far back';
  23168. state.mode = BAD;
  23169. break;
  23170. }
  23171. // (!) This block is disabled in zlib defailts,
  23172. // don't enable it for binary compatibility
  23173. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23174. // Trace((stderr, "inflate.c too far\n"));
  23175. // copy -= state.whave;
  23176. // if (copy > state.length) { copy = state.length; }
  23177. // if (copy > left) { copy = left; }
  23178. // left -= copy;
  23179. // state.length -= copy;
  23180. // do {
  23181. // output[put++] = 0;
  23182. // } while (--copy);
  23183. // if (state.length === 0) { state.mode = LEN; }
  23184. // break;
  23185. //#endif
  23186. }
  23187. if (copy > state.wnext) {
  23188. copy -= state.wnext;
  23189. from = state.wsize - copy;
  23190. }
  23191. else {
  23192. from = state.wnext - copy;
  23193. }
  23194. if (copy > state.length) { copy = state.length; }
  23195. from_source = state.window;
  23196. }
  23197. else { /* copy from output */
  23198. from_source = output;
  23199. from = put - state.offset;
  23200. copy = state.length;
  23201. }
  23202. if (copy > left) { copy = left; }
  23203. left -= copy;
  23204. state.length -= copy;
  23205. do {
  23206. output[put++] = from_source[from++];
  23207. } while (--copy);
  23208. if (state.length === 0) { state.mode = LEN; }
  23209. break;
  23210. case LIT:
  23211. if (left === 0) { break inf_leave; }
  23212. output[put++] = state.length;
  23213. left--;
  23214. state.mode = LEN;
  23215. break;
  23216. case CHECK:
  23217. if (state.wrap) {
  23218. //=== NEEDBITS(32);
  23219. while (bits < 32) {
  23220. if (have === 0) { break inf_leave; }
  23221. have--;
  23222. // Use '|' insdead of '+' to make sure that result is signed
  23223. hold |= input[next++] << bits;
  23224. bits += 8;
  23225. }
  23226. //===//
  23227. _out -= left;
  23228. strm.total_out += _out;
  23229. state.total += _out;
  23230. if (_out) {
  23231. strm.adler = state.check =
  23232. /*UPDATE(state.check, put - _out, _out);*/
  23233. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23234. }
  23235. _out = left;
  23236. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23237. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23238. strm.msg = 'incorrect data check';
  23239. state.mode = BAD;
  23240. break;
  23241. }
  23242. //=== INITBITS();
  23243. hold = 0;
  23244. bits = 0;
  23245. //===//
  23246. //Tracev((stderr, "inflate: check matches trailer\n"));
  23247. }
  23248. state.mode = LENGTH;
  23249. /* falls through */
  23250. case LENGTH:
  23251. if (state.wrap && state.flags) {
  23252. //=== NEEDBITS(32);
  23253. while (bits < 32) {
  23254. if (have === 0) { break inf_leave; }
  23255. have--;
  23256. hold += input[next++] << bits;
  23257. bits += 8;
  23258. }
  23259. //===//
  23260. if (hold !== (state.total & 0xffffffff)) {
  23261. strm.msg = 'incorrect length check';
  23262. state.mode = BAD;
  23263. break;
  23264. }
  23265. //=== INITBITS();
  23266. hold = 0;
  23267. bits = 0;
  23268. //===//
  23269. //Tracev((stderr, "inflate: length matches trailer\n"));
  23270. }
  23271. state.mode = DONE;
  23272. /* falls through */
  23273. case DONE:
  23274. ret = Z_STREAM_END;
  23275. break inf_leave;
  23276. case BAD:
  23277. ret = Z_DATA_ERROR;
  23278. break inf_leave;
  23279. case MEM:
  23280. return Z_MEM_ERROR;
  23281. case SYNC:
  23282. /* falls through */
  23283. default:
  23284. return Z_STREAM_ERROR;
  23285. }
  23286. }
  23287. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23288. /*
  23289. Return from inflate(), updating the total counts and the check value.
  23290. If there was no progress during the inflate() call, return a buffer
  23291. error. Call updatewindow() to create and/or update the window state.
  23292. Note: a memory error from inflate() is non-recoverable.
  23293. */
  23294. //--- RESTORE() ---
  23295. strm.next_out = put;
  23296. strm.avail_out = left;
  23297. strm.next_in = next;
  23298. strm.avail_in = have;
  23299. state.hold = hold;
  23300. state.bits = bits;
  23301. //---
  23302. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23303. (state.mode < CHECK || flush !== Z_FINISH))) {
  23304. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23305. state.mode = MEM;
  23306. return Z_MEM_ERROR;
  23307. }
  23308. }
  23309. _in -= strm.avail_in;
  23310. _out -= strm.avail_out;
  23311. strm.total_in += _in;
  23312. strm.total_out += _out;
  23313. state.total += _out;
  23314. if (state.wrap && _out) {
  23315. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23316. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23317. }
  23318. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23319. (state.mode === TYPE ? 128 : 0) +
  23320. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23321. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23322. ret = Z_BUF_ERROR;
  23323. }
  23324. return ret;
  23325. }
  23326. function inflateEnd(strm) {
  23327. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23328. return Z_STREAM_ERROR;
  23329. }
  23330. var state = strm.state;
  23331. if (state.window) {
  23332. state.window = null;
  23333. }
  23334. strm.state = null;
  23335. return Z_OK;
  23336. }
  23337. function inflateGetHeader(strm, head) {
  23338. var state;
  23339. /* check state */
  23340. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23341. state = strm.state;
  23342. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23343. /* save header structure */
  23344. state.head = head;
  23345. head.done = false;
  23346. return Z_OK;
  23347. }
  23348. exports.inflateReset = inflateReset;
  23349. exports.inflateReset2 = inflateReset2;
  23350. exports.inflateResetKeep = inflateResetKeep;
  23351. exports.inflateInit = inflateInit;
  23352. exports.inflateInit2 = inflateInit2;
  23353. exports.inflate = inflate;
  23354. exports.inflateEnd = inflateEnd;
  23355. exports.inflateGetHeader = inflateGetHeader;
  23356. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23357. /* Not implemented
  23358. exports.inflateCopy = inflateCopy;
  23359. exports.inflateGetDictionary = inflateGetDictionary;
  23360. exports.inflateMark = inflateMark;
  23361. exports.inflatePrime = inflatePrime;
  23362. exports.inflateSetDictionary = inflateSetDictionary;
  23363. exports.inflateSync = inflateSync;
  23364. exports.inflateSyncPoint = inflateSyncPoint;
  23365. exports.inflateUndermine = inflateUndermine;
  23366. */
  23367. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./inffast":79,"./inftrees":81}],81:[function(require,module,exports){
  23368. 'use strict';
  23369. var utils = require('../utils/common');
  23370. var MAXBITS = 15;
  23371. var ENOUGH_LENS = 852;
  23372. var ENOUGH_DISTS = 592;
  23373. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23374. var CODES = 0;
  23375. var LENS = 1;
  23376. var DISTS = 2;
  23377. var lbase = [ /* Length codes 257..285 base */
  23378. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23379. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23380. ];
  23381. var lext = [ /* Length codes 257..285 extra */
  23382. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23383. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23384. ];
  23385. var dbase = [ /* Distance codes 0..29 base */
  23386. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23387. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23388. 8193, 12289, 16385, 24577, 0, 0
  23389. ];
  23390. var dext = [ /* Distance codes 0..29 extra */
  23391. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23392. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23393. 28, 28, 29, 29, 64, 64
  23394. ];
  23395. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23396. {
  23397. var bits = opts.bits;
  23398. //here = opts.here; /* table entry for duplication */
  23399. var len = 0; /* a code's length in bits */
  23400. var sym = 0; /* index of code symbols */
  23401. var min = 0, max = 0; /* minimum and maximum code lengths */
  23402. var root = 0; /* number of index bits for root table */
  23403. var curr = 0; /* number of index bits for current table */
  23404. var drop = 0; /* code bits to drop for sub-table */
  23405. var left = 0; /* number of prefix codes available */
  23406. var used = 0; /* code entries in table used */
  23407. var huff = 0; /* Huffman code */
  23408. var incr; /* for incrementing code, index */
  23409. var fill; /* index for replicating entries */
  23410. var low; /* low bits for current root entry */
  23411. var mask; /* mask for low root bits */
  23412. var next; /* next available space in table */
  23413. var base = null; /* base value table to use */
  23414. var base_index = 0;
  23415. // var shoextra; /* extra bits table to use */
  23416. var end; /* use base and extra for symbol > end */
  23417. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23418. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23419. var extra = null;
  23420. var extra_index = 0;
  23421. var here_bits, here_op, here_val;
  23422. /*
  23423. Process a set of code lengths to create a canonical Huffman code. The
  23424. code lengths are lens[0..codes-1]. Each length corresponds to the
  23425. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23426. symbols by length from short to long, and retaining the symbol order
  23427. for codes with equal lengths. Then the code starts with all zero bits
  23428. for the first code of the shortest length, and the codes are integer
  23429. increments for the same length, and zeros are appended as the length
  23430. increases. For the deflate format, these bits are stored backwards
  23431. from their more natural integer increment ordering, and so when the
  23432. decoding tables are built in the large loop below, the integer codes
  23433. are incremented backwards.
  23434. This routine assumes, but does not check, that all of the entries in
  23435. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23436. 1..MAXBITS is interpreted as that code length. zero means that that
  23437. symbol does not occur in this code.
  23438. The codes are sorted by computing a count of codes for each length,
  23439. creating from that a table of starting indices for each length in the
  23440. sorted table, and then entering the symbols in order in the sorted
  23441. table. The sorted table is work[], with that space being provided by
  23442. the caller.
  23443. The length counts are used for other purposes as well, i.e. finding
  23444. the minimum and maximum length codes, determining if there are any
  23445. codes at all, checking for a valid set of lengths, and looking ahead
  23446. at length counts to determine sub-table sizes when building the
  23447. decoding tables.
  23448. */
  23449. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23450. for (len = 0; len <= MAXBITS; len++) {
  23451. count[len] = 0;
  23452. }
  23453. for (sym = 0; sym < codes; sym++) {
  23454. count[lens[lens_index + sym]]++;
  23455. }
  23456. /* bound code lengths, force root to be within code lengths */
  23457. root = bits;
  23458. for (max = MAXBITS; max >= 1; max--) {
  23459. if (count[max] !== 0) { break; }
  23460. }
  23461. if (root > max) {
  23462. root = max;
  23463. }
  23464. if (max === 0) { /* no symbols to code at all */
  23465. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23466. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23467. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23468. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23469. //table.op[opts.table_index] = 64;
  23470. //table.bits[opts.table_index] = 1;
  23471. //table.val[opts.table_index++] = 0;
  23472. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23473. opts.bits = 1;
  23474. return 0; /* no symbols, but wait for decoding to report error */
  23475. }
  23476. for (min = 1; min < max; min++) {
  23477. if (count[min] !== 0) { break; }
  23478. }
  23479. if (root < min) {
  23480. root = min;
  23481. }
  23482. /* check for an over-subscribed or incomplete set of lengths */
  23483. left = 1;
  23484. for (len = 1; len <= MAXBITS; len++) {
  23485. left <<= 1;
  23486. left -= count[len];
  23487. if (left < 0) {
  23488. return -1;
  23489. } /* over-subscribed */
  23490. }
  23491. if (left > 0 && (type === CODES || max !== 1)) {
  23492. return -1; /* incomplete set */
  23493. }
  23494. /* generate offsets into symbol table for each length for sorting */
  23495. offs[1] = 0;
  23496. for (len = 1; len < MAXBITS; len++) {
  23497. offs[len + 1] = offs[len] + count[len];
  23498. }
  23499. /* sort symbols by length, by symbol order within each length */
  23500. for (sym = 0; sym < codes; sym++) {
  23501. if (lens[lens_index + sym] !== 0) {
  23502. work[offs[lens[lens_index + sym]]++] = sym;
  23503. }
  23504. }
  23505. /*
  23506. Create and fill in decoding tables. In this loop, the table being
  23507. filled is at next and has curr index bits. The code being used is huff
  23508. with length len. That code is converted to an index by dropping drop
  23509. bits off of the bottom. For codes where len is less than drop + curr,
  23510. those top drop + curr - len bits are incremented through all values to
  23511. fill the table with replicated entries.
  23512. root is the number of index bits for the root table. When len exceeds
  23513. root, sub-tables are created pointed to by the root entry with an index
  23514. of the low root bits of huff. This is saved in low to check for when a
  23515. new sub-table should be started. drop is zero when the root table is
  23516. being filled, and drop is root when sub-tables are being filled.
  23517. When a new sub-table is needed, it is necessary to look ahead in the
  23518. code lengths to determine what size sub-table is needed. The length
  23519. counts are used for this, and so count[] is decremented as codes are
  23520. entered in the tables.
  23521. used keeps track of how many table entries have been allocated from the
  23522. provided *table space. It is checked for LENS and DIST tables against
  23523. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23524. the initial root table size constants. See the comments in inftrees.h
  23525. for more information.
  23526. sym increments through all symbols, and the loop terminates when
  23527. all codes of length max, i.e. all codes, have been processed. This
  23528. routine permits incomplete codes, so another loop after this one fills
  23529. in the rest of the decoding tables with invalid code markers.
  23530. */
  23531. /* set up for code type */
  23532. // poor man optimization - use if-else instead of switch,
  23533. // to avoid deopts in old v8
  23534. if (type === CODES) {
  23535. base = extra = work; /* dummy value--not used */
  23536. end = 19;
  23537. } else if (type === LENS) {
  23538. base = lbase;
  23539. base_index -= 257;
  23540. extra = lext;
  23541. extra_index -= 257;
  23542. end = 256;
  23543. } else { /* DISTS */
  23544. base = dbase;
  23545. extra = dext;
  23546. end = -1;
  23547. }
  23548. /* initialize opts for loop */
  23549. huff = 0; /* starting code */
  23550. sym = 0; /* starting code symbol */
  23551. len = min; /* starting code length */
  23552. next = table_index; /* current table to fill in */
  23553. curr = root; /* current table index bits */
  23554. drop = 0; /* current bits to drop from code for index */
  23555. low = -1; /* trigger new sub-table when len > root */
  23556. used = 1 << root; /* use root table entries */
  23557. mask = used - 1; /* mask for comparing low */
  23558. /* check available table space */
  23559. if ((type === LENS && used > ENOUGH_LENS) ||
  23560. (type === DISTS && used > ENOUGH_DISTS)) {
  23561. return 1;
  23562. }
  23563. var i=0;
  23564. /* process all codes and make table entries */
  23565. for (;;) {
  23566. i++;
  23567. /* create table entry */
  23568. here_bits = len - drop;
  23569. if (work[sym] < end) {
  23570. here_op = 0;
  23571. here_val = work[sym];
  23572. }
  23573. else if (work[sym] > end) {
  23574. here_op = extra[extra_index + work[sym]];
  23575. here_val = base[base_index + work[sym]];
  23576. }
  23577. else {
  23578. here_op = 32 + 64; /* end of block */
  23579. here_val = 0;
  23580. }
  23581. /* replicate for those indices with low len bits equal to huff */
  23582. incr = 1 << (len - drop);
  23583. fill = 1 << curr;
  23584. min = fill; /* save offset to next table */
  23585. do {
  23586. fill -= incr;
  23587. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23588. } while (fill !== 0);
  23589. /* backwards increment the len-bit code huff */
  23590. incr = 1 << (len - 1);
  23591. while (huff & incr) {
  23592. incr >>= 1;
  23593. }
  23594. if (incr !== 0) {
  23595. huff &= incr - 1;
  23596. huff += incr;
  23597. } else {
  23598. huff = 0;
  23599. }
  23600. /* go to next symbol, update count, len */
  23601. sym++;
  23602. if (--count[len] === 0) {
  23603. if (len === max) { break; }
  23604. len = lens[lens_index + work[sym]];
  23605. }
  23606. /* create new sub-table if needed */
  23607. if (len > root && (huff & mask) !== low) {
  23608. /* if first time, transition to sub-tables */
  23609. if (drop === 0) {
  23610. drop = root;
  23611. }
  23612. /* increment past last table */
  23613. next += min; /* here min is 1 << curr */
  23614. /* determine length of next table */
  23615. curr = len - drop;
  23616. left = 1 << curr;
  23617. while (curr + drop < max) {
  23618. left -= count[curr + drop];
  23619. if (left <= 0) { break; }
  23620. curr++;
  23621. left <<= 1;
  23622. }
  23623. /* check for enough space */
  23624. used += 1 << curr;
  23625. if ((type === LENS && used > ENOUGH_LENS) ||
  23626. (type === DISTS && used > ENOUGH_DISTS)) {
  23627. return 1;
  23628. }
  23629. /* point entry in root table to sub-table */
  23630. low = huff & mask;
  23631. /*table.op[low] = curr;
  23632. table.bits[low] = root;
  23633. table.val[low] = next - opts.table_index;*/
  23634. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23635. }
  23636. }
  23637. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23638. at most one remaining entry, since if the code is incomplete, the
  23639. maximum code length that was allowed to get this far is one bit) */
  23640. if (huff !== 0) {
  23641. //table.op[next + huff] = 64; /* invalid code marker */
  23642. //table.bits[next + huff] = len - drop;
  23643. //table.val[next + huff] = 0;
  23644. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23645. }
  23646. /* set return parameters */
  23647. //opts.table_index += used;
  23648. opts.bits = root;
  23649. return 0;
  23650. };
  23651. },{"../utils/common":72}],82:[function(require,module,exports){
  23652. 'use strict';
  23653. module.exports = {
  23654. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23655. '1': 'stream end', /* Z_STREAM_END 1 */
  23656. '0': '', /* Z_OK 0 */
  23657. '-1': 'file error', /* Z_ERRNO (-1) */
  23658. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23659. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23660. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23661. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23662. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23663. };
  23664. },{}],83:[function(require,module,exports){
  23665. 'use strict';
  23666. var utils = require('../utils/common');
  23667. /* Public constants ==========================================================*/
  23668. /* ===========================================================================*/
  23669. //var Z_FILTERED = 1;
  23670. //var Z_HUFFMAN_ONLY = 2;
  23671. //var Z_RLE = 3;
  23672. var Z_FIXED = 4;
  23673. //var Z_DEFAULT_STRATEGY = 0;
  23674. /* Possible values of the data_type field (though see inflate()) */
  23675. var Z_BINARY = 0;
  23676. var Z_TEXT = 1;
  23677. //var Z_ASCII = 1; // = Z_TEXT
  23678. var Z_UNKNOWN = 2;
  23679. /*============================================================================*/
  23680. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23681. // From zutil.h
  23682. var STORED_BLOCK = 0;
  23683. var STATIC_TREES = 1;
  23684. var DYN_TREES = 2;
  23685. /* The three kinds of block type */
  23686. var MIN_MATCH = 3;
  23687. var MAX_MATCH = 258;
  23688. /* The minimum and maximum match lengths */
  23689. // From deflate.h
  23690. /* ===========================================================================
  23691. * Internal compression state.
  23692. */
  23693. var LENGTH_CODES = 29;
  23694. /* number of length codes, not counting the special END_BLOCK code */
  23695. var LITERALS = 256;
  23696. /* number of literal bytes 0..255 */
  23697. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23698. /* number of Literal or Length codes, including the END_BLOCK code */
  23699. var D_CODES = 30;
  23700. /* number of distance codes */
  23701. var BL_CODES = 19;
  23702. /* number of codes used to transfer the bit lengths */
  23703. var HEAP_SIZE = 2*L_CODES + 1;
  23704. /* maximum heap size */
  23705. var MAX_BITS = 15;
  23706. /* All codes must not exceed MAX_BITS bits */
  23707. var Buf_size = 16;
  23708. /* size of bit buffer in bi_buf */
  23709. /* ===========================================================================
  23710. * Constants
  23711. */
  23712. var MAX_BL_BITS = 7;
  23713. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23714. var END_BLOCK = 256;
  23715. /* end of block literal code */
  23716. var REP_3_6 = 16;
  23717. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23718. var REPZ_3_10 = 17;
  23719. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23720. var REPZ_11_138 = 18;
  23721. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23722. var extra_lbits = /* extra bits for each length code */
  23723. [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];
  23724. var extra_dbits = /* extra bits for each distance code */
  23725. [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];
  23726. var extra_blbits = /* extra bits for each bit length code */
  23727. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23728. var bl_order =
  23729. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23730. /* The lengths of the bit length codes are sent in order of decreasing
  23731. * probability, to avoid transmitting the lengths for unused bit length codes.
  23732. */
  23733. /* ===========================================================================
  23734. * Local data. These are initialized only once.
  23735. */
  23736. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23737. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23738. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23739. var static_ltree = new Array((L_CODES+2) * 2);
  23740. zero(static_ltree);
  23741. /* The static literal tree. Since the bit lengths are imposed, there is no
  23742. * need for the L_CODES extra codes used during heap construction. However
  23743. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23744. * below).
  23745. */
  23746. var static_dtree = new Array(D_CODES * 2);
  23747. zero(static_dtree);
  23748. /* The static distance tree. (Actually a trivial tree since all codes use
  23749. * 5 bits.)
  23750. */
  23751. var _dist_code = new Array(DIST_CODE_LEN);
  23752. zero(_dist_code);
  23753. /* Distance codes. The first 256 values correspond to the distances
  23754. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23755. * the 15 bit distances.
  23756. */
  23757. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23758. zero(_length_code);
  23759. /* length code for each normalized match length (0 == MIN_MATCH) */
  23760. var base_length = new Array(LENGTH_CODES);
  23761. zero(base_length);
  23762. /* First normalized length for each code (0 = MIN_MATCH) */
  23763. var base_dist = new Array(D_CODES);
  23764. zero(base_dist);
  23765. /* First normalized distance for each code (0 = distance of 1) */
  23766. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23767. this.static_tree = static_tree; /* static tree or NULL */
  23768. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23769. this.extra_base = extra_base; /* base index for extra_bits */
  23770. this.elems = elems; /* max number of elements in the tree */
  23771. this.max_length = max_length; /* max bit length for the codes */
  23772. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23773. this.has_stree = static_tree && static_tree.length;
  23774. };
  23775. var static_l_desc;
  23776. var static_d_desc;
  23777. var static_bl_desc;
  23778. var TreeDesc = function(dyn_tree, stat_desc) {
  23779. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23780. this.max_code = 0; /* largest code with non zero frequency */
  23781. this.stat_desc = stat_desc; /* the corresponding static tree */
  23782. };
  23783. function d_code(dist) {
  23784. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23785. }
  23786. /* ===========================================================================
  23787. * Output a short LSB first on the stream.
  23788. * IN assertion: there is enough room in pendingBuf.
  23789. */
  23790. function put_short (s, w) {
  23791. // put_byte(s, (uch)((w) & 0xff));
  23792. // put_byte(s, (uch)((ush)(w) >> 8));
  23793. s.pending_buf[s.pending++] = (w) & 0xff;
  23794. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23795. }
  23796. /* ===========================================================================
  23797. * Send a value on a given number of bits.
  23798. * IN assertion: length <= 16 and value fits in length bits.
  23799. */
  23800. function send_bits(s, value, length) {
  23801. if (s.bi_valid > (Buf_size - length)) {
  23802. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23803. put_short(s, s.bi_buf);
  23804. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23805. s.bi_valid += length - Buf_size;
  23806. } else {
  23807. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23808. s.bi_valid += length;
  23809. }
  23810. }
  23811. function send_code(s, c, tree) {
  23812. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23813. }
  23814. /* ===========================================================================
  23815. * Reverse the first len bits of a code, using straightforward code (a faster
  23816. * method would use a table)
  23817. * IN assertion: 1 <= len <= 15
  23818. */
  23819. function bi_reverse(code, len) {
  23820. var res = 0;
  23821. do {
  23822. res |= code & 1;
  23823. code >>>= 1;
  23824. res <<= 1;
  23825. } while (--len > 0);
  23826. return res >>> 1;
  23827. }
  23828. /* ===========================================================================
  23829. * Flush the bit buffer, keeping at most 7 bits in it.
  23830. */
  23831. function bi_flush(s) {
  23832. if (s.bi_valid === 16) {
  23833. put_short(s, s.bi_buf);
  23834. s.bi_buf = 0;
  23835. s.bi_valid = 0;
  23836. } else if (s.bi_valid >= 8) {
  23837. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23838. s.bi_buf >>= 8;
  23839. s.bi_valid -= 8;
  23840. }
  23841. }
  23842. /* ===========================================================================
  23843. * Compute the optimal bit lengths for a tree and update the total bit length
  23844. * for the current block.
  23845. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23846. * above are the tree nodes sorted by increasing frequency.
  23847. * OUT assertions: the field len is set to the optimal bit length, the
  23848. * array bl_count contains the frequencies for each bit length.
  23849. * The length opt_len is updated; static_len is also updated if stree is
  23850. * not null.
  23851. */
  23852. function gen_bitlen(s, desc)
  23853. // deflate_state *s;
  23854. // tree_desc *desc; /* the tree descriptor */
  23855. {
  23856. var tree = desc.dyn_tree;
  23857. var max_code = desc.max_code;
  23858. var stree = desc.stat_desc.static_tree;
  23859. var has_stree = desc.stat_desc.has_stree;
  23860. var extra = desc.stat_desc.extra_bits;
  23861. var base = desc.stat_desc.extra_base;
  23862. var max_length = desc.stat_desc.max_length;
  23863. var h; /* heap index */
  23864. var n, m; /* iterate over the tree elements */
  23865. var bits; /* bit length */
  23866. var xbits; /* extra bits */
  23867. var f; /* frequency */
  23868. var overflow = 0; /* number of elements with bit length too large */
  23869. for (bits = 0; bits <= MAX_BITS; bits++) {
  23870. s.bl_count[bits] = 0;
  23871. }
  23872. /* In a first pass, compute the optimal bit lengths (which may
  23873. * overflow in the case of the bit length tree).
  23874. */
  23875. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  23876. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  23877. n = s.heap[h];
  23878. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  23879. if (bits > max_length) {
  23880. bits = max_length;
  23881. overflow++;
  23882. }
  23883. tree[n*2 + 1]/*.Len*/ = bits;
  23884. /* We overwrite tree[n].Dad which is no longer needed */
  23885. if (n > max_code) { continue; } /* not a leaf node */
  23886. s.bl_count[bits]++;
  23887. xbits = 0;
  23888. if (n >= base) {
  23889. xbits = extra[n-base];
  23890. }
  23891. f = tree[n * 2]/*.Freq*/;
  23892. s.opt_len += f * (bits + xbits);
  23893. if (has_stree) {
  23894. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  23895. }
  23896. }
  23897. if (overflow === 0) { return; }
  23898. // Trace((stderr,"\nbit length overflow\n"));
  23899. /* This happens for example on obj2 and pic of the Calgary corpus */
  23900. /* Find the first bit length which could increase: */
  23901. do {
  23902. bits = max_length-1;
  23903. while (s.bl_count[bits] === 0) { bits--; }
  23904. s.bl_count[bits]--; /* move one leaf down the tree */
  23905. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  23906. s.bl_count[max_length]--;
  23907. /* The brother of the overflow item also moves one step up,
  23908. * but this does not affect bl_count[max_length]
  23909. */
  23910. overflow -= 2;
  23911. } while (overflow > 0);
  23912. /* Now recompute all bit lengths, scanning in increasing frequency.
  23913. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  23914. * lengths instead of fixing only the wrong ones. This idea is taken
  23915. * from 'ar' written by Haruhiko Okumura.)
  23916. */
  23917. for (bits = max_length; bits !== 0; bits--) {
  23918. n = s.bl_count[bits];
  23919. while (n !== 0) {
  23920. m = s.heap[--h];
  23921. if (m > max_code) { continue; }
  23922. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  23923. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  23924. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  23925. tree[m*2 + 1]/*.Len*/ = bits;
  23926. }
  23927. n--;
  23928. }
  23929. }
  23930. }
  23931. /* ===========================================================================
  23932. * Generate the codes for a given tree and bit counts (which need not be
  23933. * optimal).
  23934. * IN assertion: the array bl_count contains the bit length statistics for
  23935. * the given tree and the field len is set for all tree elements.
  23936. * OUT assertion: the field code is set for all tree elements of non
  23937. * zero code length.
  23938. */
  23939. function gen_codes(tree, max_code, bl_count)
  23940. // ct_data *tree; /* the tree to decorate */
  23941. // int max_code; /* largest code with non zero frequency */
  23942. // ushf *bl_count; /* number of codes at each bit length */
  23943. {
  23944. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  23945. var code = 0; /* running code value */
  23946. var bits; /* bit index */
  23947. var n; /* code index */
  23948. /* The distribution counts are first used to generate the code values
  23949. * without bit reversal.
  23950. */
  23951. for (bits = 1; bits <= MAX_BITS; bits++) {
  23952. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  23953. }
  23954. /* Check that the bit counts in bl_count are consistent. The last code
  23955. * must be all ones.
  23956. */
  23957. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  23958. // "inconsistent bit counts");
  23959. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  23960. for (n = 0; n <= max_code; n++) {
  23961. var len = tree[n*2 + 1]/*.Len*/;
  23962. if (len === 0) { continue; }
  23963. /* Now reverse the bits */
  23964. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  23965. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  23966. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  23967. }
  23968. }
  23969. /* ===========================================================================
  23970. * Initialize the various 'constant' tables.
  23971. */
  23972. function tr_static_init() {
  23973. var n; /* iterates over tree elements */
  23974. var bits; /* bit counter */
  23975. var length; /* length value */
  23976. var code; /* code value */
  23977. var dist; /* distance index */
  23978. var bl_count = new Array(MAX_BITS+1);
  23979. /* number of codes at each bit length for an optimal tree */
  23980. // do check in _tr_init()
  23981. //if (static_init_done) return;
  23982. /* For some embedded targets, global variables are not initialized: */
  23983. /*#ifdef NO_INIT_GLOBAL_POINTERS
  23984. static_l_desc.static_tree = static_ltree;
  23985. static_l_desc.extra_bits = extra_lbits;
  23986. static_d_desc.static_tree = static_dtree;
  23987. static_d_desc.extra_bits = extra_dbits;
  23988. static_bl_desc.extra_bits = extra_blbits;
  23989. #endif*/
  23990. /* Initialize the mapping length (0..255) -> length code (0..28) */
  23991. length = 0;
  23992. for (code = 0; code < LENGTH_CODES-1; code++) {
  23993. base_length[code] = length;
  23994. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  23995. _length_code[length++] = code;
  23996. }
  23997. }
  23998. //Assert (length == 256, "tr_static_init: length != 256");
  23999. /* Note that the length 255 (match length 258) can be represented
  24000. * in two different ways: code 284 + 5 bits or code 285, so we
  24001. * overwrite length_code[255] to use the best encoding:
  24002. */
  24003. _length_code[length-1] = code;
  24004. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24005. dist = 0;
  24006. for (code = 0 ; code < 16; code++) {
  24007. base_dist[code] = dist;
  24008. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24009. _dist_code[dist++] = code;
  24010. }
  24011. }
  24012. //Assert (dist == 256, "tr_static_init: dist != 256");
  24013. dist >>= 7; /* from now on, all distances are divided by 128 */
  24014. for (; code < D_CODES; code++) {
  24015. base_dist[code] = dist << 7;
  24016. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24017. _dist_code[256 + dist++] = code;
  24018. }
  24019. }
  24020. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24021. /* Construct the codes of the static literal tree */
  24022. for (bits = 0; bits <= MAX_BITS; bits++) {
  24023. bl_count[bits] = 0;
  24024. }
  24025. n = 0;
  24026. while (n <= 143) {
  24027. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24028. n++;
  24029. bl_count[8]++;
  24030. }
  24031. while (n <= 255) {
  24032. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24033. n++;
  24034. bl_count[9]++;
  24035. }
  24036. while (n <= 279) {
  24037. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24038. n++;
  24039. bl_count[7]++;
  24040. }
  24041. while (n <= 287) {
  24042. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24043. n++;
  24044. bl_count[8]++;
  24045. }
  24046. /* Codes 286 and 287 do not exist, but we must include them in the
  24047. * tree construction to get a canonical Huffman tree (longest code
  24048. * all ones)
  24049. */
  24050. gen_codes(static_ltree, L_CODES+1, bl_count);
  24051. /* The static distance tree is trivial: */
  24052. for (n = 0; n < D_CODES; n++) {
  24053. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24054. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24055. }
  24056. // Now data ready and we can init static trees
  24057. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24058. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24059. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24060. //static_init_done = true;
  24061. }
  24062. /* ===========================================================================
  24063. * Initialize a new block.
  24064. */
  24065. function init_block(s) {
  24066. var n; /* iterates over tree elements */
  24067. /* Initialize the trees. */
  24068. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24069. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24070. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24071. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24072. s.opt_len = s.static_len = 0;
  24073. s.last_lit = s.matches = 0;
  24074. }
  24075. /* ===========================================================================
  24076. * Flush the bit buffer and align the output on a byte boundary
  24077. */
  24078. function bi_windup(s)
  24079. {
  24080. if (s.bi_valid > 8) {
  24081. put_short(s, s.bi_buf);
  24082. } else if (s.bi_valid > 0) {
  24083. //put_byte(s, (Byte)s->bi_buf);
  24084. s.pending_buf[s.pending++] = s.bi_buf;
  24085. }
  24086. s.bi_buf = 0;
  24087. s.bi_valid = 0;
  24088. }
  24089. /* ===========================================================================
  24090. * Copy a stored block, storing first the length and its
  24091. * one's complement if requested.
  24092. */
  24093. function copy_block(s, buf, len, header)
  24094. //DeflateState *s;
  24095. //charf *buf; /* the input data */
  24096. //unsigned len; /* its length */
  24097. //int header; /* true if block header must be written */
  24098. {
  24099. bi_windup(s); /* align on byte boundary */
  24100. if (header) {
  24101. put_short(s, len);
  24102. put_short(s, ~len);
  24103. }
  24104. // while (len--) {
  24105. // put_byte(s, *buf++);
  24106. // }
  24107. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24108. s.pending += len;
  24109. }
  24110. /* ===========================================================================
  24111. * Compares to subtrees, using the tree depth as tie breaker when
  24112. * the subtrees have equal frequency. This minimizes the worst case length.
  24113. */
  24114. function smaller(tree, n, m, depth) {
  24115. var _n2 = n*2;
  24116. var _m2 = m*2;
  24117. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24118. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24119. }
  24120. /* ===========================================================================
  24121. * Restore the heap property by moving down the tree starting at node k,
  24122. * exchanging a node with the smallest of its two sons if necessary, stopping
  24123. * when the heap property is re-established (each father smaller than its
  24124. * two sons).
  24125. */
  24126. function pqdownheap(s, tree, k)
  24127. // deflate_state *s;
  24128. // ct_data *tree; /* the tree to restore */
  24129. // int k; /* node to move down */
  24130. {
  24131. var v = s.heap[k];
  24132. var j = k << 1; /* left son of k */
  24133. while (j <= s.heap_len) {
  24134. /* Set j to the smallest of the two sons: */
  24135. if (j < s.heap_len &&
  24136. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24137. j++;
  24138. }
  24139. /* Exit if v is smaller than both sons */
  24140. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24141. /* Exchange v with the smallest son */
  24142. s.heap[k] = s.heap[j];
  24143. k = j;
  24144. /* And continue down the tree, setting j to the left son of k */
  24145. j <<= 1;
  24146. }
  24147. s.heap[k] = v;
  24148. }
  24149. // inlined manually
  24150. // var SMALLEST = 1;
  24151. /* ===========================================================================
  24152. * Send the block data compressed using the given Huffman trees
  24153. */
  24154. function compress_block(s, ltree, dtree)
  24155. // deflate_state *s;
  24156. // const ct_data *ltree; /* literal tree */
  24157. // const ct_data *dtree; /* distance tree */
  24158. {
  24159. var dist; /* distance of matched string */
  24160. var lc; /* match length or unmatched char (if dist == 0) */
  24161. var lx = 0; /* running index in l_buf */
  24162. var code; /* the code to send */
  24163. var extra; /* number of extra bits to send */
  24164. if (s.last_lit !== 0) {
  24165. do {
  24166. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24167. lc = s.pending_buf[s.l_buf + lx];
  24168. lx++;
  24169. if (dist === 0) {
  24170. send_code(s, lc, ltree); /* send a literal byte */
  24171. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24172. } else {
  24173. /* Here, lc is the match length - MIN_MATCH */
  24174. code = _length_code[lc];
  24175. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24176. extra = extra_lbits[code];
  24177. if (extra !== 0) {
  24178. lc -= base_length[code];
  24179. send_bits(s, lc, extra); /* send the extra length bits */
  24180. }
  24181. dist--; /* dist is now the match distance - 1 */
  24182. code = d_code(dist);
  24183. //Assert (code < D_CODES, "bad d_code");
  24184. send_code(s, code, dtree); /* send the distance code */
  24185. extra = extra_dbits[code];
  24186. if (extra !== 0) {
  24187. dist -= base_dist[code];
  24188. send_bits(s, dist, extra); /* send the extra distance bits */
  24189. }
  24190. } /* literal or match pair ? */
  24191. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24192. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24193. // "pendingBuf overflow");
  24194. } while (lx < s.last_lit);
  24195. }
  24196. send_code(s, END_BLOCK, ltree);
  24197. }
  24198. /* ===========================================================================
  24199. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24200. * Update the total bit length for the current block.
  24201. * IN assertion: the field freq is set for all tree elements.
  24202. * OUT assertions: the fields len and code are set to the optimal bit length
  24203. * and corresponding code. The length opt_len is updated; static_len is
  24204. * also updated if stree is not null. The field max_code is set.
  24205. */
  24206. function build_tree(s, desc)
  24207. // deflate_state *s;
  24208. // tree_desc *desc; /* the tree descriptor */
  24209. {
  24210. var tree = desc.dyn_tree;
  24211. var stree = desc.stat_desc.static_tree;
  24212. var has_stree = desc.stat_desc.has_stree;
  24213. var elems = desc.stat_desc.elems;
  24214. var n, m; /* iterate over heap elements */
  24215. var max_code = -1; /* largest code with non zero frequency */
  24216. var node; /* new node being created */
  24217. /* Construct the initial heap, with least frequent element in
  24218. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24219. * heap[0] is not used.
  24220. */
  24221. s.heap_len = 0;
  24222. s.heap_max = HEAP_SIZE;
  24223. for (n = 0; n < elems; n++) {
  24224. if (tree[n * 2]/*.Freq*/ !== 0) {
  24225. s.heap[++s.heap_len] = max_code = n;
  24226. s.depth[n] = 0;
  24227. } else {
  24228. tree[n*2 + 1]/*.Len*/ = 0;
  24229. }
  24230. }
  24231. /* The pkzip format requires that at least one distance code exists,
  24232. * and that at least one bit should be sent even if there is only one
  24233. * possible code. So to avoid special checks later on we force at least
  24234. * two codes of non zero frequency.
  24235. */
  24236. while (s.heap_len < 2) {
  24237. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24238. tree[node * 2]/*.Freq*/ = 1;
  24239. s.depth[node] = 0;
  24240. s.opt_len--;
  24241. if (has_stree) {
  24242. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24243. }
  24244. /* node is 0 or 1 so it does not have extra bits */
  24245. }
  24246. desc.max_code = max_code;
  24247. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24248. * establish sub-heaps of increasing lengths:
  24249. */
  24250. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24251. /* Construct the Huffman tree by repeatedly combining the least two
  24252. * frequent nodes.
  24253. */
  24254. node = elems; /* next internal node of the tree */
  24255. do {
  24256. //pqremove(s, tree, n); /* n = node of least frequency */
  24257. /*** pqremove ***/
  24258. n = s.heap[1/*SMALLEST*/];
  24259. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24260. pqdownheap(s, tree, 1/*SMALLEST*/);
  24261. /***/
  24262. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24263. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24264. s.heap[--s.heap_max] = m;
  24265. /* Create a new node father of n and m */
  24266. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24267. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24268. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24269. /* and insert the new node in the heap */
  24270. s.heap[1/*SMALLEST*/] = node++;
  24271. pqdownheap(s, tree, 1/*SMALLEST*/);
  24272. } while (s.heap_len >= 2);
  24273. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24274. /* At this point, the fields freq and dad are set. We can now
  24275. * generate the bit lengths.
  24276. */
  24277. gen_bitlen(s, desc);
  24278. /* The field len is now set, we can generate the bit codes */
  24279. gen_codes(tree, max_code, s.bl_count);
  24280. }
  24281. /* ===========================================================================
  24282. * Scan a literal or distance tree to determine the frequencies of the codes
  24283. * in the bit length tree.
  24284. */
  24285. function scan_tree(s, tree, max_code)
  24286. // deflate_state *s;
  24287. // ct_data *tree; /* the tree to be scanned */
  24288. // int max_code; /* and its largest code of non zero frequency */
  24289. {
  24290. var n; /* iterates over all tree elements */
  24291. var prevlen = -1; /* last emitted length */
  24292. var curlen; /* length of current code */
  24293. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24294. var count = 0; /* repeat count of the current code */
  24295. var max_count = 7; /* max repeat count */
  24296. var min_count = 4; /* min repeat count */
  24297. if (nextlen === 0) {
  24298. max_count = 138;
  24299. min_count = 3;
  24300. }
  24301. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24302. for (n = 0; n <= max_code; n++) {
  24303. curlen = nextlen;
  24304. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24305. if (++count < max_count && curlen === nextlen) {
  24306. continue;
  24307. } else if (count < min_count) {
  24308. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24309. } else if (curlen !== 0) {
  24310. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24311. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24312. } else if (count <= 10) {
  24313. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24314. } else {
  24315. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24316. }
  24317. count = 0;
  24318. prevlen = curlen;
  24319. if (nextlen === 0) {
  24320. max_count = 138;
  24321. min_count = 3;
  24322. } else if (curlen === nextlen) {
  24323. max_count = 6;
  24324. min_count = 3;
  24325. } else {
  24326. max_count = 7;
  24327. min_count = 4;
  24328. }
  24329. }
  24330. }
  24331. /* ===========================================================================
  24332. * Send a literal or distance tree in compressed form, using the codes in
  24333. * bl_tree.
  24334. */
  24335. function send_tree(s, tree, max_code)
  24336. // deflate_state *s;
  24337. // ct_data *tree; /* the tree to be scanned */
  24338. // int max_code; /* and its largest code of non zero frequency */
  24339. {
  24340. var n; /* iterates over all tree elements */
  24341. var prevlen = -1; /* last emitted length */
  24342. var curlen; /* length of current code */
  24343. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24344. var count = 0; /* repeat count of the current code */
  24345. var max_count = 7; /* max repeat count */
  24346. var min_count = 4; /* min repeat count */
  24347. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24348. if (nextlen === 0) {
  24349. max_count = 138;
  24350. min_count = 3;
  24351. }
  24352. for (n = 0; n <= max_code; n++) {
  24353. curlen = nextlen;
  24354. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24355. if (++count < max_count && curlen === nextlen) {
  24356. continue;
  24357. } else if (count < min_count) {
  24358. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24359. } else if (curlen !== 0) {
  24360. if (curlen !== prevlen) {
  24361. send_code(s, curlen, s.bl_tree);
  24362. count--;
  24363. }
  24364. //Assert(count >= 3 && count <= 6, " 3_6?");
  24365. send_code(s, REP_3_6, s.bl_tree);
  24366. send_bits(s, count-3, 2);
  24367. } else if (count <= 10) {
  24368. send_code(s, REPZ_3_10, s.bl_tree);
  24369. send_bits(s, count-3, 3);
  24370. } else {
  24371. send_code(s, REPZ_11_138, s.bl_tree);
  24372. send_bits(s, count-11, 7);
  24373. }
  24374. count = 0;
  24375. prevlen = curlen;
  24376. if (nextlen === 0) {
  24377. max_count = 138;
  24378. min_count = 3;
  24379. } else if (curlen === nextlen) {
  24380. max_count = 6;
  24381. min_count = 3;
  24382. } else {
  24383. max_count = 7;
  24384. min_count = 4;
  24385. }
  24386. }
  24387. }
  24388. /* ===========================================================================
  24389. * Construct the Huffman tree for the bit lengths and return the index in
  24390. * bl_order of the last bit length code to send.
  24391. */
  24392. function build_bl_tree(s) {
  24393. var max_blindex; /* index of last bit length code of non zero freq */
  24394. /* Determine the bit length frequencies for literal and distance trees */
  24395. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24396. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24397. /* Build the bit length tree: */
  24398. build_tree(s, s.bl_desc);
  24399. /* opt_len now includes the length of the tree representations, except
  24400. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24401. */
  24402. /* Determine the number of bit length codes to send. The pkzip format
  24403. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24404. * 3 but the actual value used is 4.)
  24405. */
  24406. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24407. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24408. break;
  24409. }
  24410. }
  24411. /* Update opt_len to include the bit length tree and counts */
  24412. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24413. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24414. // s->opt_len, s->static_len));
  24415. return max_blindex;
  24416. }
  24417. /* ===========================================================================
  24418. * Send the header for a block using dynamic Huffman trees: the counts, the
  24419. * lengths of the bit length codes, the literal tree and the distance tree.
  24420. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24421. */
  24422. function send_all_trees(s, lcodes, dcodes, blcodes)
  24423. // deflate_state *s;
  24424. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24425. {
  24426. var rank; /* index in bl_order */
  24427. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24428. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24429. // "too many codes");
  24430. //Tracev((stderr, "\nbl counts: "));
  24431. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24432. send_bits(s, dcodes-1, 5);
  24433. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24434. for (rank = 0; rank < blcodes; rank++) {
  24435. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24436. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24437. }
  24438. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24439. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24440. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24441. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24442. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24443. }
  24444. /* ===========================================================================
  24445. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24446. * - TEXT if the two conditions below are satisfied:
  24447. * a) There are no non-portable control characters belonging to the
  24448. * "black list" (0..6, 14..25, 28..31).
  24449. * b) There is at least one printable character belonging to the
  24450. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24451. * - BINARY otherwise.
  24452. * - The following partially-portable control characters form a
  24453. * "gray list" that is ignored in this detection algorithm:
  24454. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24455. * IN assertion: the fields Freq of dyn_ltree are set.
  24456. */
  24457. function detect_data_type(s) {
  24458. /* black_mask is the bit mask of black-listed bytes
  24459. * set bits 0..6, 14..25, and 28..31
  24460. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24461. */
  24462. var black_mask = 0xf3ffc07f;
  24463. var n;
  24464. /* Check for non-textual ("black-listed") bytes. */
  24465. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24466. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24467. return Z_BINARY;
  24468. }
  24469. }
  24470. /* Check for textual ("white-listed") bytes. */
  24471. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24472. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24473. return Z_TEXT;
  24474. }
  24475. for (n = 32; n < LITERALS; n++) {
  24476. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24477. return Z_TEXT;
  24478. }
  24479. }
  24480. /* There are no "black-listed" or "white-listed" bytes:
  24481. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24482. */
  24483. return Z_BINARY;
  24484. }
  24485. var static_init_done = false;
  24486. /* ===========================================================================
  24487. * Initialize the tree data structures for a new zlib stream.
  24488. */
  24489. function _tr_init(s)
  24490. {
  24491. if (!static_init_done) {
  24492. tr_static_init();
  24493. static_init_done = true;
  24494. }
  24495. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24496. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24497. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24498. s.bi_buf = 0;
  24499. s.bi_valid = 0;
  24500. /* Initialize the first block of the first file: */
  24501. init_block(s);
  24502. }
  24503. /* ===========================================================================
  24504. * Send a stored block
  24505. */
  24506. function _tr_stored_block(s, buf, stored_len, last)
  24507. //DeflateState *s;
  24508. //charf *buf; /* input block */
  24509. //ulg stored_len; /* length of input block */
  24510. //int last; /* one if this is the last block for a file */
  24511. {
  24512. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24513. copy_block(s, buf, stored_len, true); /* with header */
  24514. }
  24515. /* ===========================================================================
  24516. * Send one empty static block to give enough lookahead for inflate.
  24517. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24518. */
  24519. function _tr_align(s) {
  24520. send_bits(s, STATIC_TREES<<1, 3);
  24521. send_code(s, END_BLOCK, static_ltree);
  24522. bi_flush(s);
  24523. }
  24524. /* ===========================================================================
  24525. * Determine the best encoding for the current block: dynamic trees, static
  24526. * trees or store, and output the encoded block to the zip file.
  24527. */
  24528. function _tr_flush_block(s, buf, stored_len, last)
  24529. //DeflateState *s;
  24530. //charf *buf; /* input block, or NULL if too old */
  24531. //ulg stored_len; /* length of input block */
  24532. //int last; /* one if this is the last block for a file */
  24533. {
  24534. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24535. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24536. /* Build the Huffman trees unless a stored block is forced */
  24537. if (s.level > 0) {
  24538. /* Check if the file is binary or text */
  24539. if (s.strm.data_type === Z_UNKNOWN) {
  24540. s.strm.data_type = detect_data_type(s);
  24541. }
  24542. /* Construct the literal and distance trees */
  24543. build_tree(s, s.l_desc);
  24544. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24545. // s->static_len));
  24546. build_tree(s, s.d_desc);
  24547. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24548. // s->static_len));
  24549. /* At this point, opt_len and static_len are the total bit lengths of
  24550. * the compressed block data, excluding the tree representations.
  24551. */
  24552. /* Build the bit length tree for the above two trees, and get the index
  24553. * in bl_order of the last bit length code to send.
  24554. */
  24555. max_blindex = build_bl_tree(s);
  24556. /* Determine the best encoding. Compute the block lengths in bytes. */
  24557. opt_lenb = (s.opt_len+3+7) >>> 3;
  24558. static_lenb = (s.static_len+3+7) >>> 3;
  24559. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24560. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24561. // s->last_lit));
  24562. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24563. } else {
  24564. // Assert(buf != (char*)0, "lost buf");
  24565. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24566. }
  24567. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24568. /* 4: two words for the lengths */
  24569. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24570. * Otherwise we can't have processed more than WSIZE input bytes since
  24571. * the last block flush, because compression would have been
  24572. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24573. * transform a block into a stored block.
  24574. */
  24575. _tr_stored_block(s, buf, stored_len, last);
  24576. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24577. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24578. compress_block(s, static_ltree, static_dtree);
  24579. } else {
  24580. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24581. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24582. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24583. }
  24584. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24585. /* The above check is made mod 2^32, for files larger than 512 MB
  24586. * and uLong implemented on 32 bits.
  24587. */
  24588. init_block(s);
  24589. if (last) {
  24590. bi_windup(s);
  24591. }
  24592. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24593. // s->compressed_len-7*last));
  24594. }
  24595. /* ===========================================================================
  24596. * Save the match info and tally the frequency counts. Return true if
  24597. * the current block must be flushed.
  24598. */
  24599. function _tr_tally(s, dist, lc)
  24600. // deflate_state *s;
  24601. // unsigned dist; /* distance of matched string */
  24602. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24603. {
  24604. //var out_length, in_length, dcode;
  24605. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24606. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24607. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24608. s.last_lit++;
  24609. if (dist === 0) {
  24610. /* lc is the unmatched char */
  24611. s.dyn_ltree[lc*2]/*.Freq*/++;
  24612. } else {
  24613. s.matches++;
  24614. /* Here, lc is the match length - MIN_MATCH */
  24615. dist--; /* dist = match distance - 1 */
  24616. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24617. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24618. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24619. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24620. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24621. }
  24622. // (!) This block is disabled in zlib defailts,
  24623. // don't enable it for binary compatibility
  24624. //#ifdef TRUNCATE_BLOCK
  24625. // /* Try to guess if it is profitable to stop the current block here */
  24626. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24627. // /* Compute an upper bound for the compressed length */
  24628. // out_length = s.last_lit*8;
  24629. // in_length = s.strstart - s.block_start;
  24630. //
  24631. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24632. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24633. // }
  24634. // out_length >>>= 3;
  24635. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24636. // // s->last_lit, in_length, out_length,
  24637. // // 100L - out_length*100L/in_length));
  24638. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24639. // return true;
  24640. // }
  24641. // }
  24642. //#endif
  24643. return (s.last_lit === s.lit_bufsize-1);
  24644. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24645. * on 16 bit machines and because stored blocks are restricted to
  24646. * 64K-1 bytes.
  24647. */
  24648. }
  24649. exports._tr_init = _tr_init;
  24650. exports._tr_stored_block = _tr_stored_block;
  24651. exports._tr_flush_block = _tr_flush_block;
  24652. exports._tr_tally = _tr_tally;
  24653. exports._tr_align = _tr_align;
  24654. },{"../utils/common":72}],84:[function(require,module,exports){
  24655. 'use strict';
  24656. function ZStream() {
  24657. /* next input byte */
  24658. this.input = null; // JS specific, because we have no pointers
  24659. this.next_in = 0;
  24660. /* number of bytes available at input */
  24661. this.avail_in = 0;
  24662. /* total number of input bytes read so far */
  24663. this.total_in = 0;
  24664. /* next output byte should be put there */
  24665. this.output = null; // JS specific, because we have no pointers
  24666. this.next_out = 0;
  24667. /* remaining free space at output */
  24668. this.avail_out = 0;
  24669. /* total number of bytes output so far */
  24670. this.total_out = 0;
  24671. /* last error message, NULL if no error */
  24672. this.msg = ''/*Z_NULL*/;
  24673. /* not visible by applications */
  24674. this.state = null;
  24675. /* best guess about the data type: binary or text */
  24676. this.data_type = 2/*Z_UNKNOWN*/;
  24677. /* adler32 value of the uncompressed data */
  24678. this.adler = 0;
  24679. }
  24680. module.exports = ZStream;
  24681. },{}],85:[function(require,module,exports){
  24682. module.exports = require('./lib/retry');
  24683. },{"./lib/retry":86}],86:[function(require,module,exports){
  24684. var RetryOperation = require('./retry_operation');
  24685. exports.operation = function(options) {
  24686. var timeouts = exports.timeouts(options);
  24687. return new RetryOperation(timeouts);
  24688. };
  24689. exports.timeouts = function(options) {
  24690. if (options instanceof Array) {
  24691. return [].concat(options);
  24692. }
  24693. var opts = {
  24694. retries: 10,
  24695. factor: 2,
  24696. minTimeout: 1 * 1000,
  24697. maxTimeout: Infinity,
  24698. randomize: false
  24699. };
  24700. for (var key in options) {
  24701. opts[key] = options[key];
  24702. }
  24703. if (opts.minTimeout > opts.maxTimeout) {
  24704. throw new Error('minTimeout is greater than maxTimeout');
  24705. }
  24706. var timeouts = [];
  24707. for (var i = 0; i < opts.retries; i++) {
  24708. timeouts.push(this._createTimeout(i, opts));
  24709. }
  24710. // sort the array numerically ascending
  24711. timeouts.sort(function(a,b) {
  24712. return a - b;
  24713. });
  24714. return timeouts;
  24715. };
  24716. exports._createTimeout = function(attempt, opts) {
  24717. var random = (opts.randomize)
  24718. ? (Math.random() + 1)
  24719. : 1;
  24720. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  24721. timeout = Math.min(timeout, opts.maxTimeout);
  24722. return timeout;
  24723. };
  24724. },{"./retry_operation":87}],87:[function(require,module,exports){
  24725. function RetryOperation(timeouts) {
  24726. this._timeouts = timeouts;
  24727. this._fn = null;
  24728. this._errors = [];
  24729. this._attempts = 1;
  24730. this._operationTimeout = null;
  24731. this._operationTimeoutCb = null;
  24732. this._timeout = null;
  24733. }
  24734. module.exports = RetryOperation;
  24735. RetryOperation.prototype.retry = function(err) {
  24736. if (this._timeout) {
  24737. clearTimeout(this._timeout);
  24738. }
  24739. if (!err) {
  24740. return false;
  24741. }
  24742. this._errors.push(err);
  24743. var timeout = this._timeouts.shift();
  24744. if (timeout === undefined) {
  24745. return false;
  24746. }
  24747. this._attempts++;
  24748. var self = this;
  24749. setTimeout(function() {
  24750. self._fn(self._attempts);
  24751. if (self._operationTimeoutCb) {
  24752. self._timeout = setTimeout(function() {
  24753. self._operationTimeoutCb(self._attempts);
  24754. }, self._operationTimeout);
  24755. }
  24756. }, timeout);
  24757. return true;
  24758. };
  24759. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  24760. this._fn = fn;
  24761. if (timeoutOps) {
  24762. if (timeoutOps.timeout) {
  24763. this._operationTimeout = timeoutOps.timeout;
  24764. }
  24765. if (timeoutOps.cb) {
  24766. this._operationTimeoutCb = timeoutOps.cb;
  24767. }
  24768. }
  24769. this._fn(this._attempts);
  24770. var self = this;
  24771. if (this._operationTimeoutCb) {
  24772. this._timeout = setTimeout(function() {
  24773. self._operationTimeoutCb();
  24774. }, self._operationTimeout);
  24775. }
  24776. };
  24777. RetryOperation.prototype.try = function(fn) {
  24778. console.log('Using RetryOperation.try() is deprecated');
  24779. this.attempt(fn);
  24780. };
  24781. RetryOperation.prototype.start = function(fn) {
  24782. console.log('Using RetryOperation.start() is deprecated');
  24783. this.attempt(fn);
  24784. };
  24785. RetryOperation.prototype.start = RetryOperation.prototype.try;
  24786. RetryOperation.prototype.errors = function() {
  24787. return this._errors;
  24788. };
  24789. RetryOperation.prototype.attempts = function() {
  24790. return this._attempts;
  24791. };
  24792. RetryOperation.prototype.mainError = function() {
  24793. if (this._errors.length === 0) {
  24794. return null;
  24795. }
  24796. var counts = {};
  24797. var mainError = null;
  24798. var mainErrorCount = 0;
  24799. for (var i = 0; i < this._errors.length; i++) {
  24800. var error = this._errors[i];
  24801. var message = error.message;
  24802. var count = (counts[message] || 0) + 1;
  24803. counts[message] = count;
  24804. if (count >= mainErrorCount) {
  24805. mainError = error;
  24806. mainErrorCount = count;
  24807. }
  24808. }
  24809. return mainError;
  24810. };
  24811. },{}],88:[function(require,module,exports){
  24812. module.exports = function arrayEquals(array) {
  24813. // if the other array is a falsy value, return
  24814. if (!array)
  24815. return false;
  24816. // compare lengths - can save a lot of time
  24817. if (this.length != array.length)
  24818. return false;
  24819. for (var i = 0, l = this.length; i < l; i++) {
  24820. // Check if we have nested arrays
  24821. if (this[i] instanceof Array && array[i] instanceof Array) {
  24822. // recurse into the nested arrays
  24823. if (!arrayEquals.apply(this[i], [array[i]]))
  24824. return false;
  24825. } else if (this[i] != array[i]) {
  24826. // Warning - two different object instances will never be equal:
  24827. // {x:20} != {x:20}
  24828. return false;
  24829. }
  24830. }
  24831. return true;
  24832. }
  24833. },{}],89:[function(require,module,exports){
  24834. exports.Interop = require('./interop');
  24835. },{"./interop":90}],90:[function(require,module,exports){
  24836. "use strict";
  24837. var transform = require('./transform');
  24838. var arrayEquals = require('./array-equals');
  24839. function Interop() {
  24840. /**
  24841. * This map holds the most recent Unified Plan offer/answer SDP that was
  24842. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  24843. * the SDP string as values.
  24844. *
  24845. * @type {{}}
  24846. */
  24847. this.cache = {};
  24848. }
  24849. module.exports = Interop;
  24850. /**
  24851. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  24852. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  24853. * application.
  24854. *
  24855. * @param desc
  24856. * @returns {*}
  24857. */
  24858. Interop.prototype.toPlanB = function(desc) {
  24859. //#region Preliminary input validation.
  24860. if (typeof desc !== 'object' || desc === null ||
  24861. typeof desc.sdp !== 'string') {
  24862. console.warn('An empty description was passed as an argument.');
  24863. return desc;
  24864. }
  24865. // Objectify the SDP for easier manipulation.
  24866. var session = transform.parse(desc.sdp);
  24867. // If the SDP contains no media, there's nothing to transform.
  24868. if (typeof session.media === 'undefined' ||
  24869. !Array.isArray(session.media) || session.media.length === 0) {
  24870. console.warn('The description has no media.');
  24871. return desc;
  24872. }
  24873. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  24874. // SDP has a video, an audio and a data "channel" at most.
  24875. if (session.media.length <= 3 && session.media.every(function(m) {
  24876. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24877. })) {
  24878. console.warn('This description does not look like Unified Plan.');
  24879. return desc;
  24880. }
  24881. //#endregion
  24882. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  24883. // -> Unified Plan transformation.
  24884. this.cache[desc.type] = desc.sdp;
  24885. //#region Convert from Unified Plan to Plan B.
  24886. // We rebuild the session.media array.
  24887. var media = session.media;
  24888. session.media = [];
  24889. // Associative array that maps channel types to channel objects for fast
  24890. // access to channel objects by their type, e.g. type2bl['audio']->channel
  24891. // obj.
  24892. var type2bl = {};
  24893. // Used to build the group:BUNDLE value after the channels construction
  24894. // loop.
  24895. var types = [];
  24896. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  24897. media.forEach(function(unifiedLine) {
  24898. // rtcp-mux is required in the Plan B SDP.
  24899. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  24900. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  24901. unifiedLine.direction !== 'inactive') {
  24902. throw new Error('Cannot convert to Plan B because m-lines ' +
  24903. 'without the rtcp-mux attribute were found.');
  24904. }
  24905. if (unifiedLine.type === 'application') {
  24906. session.media.push(unifiedLine);
  24907. types.push(unifiedLine.mid);
  24908. return;
  24909. }
  24910. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  24911. // as the channel basis.
  24912. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  24913. type2bl[unifiedLine.type] = unifiedLine;
  24914. }
  24915. // Add sources to the channel and handle a=msid.
  24916. if (typeof unifiedLine.sources === 'object') {
  24917. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  24918. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  24919. type2bl[unifiedLine.type].sources = {};
  24920. // Assign the sources to the channel.
  24921. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  24922. if (typeof unifiedLine.msid !== 'undefined') {
  24923. // In Plan B the msid is an SSRC attribute. Also, we don't
  24924. // care about the obsolete label and mslabel attributes.
  24925. //
  24926. // Note that it is not guaranteed that the unifiedLine will have
  24927. // an msid. recvonly channels in particular don't have one.
  24928. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  24929. }
  24930. // NOTE ssrcs in ssrc groups will share msids, as
  24931. // draft-uberti-rtcweb-plan-00 mandates.
  24932. });
  24933. }
  24934. // Add ssrc groups to the channel.
  24935. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  24936. Array.isArray(unifiedLine.ssrcGroups)) {
  24937. // Create the ssrcGroups array, if it's not defined.
  24938. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  24939. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  24940. type2bl[unifiedLine.type].ssrcGroups = [];
  24941. }
  24942. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  24943. }
  24944. if (type2bl[unifiedLine.type] === unifiedLine) {
  24945. // Copy ICE related stuff from the principal media line.
  24946. unifiedLine.candidates = media[0].candidates;
  24947. unifiedLine.iceUfrag = media[0].iceUfrag;
  24948. unifiedLine.icePwd = media[0].icePwd;
  24949. unifiedLine.fingerprint = media[0].fingerprint;
  24950. // Plan B mids are in ['audio', 'video', 'data']
  24951. unifiedLine.mid = unifiedLine.type;
  24952. // Plan B doesn't support/need the bundle-only attribute.
  24953. delete unifiedLine.bundleOnly;
  24954. // In Plan B the msid is an SSRC attribute.
  24955. delete unifiedLine.msid;
  24956. // Used to build the group:BUNDLE value after this loop.
  24957. types.push(unifiedLine.type);
  24958. // Add the channel to the new media array.
  24959. session.media.push(unifiedLine);
  24960. }
  24961. });
  24962. // We regenerate the BUNDLE group with the new mids.
  24963. session.groups.some(function(group) {
  24964. if (group.type === 'BUNDLE') {
  24965. group.mids = types.join(' ');
  24966. return true;
  24967. }
  24968. });
  24969. // msid semantic
  24970. session.msidSemantic = {
  24971. semantic: 'WMS',
  24972. token: '*'
  24973. };
  24974. var resStr = transform.write(session);
  24975. return new RTCSessionDescription({
  24976. type: desc.type,
  24977. sdp: resStr
  24978. });
  24979. //#endregion
  24980. };
  24981. /**
  24982. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  24983. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  24984. * to FF.
  24985. *
  24986. * @param desc
  24987. * @returns {*}
  24988. */
  24989. Interop.prototype.toUnifiedPlan = function(desc) {
  24990. //#region Preliminary input validation.
  24991. if (typeof desc !== 'object' || desc === null ||
  24992. typeof desc.sdp !== 'string') {
  24993. console.warn('An empty description was passed as an argument.');
  24994. return desc;
  24995. }
  24996. var session = transform.parse(desc.sdp);
  24997. // If the SDP contains no media, there's nothing to transform.
  24998. if (typeof session.media === 'undefined' ||
  24999. !Array.isArray(session.media) || session.media.length === 0) {
  25000. console.warn('The description has no media.');
  25001. return desc;
  25002. }
  25003. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25004. // a video, an audio and a data "channel" at most.
  25005. if (session.media.length > 3 || !session.media.every(function(m) {
  25006. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25007. })) {
  25008. console.warn('This description does not look like Plan B.');
  25009. return desc;
  25010. }
  25011. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25012. var mids = [];
  25013. session.media.forEach(function(m) {
  25014. mids.push(m.mid);
  25015. });
  25016. var hasBundle = false;
  25017. if (typeof session.groups !== 'undefined' &&
  25018. Array.isArray(session.groups)) {
  25019. hasBundle = session.groups.every(function(g) {
  25020. return g.type !== 'BUNDLE' ||
  25021. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25022. });
  25023. }
  25024. if (!hasBundle) {
  25025. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25026. " are not bundled were found.");
  25027. }
  25028. //#endregion
  25029. //#region Convert from Plan B to Unified Plan.
  25030. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25031. // rebuild an equivalent Unified Plan offer/answer.
  25032. //
  25033. // For example, if this is a local answer (in Unified Plan style) that we
  25034. // convert to Plan B prior to handing it over to the application (the
  25035. // PeerConnection wrapper called us, for instance, after a successful
  25036. // createAnswer), we want to remember the m-line at which we've seen the
  25037. // (local) SSRC. That's because when the application wants to do call the
  25038. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25039. // Unified Plan), we need to know to which m-line to assign the (local)
  25040. // SSRC. We also need to know all the other m-lines that the original
  25041. // answer had and include them in the transformed answer as well.
  25042. //
  25043. // Another example is if this is a remote offer that we convert to Plan B
  25044. // prior to giving it to the application, we want to remember the mid at
  25045. // which we've seen the (remote) SSRC.
  25046. //
  25047. // In the iteration that follows, we use the cached Unified Plan (if it
  25048. // exists) to assign mids to ssrcs.
  25049. var cached;
  25050. if (typeof this.cache[desc.type] !== 'undefined') {
  25051. cached = transform.parse(this.cache[desc.type]);
  25052. }
  25053. // A helper map that sends mids to m-line objects. We use it later to
  25054. // rebuild the Unified Plan style session.media array.
  25055. var mid2ul = {};
  25056. session.media.forEach(function(bLine) {
  25057. if ((typeof bLine.rtcpMux !== 'string' ||
  25058. bLine.rtcpMux !== 'rtcp-mux') &&
  25059. bLine.direction !== 'inactive') {
  25060. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25061. "without the rtcp-mux attribute were found.");
  25062. }
  25063. if (bLine.type === 'application') {
  25064. mid2ul[bLine.mid] = bLine;
  25065. return;
  25066. }
  25067. // With rtcp-mux and bundle all the channels should have the same ICE
  25068. // stuff.
  25069. var sources = bLine.sources;
  25070. var ssrcGroups = bLine.ssrcGroups;
  25071. var candidates = bLine.candidates;
  25072. var iceUfrag = bLine.iceUfrag;
  25073. var icePwd = bLine.icePwd;
  25074. var fingerprint = bLine.fingerprint;
  25075. var port = bLine.port;
  25076. // We'll use the "bLine" object as a prototype for each new "mLine"
  25077. // that we create, but first we need to clean it up a bit.
  25078. delete bLine.sources;
  25079. delete bLine.ssrcGroups;
  25080. delete bLine.candidates;
  25081. delete bLine.iceUfrag;
  25082. delete bLine.icePwd;
  25083. delete bLine.fingerprint;
  25084. delete bLine.port;
  25085. delete bLine.mid;
  25086. // inverted ssrc group map
  25087. var ssrc2group = {};
  25088. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25089. ssrcGroups.forEach(function (ssrcGroup) {
  25090. // TODO(gp) find out how to receive simulcast with FF. For the
  25091. // time being, hide it.
  25092. if (ssrcGroup.semantics === 'SIM') {
  25093. return;
  25094. }
  25095. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25096. Array.isArray(ssrcGroup.ssrcs)) {
  25097. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25098. if (typeof ssrc2group[ssrc] === 'undefined') {
  25099. ssrc2group[ssrc] = [];
  25100. }
  25101. ssrc2group[ssrc].push(ssrcGroup);
  25102. });
  25103. }
  25104. });
  25105. }
  25106. // ssrc to m-line index.
  25107. var ssrc2ml = {};
  25108. if (typeof sources === 'object') {
  25109. // Explode the Plan B channel sources with one m-line per source.
  25110. Object.keys(sources).forEach(function(ssrc) {
  25111. // The (unified) m-line for this SSRC. We either create it from
  25112. // scratch or, if it's a grouped SSRC, we re-use a related
  25113. // mline. In other words, if the source is grouped with another
  25114. // source, put the two together in the same m-line.
  25115. var unifiedLine;
  25116. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25117. Array.isArray(ssrc2group[ssrc])) {
  25118. ssrc2group[ssrc].some(function (ssrcGroup) {
  25119. // ssrcGroup.ssrcs *is* an Array, no need to check
  25120. // again here.
  25121. return ssrcGroup.ssrcs.some(function (related) {
  25122. if (typeof ssrc2ml[related] === 'object') {
  25123. unifiedLine = ssrc2ml[related];
  25124. return true;
  25125. }
  25126. });
  25127. });
  25128. }
  25129. if (typeof unifiedLine === 'object') {
  25130. // the m-line already exists. Just add the source.
  25131. unifiedLine.sources[ssrc] = sources[ssrc];
  25132. delete sources[ssrc].msid;
  25133. } else {
  25134. // Use the "bLine" as a prototype for the "unifiedLine".
  25135. unifiedLine = Object.create(bLine);
  25136. ssrc2ml[ssrc] = unifiedLine;
  25137. if (typeof sources[ssrc].msid !== 'undefined') {
  25138. // Assign the msid of the source to the m-line. Note
  25139. // that it is not guaranteed that the source will have
  25140. // msid. In particular "recvonly" sources don't have an
  25141. // msid. Note that "recvonly" is a term only defined
  25142. // for m-lines.
  25143. unifiedLine.msid = sources[ssrc].msid;
  25144. delete sources[ssrc].msid;
  25145. }
  25146. // We assign one SSRC per media line.
  25147. unifiedLine.sources = {};
  25148. unifiedLine.sources[ssrc] = sources[ssrc];
  25149. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25150. // Use the cached Unified Plan SDP (if it exists) to assign
  25151. // SSRCs to mids.
  25152. if (typeof cached !== 'undefined' &&
  25153. typeof cached.media !== 'undefined' &&
  25154. Array.isArray(cached.media)) {
  25155. cached.media.forEach(function (m) {
  25156. if (typeof m.sources === 'object') {
  25157. Object.keys(m.sources).forEach(function (s) {
  25158. if (s === ssrc) {
  25159. unifiedLine.mid = m.mid;
  25160. }
  25161. });
  25162. }
  25163. });
  25164. }
  25165. if (typeof unifiedLine.mid === 'undefined') {
  25166. // If this is an SSRC that we see for the first time
  25167. // assign it a new mid. This is typically the case when
  25168. // this method is called to transform a remote
  25169. // description for the first time or when there is a
  25170. // new SSRC in the remote description because a new
  25171. // peer has joined the conference. Local SSRCs should
  25172. // have already been added to the map in the toPlanB
  25173. // method.
  25174. //
  25175. // Because FF generates answers in Unified Plan style,
  25176. // we MUST already have a cached answer with all the
  25177. // local SSRCs mapped to some m-line/mid.
  25178. if (desc.type === 'answer') {
  25179. throw new Error("An unmapped SSRC was found.");
  25180. }
  25181. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25182. }
  25183. // Include the candidates in the 1st media line.
  25184. unifiedLine.candidates = candidates;
  25185. unifiedLine.iceUfrag = iceUfrag;
  25186. unifiedLine.icePwd = icePwd;
  25187. unifiedLine.fingerprint = fingerprint;
  25188. unifiedLine.port = port;
  25189. mid2ul[unifiedLine.mid] = unifiedLine;
  25190. }
  25191. });
  25192. }
  25193. });
  25194. // Rebuild the media array in the right order and add the missing mLines
  25195. // (missing from the Plan B SDP).
  25196. session.media = [];
  25197. mids = []; // reuse
  25198. if (desc.type === 'answer') {
  25199. // The media lines in the answer must match the media lines in the
  25200. // offer. The order is important too. Here we assume that Firefox is the
  25201. // answerer, so we merely have to use the reconstructed (unified) answer
  25202. // to update the cached (unified) answer accordingly.
  25203. //
  25204. // In the general case, one would have to use the cached (unified) offer
  25205. // to find the m-lines that are missing from the reconstructed answer,
  25206. // potentially grabbing them from the cached (unified) answer. One has
  25207. // to be carefull with this approach because inactive m-lines do not
  25208. // always have an mid, making it tricky (impossible?) to find where
  25209. // exactly and which m-lines are missing from the reconstructed answer.
  25210. for (var i = 0; i < cached.media.length; i++) {
  25211. var unifiedLine = cached.media[i];
  25212. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25213. // The mid isn't in the reconstructed (unified) answer.
  25214. // This is either a (unified) m-line containing a remote
  25215. // track only, or a (unified) m-line containing a remote
  25216. // track and a local track that has been removed.
  25217. // In either case, it MUST exist in the cached
  25218. // (unified) answer.
  25219. //
  25220. // In case this is a removed local track, clean-up
  25221. // the (unified) m-line and make sure it's 'recvonly' or
  25222. // 'inactive'.
  25223. delete unifiedLine.msid;
  25224. delete unifiedLine.sources;
  25225. delete unifiedLine.ssrcGroups;
  25226. if (!unifiedLine.direction
  25227. || unifiedLine.direction === 'sendrecv')
  25228. unifiedLine.direction = 'recvonly';
  25229. if (!unifiedLine.direction
  25230. || unifiedLine.direction === 'sendonly')
  25231. unifiedLine.direction = 'inactive';
  25232. } else {
  25233. // This is an (unified) m-line/channel that contains a local
  25234. // track (sendrecv or sendonly channel) or it's a unified
  25235. // recvonly m-line/channel. In either case, since we're
  25236. // going from PlanB -> Unified Plan this m-line MUST
  25237. // exist in the cached answer.
  25238. }
  25239. session.media.push(unifiedLine);
  25240. if (typeof unifiedLine.mid === 'string') {
  25241. // inactive lines don't/may not have an mid.
  25242. mids.push(unifiedLine.mid);
  25243. }
  25244. }
  25245. } else {
  25246. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25247. // under any circumstances. If we are no longer interested in sending a
  25248. // track, we just remove the msid and ssrc attributes and set it to
  25249. // either a=recvonly (as the reofferer, we must use recvonly if the
  25250. // other side was previously sending on the m-section, but we can also
  25251. // leave the possibility open if it wasn't previously in use), or
  25252. // a=inacive.
  25253. if (typeof cached !== 'undefined' &&
  25254. typeof cached.media !== 'undefined' &&
  25255. Array.isArray(cached.media)) {
  25256. cached.media.forEach(function(unifiedLine) {
  25257. mids.push(unifiedLine.mid);
  25258. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25259. session.media.push(mid2ul[unifiedLine.mid]);
  25260. } else {
  25261. delete unifiedLine.msid;
  25262. delete unifiedLine.sources;
  25263. delete unifiedLine.ssrcGroups;
  25264. if (!unifiedLine.direction
  25265. || unifiedLine.direction === 'sendrecv')
  25266. unifiedLine.direction = 'recvonly';
  25267. if (!unifiedLine.direction
  25268. || unifiedLine.direction === 'sendonly')
  25269. unifiedLine.direction = 'inactive';
  25270. session.media.push(unifiedLine);
  25271. }
  25272. });
  25273. }
  25274. // Add all the remaining (new) m-lines of the transformed SDP.
  25275. Object.keys(mid2ul).forEach(function(mid) {
  25276. if (mids.indexOf(mid) === -1) {
  25277. mids.push(mid);
  25278. if (typeof mid2ul[mid].direction === 'recvonly') {
  25279. // This is a remote recvonly channel. Add its SSRC to the
  25280. // appropriate sendrecv or sendonly channel.
  25281. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25282. session.media.some(function (unifiedLine) {
  25283. if ((unifiedLine.direction === 'sendrecv' ||
  25284. unifiedLine.direction === 'sendonly') &&
  25285. unifiedLine.type === mid2ul[mid].type) {
  25286. // mid2ul[mid] shouldn't have any ssrc-groups
  25287. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25288. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25289. });
  25290. return true;
  25291. }
  25292. });
  25293. } else {
  25294. session.media.push(mid2ul[mid]);
  25295. }
  25296. }
  25297. });
  25298. }
  25299. // We regenerate the BUNDLE group (since we regenerated the mids)
  25300. session.groups.some(function(group) {
  25301. if (group.type === 'BUNDLE') {
  25302. group.mids = mids.join(' ');
  25303. return true;
  25304. }
  25305. });
  25306. // msid semantic
  25307. session.msidSemantic = {
  25308. semantic: 'WMS',
  25309. token: '*'
  25310. };
  25311. var resStr = transform.write(session);
  25312. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25313. // function.
  25314. this.cache[desc.type] = resStr;
  25315. return new RTCSessionDescription({
  25316. type: desc.type,
  25317. sdp: resStr
  25318. });
  25319. //#endregion
  25320. };
  25321. },{"./array-equals":88,"./transform":91}],91:[function(require,module,exports){
  25322. var transform = require('sdp-transform');
  25323. exports.write = function(session, opts) {
  25324. if (typeof session !== 'undefined' &&
  25325. typeof session.media !== 'undefined' &&
  25326. Array.isArray(session.media)) {
  25327. session.media.forEach(function (mLine) {
  25328. // expand sources to ssrcs
  25329. if (typeof mLine.sources !== 'undefined' &&
  25330. Object.keys(mLine.sources).length !== 0) {
  25331. mLine.ssrcs = [];
  25332. Object.keys(mLine.sources).forEach(function (ssrc) {
  25333. var source = mLine.sources[ssrc];
  25334. Object.keys(source).forEach(function (attribute) {
  25335. mLine.ssrcs.push({
  25336. id: ssrc,
  25337. attribute: attribute,
  25338. value: source[attribute]
  25339. });
  25340. });
  25341. });
  25342. delete mLine.sources;
  25343. }
  25344. // join ssrcs in ssrc groups
  25345. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25346. Array.isArray(mLine.ssrcGroups)) {
  25347. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25348. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25349. Array.isArray(ssrcGroup.ssrcs)) {
  25350. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25351. }
  25352. });
  25353. }
  25354. });
  25355. }
  25356. // join group mids
  25357. if (typeof session !== 'undefined' &&
  25358. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25359. session.groups.forEach(function (g) {
  25360. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25361. g.mids = g.mids.join(' ');
  25362. }
  25363. });
  25364. }
  25365. return transform.write(session, opts);
  25366. };
  25367. exports.parse = function(sdp) {
  25368. var session = transform.parse(sdp);
  25369. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25370. Array.isArray(session.media)) {
  25371. session.media.forEach(function (mLine) {
  25372. // group sources attributes by ssrc
  25373. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25374. mLine.sources = {};
  25375. mLine.ssrcs.forEach(function (ssrc) {
  25376. if (!mLine.sources[ssrc.id])
  25377. mLine.sources[ssrc.id] = {};
  25378. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25379. });
  25380. delete mLine.ssrcs;
  25381. }
  25382. // split ssrcs in ssrc groups
  25383. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25384. Array.isArray(mLine.ssrcGroups)) {
  25385. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25386. if (typeof ssrcGroup.ssrcs === 'string') {
  25387. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25388. }
  25389. });
  25390. }
  25391. });
  25392. }
  25393. // split group mids
  25394. if (typeof session !== 'undefined' &&
  25395. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25396. session.groups.forEach(function (g) {
  25397. if (typeof g.mids === 'string') {
  25398. g.mids = g.mids.split(' ');
  25399. }
  25400. });
  25401. }
  25402. return session;
  25403. };
  25404. },{"sdp-transform":93}],92:[function(require,module,exports){
  25405. var grammar = module.exports = {
  25406. v: [{
  25407. name: 'version',
  25408. reg: /^(\d*)$/
  25409. }],
  25410. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25411. // NB: sessionId will be a String in most cases because it is huge
  25412. name: 'origin',
  25413. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25414. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25415. format: "%s %s %d %s IP%d %s"
  25416. }],
  25417. // default parsing of these only (though some of these feel outdated)
  25418. s: [{ name: 'name' }],
  25419. i: [{ name: 'description' }],
  25420. u: [{ name: 'uri' }],
  25421. e: [{ name: 'email' }],
  25422. p: [{ name: 'phone' }],
  25423. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25424. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25425. //k: [{}], // outdated thing ignored
  25426. t: [{ //t=0 0
  25427. name: 'timing',
  25428. reg: /^(\d*) (\d*)/,
  25429. names: ['start', 'stop'],
  25430. format: "%d %d"
  25431. }],
  25432. c: [{ //c=IN IP4 10.47.197.26
  25433. name: 'connection',
  25434. reg: /^IN IP(\d) (\S*)/,
  25435. names: ['version', 'ip'],
  25436. format: "IN IP%d %s"
  25437. }],
  25438. b: [{ //b=AS:4000
  25439. push: 'bandwidth',
  25440. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25441. names: ['type', 'limit'],
  25442. format: "%s:%s"
  25443. }],
  25444. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25445. // NB: special - pushes to session
  25446. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25447. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25448. names: ['type', 'port', 'protocol', 'payloads'],
  25449. format: "%s %d %s %s"
  25450. }],
  25451. a: [
  25452. { //a=rtpmap:110 opus/48000/2
  25453. push: 'rtp',
  25454. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25455. names: ['payload', 'codec', 'rate', 'encoding'],
  25456. format: function (o) {
  25457. return (o.encoding) ?
  25458. "rtpmap:%d %s/%s/%s":
  25459. "rtpmap:%d %s/%s";
  25460. }
  25461. },
  25462. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25463. push: 'fmtp',
  25464. reg: /^fmtp:(\d*) (\S*)/,
  25465. names: ['payload', 'config'],
  25466. format: "fmtp:%d %s"
  25467. },
  25468. { //a=control:streamid=0
  25469. name: 'control',
  25470. reg: /^control:(.*)/,
  25471. format: "control:%s"
  25472. },
  25473. { //a=rtcp:65179 IN IP4 193.84.77.194
  25474. name: 'rtcp',
  25475. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25476. names: ['port', 'netType', 'ipVer', 'address'],
  25477. format: function (o) {
  25478. return (o.address != null) ?
  25479. "rtcp:%d %s IP%d %s":
  25480. "rtcp:%d";
  25481. }
  25482. },
  25483. { //a=rtcp-fb:98 trr-int 100
  25484. push: 'rtcpFbTrrInt',
  25485. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25486. names: ['payload', 'value'],
  25487. format: "rtcp-fb:%d trr-int %d"
  25488. },
  25489. { //a=rtcp-fb:98 nack rpsi
  25490. push: 'rtcpFb',
  25491. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25492. names: ['payload', 'type', 'subtype'],
  25493. format: function (o) {
  25494. return (o.subtype != null) ?
  25495. "rtcp-fb:%s %s %s":
  25496. "rtcp-fb:%s %s";
  25497. }
  25498. },
  25499. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25500. //a=extmap:1/recvonly URI-gps-string
  25501. push: 'ext',
  25502. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25503. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25504. format: function (o) {
  25505. return (o.config != null) ?
  25506. "extmap:%s %s %s":
  25507. "extmap:%s %s";
  25508. }
  25509. },
  25510. {
  25511. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25512. push: 'crypto',
  25513. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25514. names: ['id', 'suite', 'config', 'sessionConfig'],
  25515. format: function (o) {
  25516. return (o.sessionConfig != null) ?
  25517. "crypto:%d %s %s %s":
  25518. "crypto:%d %s %s";
  25519. }
  25520. },
  25521. { //a=setup:actpass
  25522. name: 'setup',
  25523. reg: /^setup:(\w*)/,
  25524. format: "setup:%s"
  25525. },
  25526. { //a=mid:1
  25527. name: 'mid',
  25528. reg: /^mid:([^\s]*)/,
  25529. format: "mid:%s"
  25530. },
  25531. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25532. name: 'msid',
  25533. reg: /^msid:(.*)/,
  25534. format: "msid:%s"
  25535. },
  25536. { //a=ptime:20
  25537. name: 'ptime',
  25538. reg: /^ptime:(\d*)/,
  25539. format: "ptime:%d"
  25540. },
  25541. { //a=maxptime:60
  25542. name: 'maxptime',
  25543. reg: /^maxptime:(\d*)/,
  25544. format: "maxptime:%d"
  25545. },
  25546. { //a=sendrecv
  25547. name: 'direction',
  25548. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25549. },
  25550. { //a=ice-lite
  25551. name: 'icelite',
  25552. reg: /^(ice-lite)/
  25553. },
  25554. { //a=ice-ufrag:F7gI
  25555. name: 'iceUfrag',
  25556. reg: /^ice-ufrag:(\S*)/,
  25557. format: "ice-ufrag:%s"
  25558. },
  25559. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25560. name: 'icePwd',
  25561. reg: /^ice-pwd:(\S*)/,
  25562. format: "ice-pwd:%s"
  25563. },
  25564. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25565. name: 'fingerprint',
  25566. reg: /^fingerprint:(\S*) (\S*)/,
  25567. names: ['type', 'hash'],
  25568. format: "fingerprint:%s %s"
  25569. },
  25570. {
  25571. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25572. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25573. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25574. push:'candidates',
  25575. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  25576. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  25577. format: function (o) {
  25578. var str = "candidate:%s %d %s %d %s %d typ %s";
  25579. // NB: candidate has two optional chunks, so %void middle one if it's missing
  25580. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25581. if (o.generation != null) {
  25582. str += " generation %d";
  25583. }
  25584. return str;
  25585. }
  25586. },
  25587. { //a=end-of-candidates (keep after the candidates line for readability)
  25588. name: 'endOfCandidates',
  25589. reg: /^(end-of-candidates)/
  25590. },
  25591. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25592. name: 'remoteCandidates',
  25593. reg: /^remote-candidates:(.*)/,
  25594. format: "remote-candidates:%s"
  25595. },
  25596. { //a=ice-options:google-ice
  25597. name: 'iceOptions',
  25598. reg: /^ice-options:(\S*)/,
  25599. format: "ice-options:%s"
  25600. },
  25601. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25602. push: "ssrcs",
  25603. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25604. names: ['id', 'attribute', 'value'],
  25605. format: "ssrc:%d %s:%s"
  25606. },
  25607. { //a=ssrc-group:FEC 1 2
  25608. push: "ssrcGroups",
  25609. reg: /^ssrc-group:(\w*) (.*)/,
  25610. names: ['semantics', 'ssrcs'],
  25611. format: "ssrc-group:%s %s"
  25612. },
  25613. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25614. name: "msidSemantic",
  25615. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25616. names: ['semantic', 'token'],
  25617. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25618. },
  25619. { //a=group:BUNDLE audio video
  25620. push: 'groups',
  25621. reg: /^group:(\w*) (.*)/,
  25622. names: ['type', 'mids'],
  25623. format: "group:%s %s"
  25624. },
  25625. { //a=rtcp-mux
  25626. name: 'rtcpMux',
  25627. reg: /^(rtcp-mux)/
  25628. },
  25629. { //a=rtcp-rsize
  25630. name: 'rtcpRsize',
  25631. reg: /^(rtcp-rsize)/
  25632. },
  25633. { // any a= that we don't understand is kepts verbatim on media.invalid
  25634. push: 'invalid',
  25635. names: ["value"]
  25636. }
  25637. ]
  25638. };
  25639. // set sensible defaults to avoid polluting the grammar with boring details
  25640. Object.keys(grammar).forEach(function (key) {
  25641. var objs = grammar[key];
  25642. objs.forEach(function (obj) {
  25643. if (!obj.reg) {
  25644. obj.reg = /(.*)/;
  25645. }
  25646. if (!obj.format) {
  25647. obj.format = "%s";
  25648. }
  25649. });
  25650. });
  25651. },{}],93:[function(require,module,exports){
  25652. var parser = require('./parser');
  25653. var writer = require('./writer');
  25654. exports.write = writer;
  25655. exports.parse = parser.parse;
  25656. exports.parseFmtpConfig = parser.parseFmtpConfig;
  25657. exports.parsePayloads = parser.parsePayloads;
  25658. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  25659. },{"./parser":94,"./writer":95}],94:[function(require,module,exports){
  25660. var toIntIfInt = function (v) {
  25661. return String(Number(v)) === v ? Number(v) : v;
  25662. };
  25663. var attachProperties = function (match, location, names, rawName) {
  25664. if (rawName && !names) {
  25665. location[rawName] = toIntIfInt(match[1]);
  25666. }
  25667. else {
  25668. for (var i = 0; i < names.length; i += 1) {
  25669. if (match[i+1] != null) {
  25670. location[names[i]] = toIntIfInt(match[i+1]);
  25671. }
  25672. }
  25673. }
  25674. };
  25675. var parseReg = function (obj, location, content) {
  25676. var needsBlank = obj.name && obj.names;
  25677. if (obj.push && !location[obj.push]) {
  25678. location[obj.push] = [];
  25679. }
  25680. else if (needsBlank && !location[obj.name]) {
  25681. location[obj.name] = {};
  25682. }
  25683. var keyLocation = obj.push ?
  25684. {} : // blank object that will be pushed
  25685. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  25686. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  25687. if (obj.push) {
  25688. location[obj.push].push(keyLocation);
  25689. }
  25690. };
  25691. var grammar = require('./grammar');
  25692. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  25693. exports.parse = function (sdp) {
  25694. var session = {}
  25695. , media = []
  25696. , location = session; // points at where properties go under (one of the above)
  25697. // parse lines we understand
  25698. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  25699. var type = l[0];
  25700. var content = l.slice(2);
  25701. if (type === 'm') {
  25702. media.push({rtp: [], fmtp: []});
  25703. location = media[media.length-1]; // point at latest media line
  25704. }
  25705. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  25706. var obj = grammar[type][j];
  25707. if (obj.reg.test(content)) {
  25708. return parseReg(obj, location, content);
  25709. }
  25710. }
  25711. });
  25712. session.media = media; // link it up
  25713. return session;
  25714. };
  25715. var fmtpReducer = function (acc, expr) {
  25716. var s = expr.split('=');
  25717. if (s.length === 2) {
  25718. acc[s[0]] = toIntIfInt(s[1]);
  25719. }
  25720. return acc;
  25721. };
  25722. exports.parseFmtpConfig = function (str) {
  25723. return str.split(';').reduce(fmtpReducer, {});
  25724. };
  25725. exports.parsePayloads = function (str) {
  25726. return str.split(' ').map(Number);
  25727. };
  25728. exports.parseRemoteCandidates = function (str) {
  25729. var candidates = [];
  25730. var parts = str.split(' ').map(toIntIfInt);
  25731. for (var i = 0; i < parts.length; i += 3) {
  25732. candidates.push({
  25733. component: parts[i],
  25734. ip: parts[i + 1],
  25735. port: parts[i + 2]
  25736. });
  25737. }
  25738. return candidates;
  25739. };
  25740. },{"./grammar":92}],95:[function(require,module,exports){
  25741. var grammar = require('./grammar');
  25742. // customized util.format - discards excess arguments and can void middle ones
  25743. var formatRegExp = /%[sdv%]/g;
  25744. var format = function (formatStr) {
  25745. var i = 1;
  25746. var args = arguments;
  25747. var len = args.length;
  25748. return formatStr.replace(formatRegExp, function (x) {
  25749. if (i >= len) {
  25750. return x; // missing argument
  25751. }
  25752. var arg = args[i];
  25753. i += 1;
  25754. switch (x) {
  25755. case '%%':
  25756. return '%';
  25757. case '%s':
  25758. return String(arg);
  25759. case '%d':
  25760. return Number(arg);
  25761. case '%v':
  25762. return '';
  25763. }
  25764. });
  25765. // NB: we discard excess arguments - they are typically undefined from makeLine
  25766. };
  25767. var makeLine = function (type, obj, location) {
  25768. var str = obj.format instanceof Function ?
  25769. (obj.format(obj.push ? location : location[obj.name])) :
  25770. obj.format;
  25771. var args = [type + '=' + str];
  25772. if (obj.names) {
  25773. for (var i = 0; i < obj.names.length; i += 1) {
  25774. var n = obj.names[i];
  25775. if (obj.name) {
  25776. args.push(location[obj.name][n]);
  25777. }
  25778. else { // for mLine and push attributes
  25779. args.push(location[obj.names[i]]);
  25780. }
  25781. }
  25782. }
  25783. else {
  25784. args.push(location[obj.name]);
  25785. }
  25786. return format.apply(null, args);
  25787. };
  25788. // RFC specified order
  25789. // TODO: extend this with all the rest
  25790. var defaultOuterOrder = [
  25791. 'v', 'o', 's', 'i',
  25792. 'u', 'e', 'p', 'c',
  25793. 'b', 't', 'r', 'z', 'a'
  25794. ];
  25795. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  25796. module.exports = function (session, opts) {
  25797. opts = opts || {};
  25798. // ensure certain properties exist
  25799. if (session.version == null) {
  25800. session.version = 0; // "v=0" must be there (only defined version atm)
  25801. }
  25802. if (session.name == null) {
  25803. session.name = " "; // "s= " must be there if no meaningful name set
  25804. }
  25805. session.media.forEach(function (mLine) {
  25806. if (mLine.payloads == null) {
  25807. mLine.payloads = "";
  25808. }
  25809. });
  25810. var outerOrder = opts.outerOrder || defaultOuterOrder;
  25811. var innerOrder = opts.innerOrder || defaultInnerOrder;
  25812. var sdp = [];
  25813. // loop through outerOrder for matching properties on session
  25814. outerOrder.forEach(function (type) {
  25815. grammar[type].forEach(function (obj) {
  25816. if (obj.name in session && session[obj.name] != null) {
  25817. sdp.push(makeLine(type, obj, session));
  25818. }
  25819. else if (obj.push in session && session[obj.push] != null) {
  25820. session[obj.push].forEach(function (el) {
  25821. sdp.push(makeLine(type, obj, el));
  25822. });
  25823. }
  25824. });
  25825. });
  25826. // then for each media line, follow the innerOrder
  25827. session.media.forEach(function (mLine) {
  25828. sdp.push(makeLine('m', grammar.m[0], mLine));
  25829. innerOrder.forEach(function (type) {
  25830. grammar[type].forEach(function (obj) {
  25831. if (obj.name in mLine && mLine[obj.name] != null) {
  25832. sdp.push(makeLine(type, obj, mLine));
  25833. }
  25834. else if (obj.push in mLine && mLine[obj.push] != null) {
  25835. mLine[obj.push].forEach(function (el) {
  25836. sdp.push(makeLine(type, obj, el));
  25837. });
  25838. }
  25839. });
  25840. });
  25841. });
  25842. return sdp.join('\r\n') + '\r\n';
  25843. };
  25844. },{"./grammar":92}],96:[function(require,module,exports){
  25845. var transform = require('sdp-transform');
  25846. var transformUtils = require('./transform-utils');
  25847. var parseSsrcs = transformUtils.parseSsrcs;
  25848. var writeSsrcs = transformUtils.writeSsrcs;
  25849. //region Constants
  25850. var DEFAULT_NUM_OF_LAYERS = 3;
  25851. //endregion
  25852. //region Ctor
  25853. function Simulcast(options) {
  25854. this.options = options ? options : {};
  25855. if (!this.options.numOfLayers) {
  25856. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  25857. }
  25858. this.layers = [];
  25859. }
  25860. //endregion
  25861. //region Stateless private utility functions
  25862. /**
  25863. * Returns a random integer between min (included) and max (excluded)
  25864. * Using Math.round() gives a non-uniform distribution!
  25865. * @returns {number}
  25866. */
  25867. function generateSSRC() {
  25868. var min = 0, max = 0xffffffff;
  25869. return Math.floor(Math.random() * (max - min)) + min;
  25870. };
  25871. function processVideo(session, action) {
  25872. if (session == null || !Array.isArray(session.media)) {
  25873. return;
  25874. }
  25875. session.media.forEach(function (mLine) {
  25876. if (mLine.type === 'video') {
  25877. action(mLine);
  25878. }
  25879. });
  25880. }
  25881. function validateDescription(desc)
  25882. {
  25883. return desc && desc != null
  25884. && desc.type && desc.type != ''
  25885. && desc.sdp && desc.sdp != '';
  25886. }
  25887. function explodeRemoteSimulcast(mLine) {
  25888. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25889. return;
  25890. }
  25891. var sources = parseSsrcs(mLine);
  25892. var order = [];
  25893. // Find the SIM group and explode its sources.
  25894. var j = mLine.ssrcGroups.length;
  25895. while (j--) {
  25896. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  25897. continue;
  25898. }
  25899. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  25900. for (var i = 0; i < simulcastSsrcs.length; i++) {
  25901. var ssrc = simulcastSsrcs[i];
  25902. order.push(ssrc);
  25903. var parts = sources[ssrc].msid.split(' ');
  25904. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  25905. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  25906. // Remove all the groups that this SSRC participates in.
  25907. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25908. if (relatedGroup.semantics === 'SIM') {
  25909. return;
  25910. }
  25911. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25912. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25913. return;
  25914. }
  25915. // Nuke all the related SSRCs.
  25916. relatedSsrcs.forEach(function (relatedSSRC) {
  25917. sources[relatedSSRC].msid = sources[ssrc].msid;
  25918. sources[relatedSSRC].cname = sources[ssrc].cname;
  25919. if (relatedSSRC !== ssrc) {
  25920. order.push(relatedSSRC);
  25921. }
  25922. });
  25923. // Schedule the related group for nuking.
  25924. })
  25925. }
  25926. mLine.ssrcs = writeSsrcs(sources, order);
  25927. mLine.ssrcGroups.splice(j, 1);
  25928. };
  25929. }
  25930. function squeezeRemoteSimulcast(mLine) {
  25931. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25932. return;
  25933. }
  25934. var sources = parseSsrcs(mLine);
  25935. // Find the SIM group and nuke it.
  25936. mLine.ssrcGroups.some(function (simulcastGroup) {
  25937. if (simulcastGroup.semantics !== 'SIM') {
  25938. return false;
  25939. }
  25940. // Schedule the SIM group for nuking.
  25941. simulcastGroup.nuke = true;
  25942. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  25943. // Nuke all the higher layer SSRCs.
  25944. for (var i = 1; i < simulcastSsrcs.length; i++) {
  25945. var ssrc = simulcastSsrcs[i];
  25946. delete sources[ssrc];
  25947. // Remove all the groups that this SSRC participates in.
  25948. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25949. if (relatedGroup.semantics === 'SIM') {
  25950. return;
  25951. }
  25952. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25953. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25954. return;
  25955. }
  25956. // Nuke all the related SSRCs.
  25957. relatedSsrcs.forEach(function (relatedSSRC) {
  25958. delete sources[relatedSSRC];
  25959. });
  25960. // Schedule the related group for nuking.
  25961. relatedGroup.nuke = true;
  25962. })
  25963. }
  25964. return true;
  25965. });
  25966. mLine.ssrcs = writeSsrcs(sources);
  25967. // Nuke all the scheduled groups.
  25968. var i = mLine.ssrcGroups.length;
  25969. while (i--) {
  25970. if (mLine.ssrcGroups[i].nuke) {
  25971. mLine.ssrcGroups.splice(i, 1);
  25972. }
  25973. }
  25974. }
  25975. function removeGoogConference(mLine) {
  25976. if (!mLine || !Array.isArray(mLine.invalid)) {
  25977. return;
  25978. }
  25979. var i = mLine.invalid.length;
  25980. while (i--) {
  25981. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  25982. mLine.invalid.splice(i, 1);
  25983. }
  25984. }
  25985. }
  25986. function assertGoogConference(mLine) {
  25987. if (!mLine) {
  25988. return;
  25989. }
  25990. if (!Array.isArray(mLine.invalid)) {
  25991. mLine.invalid = [];
  25992. }
  25993. if (!mLine.invalid.some(
  25994. function (i) { return i.value === 'x-google-flag:conference' })) {
  25995. mLine.invalid.push({'value': 'x-google-flag:conference'});
  25996. }
  25997. }
  25998. //endregion
  25999. //region "Private" functions
  26000. /**
  26001. *
  26002. * @param mLine
  26003. * @private
  26004. */
  26005. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26006. if (!mLine || mLine.type !== 'video') {
  26007. return;
  26008. }
  26009. var sources = parseSsrcs(mLine);
  26010. if (Object.keys(sources).length === 0) {
  26011. // no sources, disable simulcast.
  26012. if (this.layers.length !== 0) {
  26013. this.layers = [];
  26014. }
  26015. return;
  26016. }
  26017. // find the base layer (we'll reuse its msid and cname).
  26018. var baseLayerSSRC = Object.keys(sources)[0];
  26019. var baseLayer = sources[baseLayerSSRC];
  26020. // todo(gp) handle screen sharing.
  26021. // check if base CNAME has changed and reinitialise layers.
  26022. if (this.layers.length > 0
  26023. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26024. this.layers = [];
  26025. }
  26026. // (re)initialise layers
  26027. if (this.layers.length < 1) {
  26028. // first push the base layer.
  26029. this.layers.push({
  26030. ssrc: baseLayerSSRC,
  26031. msid: baseLayer.msid,
  26032. cname: baseLayer.cname
  26033. });
  26034. var rtx = false; // RFC 4588
  26035. if (Array.isArray(mLine.rtp)) {
  26036. rtx = mLine.rtp.some(
  26037. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26038. }
  26039. if (rtx) {
  26040. this.layers[0].rtx = generateSSRC();
  26041. }
  26042. // now push additional layers.
  26043. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26044. var layer = { ssrc: generateSSRC() };
  26045. if (rtx) {
  26046. layer.rtx = generateSSRC();
  26047. }
  26048. this.layers.push(layer);
  26049. }
  26050. }
  26051. };
  26052. /**
  26053. *
  26054. * @param mLine
  26055. * @private
  26056. */
  26057. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26058. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26059. var sources = {};
  26060. var msid = this.layers[0].msid;
  26061. var cname = this.layers[0].cname;
  26062. var simulcastSsrcs = [];
  26063. var ssrcGroups = [];
  26064. for (var i = 0; i < this.layers.length; i++) {
  26065. var layer = this.layers[i];
  26066. sources[layer.ssrc] = { msid: msid, cname: cname };
  26067. simulcastSsrcs.push(layer.ssrc);
  26068. if (layer.rtx) {
  26069. sources[layer.rtx] = {
  26070. msid: msid,
  26071. cname: cname
  26072. }
  26073. ssrcGroups.push({
  26074. semantics: 'FID',
  26075. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26076. });
  26077. }
  26078. }
  26079. ssrcGroups.push({
  26080. semantics: 'SIM',
  26081. ssrcs: simulcastSsrcs.join(' ')
  26082. });
  26083. mLine.ssrcGroups = ssrcGroups;
  26084. mLine.ssrcs = writeSsrcs(sources);
  26085. }
  26086. }
  26087. //endregion
  26088. //region "Public" functions
  26089. Simulcast.prototype.isSupported = function () {
  26090. return window.chrome;
  26091. // TODO this needs improvements. For example I doubt that Chrome in Android
  26092. // has simulcast support. Also, only recent versions of Chromium have native
  26093. // simulcast support.
  26094. }
  26095. /**
  26096. *
  26097. * @param desc
  26098. * @returns {RTCSessionDescription}
  26099. */
  26100. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26101. if (!validateDescription(desc)) {
  26102. return desc;
  26103. }
  26104. var session = transform.parse(desc.sdp);
  26105. var self = this;
  26106. processVideo(session, function (mLine) {
  26107. // Handle simulcast reception.
  26108. if (self.options.explodeRemoteSimulcast) {
  26109. explodeRemoteSimulcast(mLine);
  26110. } else {
  26111. squeezeRemoteSimulcast(mLine);
  26112. }
  26113. // If native simulcast is enabled, we must append the x-goog-conference
  26114. // attribute to the SDP.
  26115. if (self.layers.length < 1) {
  26116. removeGoogConference(mLine);
  26117. } else {
  26118. assertGoogConference(mLine);
  26119. }
  26120. });
  26121. return new RTCSessionDescription({
  26122. type: desc.type,
  26123. sdp: transform.write(session)
  26124. });
  26125. };
  26126. /**
  26127. *
  26128. * @param desc
  26129. * @returns {RTCSessionDescription}
  26130. */
  26131. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26132. if (!validateDescription(desc) || !this.isSupported()) {
  26133. return desc;
  26134. }
  26135. var session = transform.parse(desc.sdp);
  26136. var self = this;
  26137. processVideo(session, function (mLine) {
  26138. // Initialize native simulcast layers, if not already done.
  26139. self._maybeInitializeLayers(mLine);
  26140. // Update the SDP with the simulcast layers.
  26141. self._restoreSimulcastView(mLine);
  26142. });
  26143. return new RTCSessionDescription({
  26144. type: desc.type,
  26145. sdp: transform.write(session)
  26146. });
  26147. };
  26148. //endregion
  26149. module.exports = Simulcast;
  26150. },{"./transform-utils":97,"sdp-transform":99}],97:[function(require,module,exports){
  26151. exports.writeSsrcs = function(sources, order) {
  26152. var ssrcs = [];
  26153. // expand sources to ssrcs
  26154. if (typeof sources !== 'undefined' &&
  26155. Object.keys(sources).length !== 0) {
  26156. if (Array.isArray(order)) {
  26157. for (var i = 0; i < order.length; i++) {
  26158. var ssrc = order[i];
  26159. var source = sources[ssrc];
  26160. Object.keys(source).forEach(function (attribute) {
  26161. ssrcs.push({
  26162. id: ssrc,
  26163. attribute: attribute,
  26164. value: source[attribute]
  26165. });
  26166. });
  26167. }
  26168. } else {
  26169. Object.keys(sources).forEach(function (ssrc) {
  26170. var source = sources[ssrc];
  26171. Object.keys(source).forEach(function (attribute) {
  26172. ssrcs.push({
  26173. id: ssrc,
  26174. attribute: attribute,
  26175. value: source[attribute]
  26176. });
  26177. });
  26178. });
  26179. }
  26180. }
  26181. return ssrcs;
  26182. };
  26183. exports.parseSsrcs = function (mLine) {
  26184. var sources = {};
  26185. // group sources attributes by ssrc.
  26186. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26187. mLine.ssrcs.forEach(function (ssrc) {
  26188. if (!sources[ssrc.id])
  26189. sources[ssrc.id] = {};
  26190. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26191. });
  26192. }
  26193. return sources;
  26194. };
  26195. },{}],98:[function(require,module,exports){
  26196. arguments[4][92][0].apply(exports,arguments)
  26197. },{"dup":92}],99:[function(require,module,exports){
  26198. arguments[4][93][0].apply(exports,arguments)
  26199. },{"./parser":100,"./writer":101,"dup":93}],100:[function(require,module,exports){
  26200. arguments[4][94][0].apply(exports,arguments)
  26201. },{"./grammar":98,"dup":94}],101:[function(require,module,exports){
  26202. arguments[4][95][0].apply(exports,arguments)
  26203. },{"./grammar":98,"dup":95}],102:[function(require,module,exports){
  26204. var MediaStreamType = {
  26205. VIDEO_TYPE: "Video",
  26206. AUDIO_TYPE: "Audio"
  26207. };
  26208. module.exports = MediaStreamType;
  26209. },{}],103:[function(require,module,exports){
  26210. var RTCEvents = {
  26211. RTC_READY: "rtc.ready",
  26212. LASTN_CHANGED: "rtc.lastn_changed",
  26213. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26214. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26215. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26216. AUDIO_MUTE: "rtc.audio_mute",
  26217. VIDEO_MUTE: "rtc.video_mute"
  26218. };
  26219. module.exports = RTCEvents;
  26220. },{}],104:[function(require,module,exports){
  26221. var Resolutions = {
  26222. "1080": {
  26223. width: 1920,
  26224. height: 1080,
  26225. order: 7
  26226. },
  26227. "fullhd": {
  26228. width: 1920,
  26229. height: 1080,
  26230. order: 7
  26231. },
  26232. "720": {
  26233. width: 1280,
  26234. height: 720,
  26235. order: 6
  26236. },
  26237. "hd": {
  26238. width: 1280,
  26239. height: 720,
  26240. order: 6
  26241. },
  26242. "960": {
  26243. width: 960,
  26244. height: 720,
  26245. order: 5
  26246. },
  26247. "640": {
  26248. width: 640,
  26249. height: 480,
  26250. order: 4
  26251. },
  26252. "vga": {
  26253. width: 640,
  26254. height: 480,
  26255. order: 4
  26256. },
  26257. "360": {
  26258. width: 640,
  26259. height: 360,
  26260. order: 3
  26261. },
  26262. "320": {
  26263. width: 320,
  26264. height: 240,
  26265. order: 2
  26266. },
  26267. "180": {
  26268. width: 320,
  26269. height: 180,
  26270. order: 1
  26271. }
  26272. };
  26273. module.exports = Resolutions;
  26274. },{}],105:[function(require,module,exports){
  26275. var StreamEventTypes = {
  26276. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26277. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26278. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26279. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26280. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  26281. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  26282. };
  26283. module.exports = StreamEventTypes;
  26284. },{}],106:[function(require,module,exports){
  26285. var UIEvents = {
  26286. NICKNAME_CHANGED: "UI.nickname_changed",
  26287. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26288. PINNED_ENDPOINT: "UI.pinned_endpoint"
  26289. };
  26290. module.exports = UIEvents;
  26291. },{}],107:[function(require,module,exports){
  26292. var AuthenticationEvents = {
  26293. /**
  26294. * Event callback arguments:
  26295. * function(authenticationEnabled, userIdentity)
  26296. * authenticationEnabled - indicates whether authentication has been enabled
  26297. * in this session
  26298. * userIdentity - if user has been logged in then it contains user name. If
  26299. * contains 'null' or 'undefined' then user is not logged in.
  26300. */
  26301. IDENTITY_UPDATED: "authentication.identity_updated"
  26302. };
  26303. module.exports = AuthenticationEvents;
  26304. },{}],108:[function(require,module,exports){
  26305. var CQEvents = {
  26306. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26307. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26308. STOP: "cq.stop"
  26309. };
  26310. module.exports = CQEvents;
  26311. },{}],109:[function(require,module,exports){
  26312. var DesktopSharingEventTypes = {
  26313. INIT: "ds.init",
  26314. SWITCHING_DONE: "ds.switching_done",
  26315. NEW_STREAM_CREATED: "ds.new_stream_created"
  26316. };
  26317. module.exports = DesktopSharingEventTypes;
  26318. },{}],110:[function(require,module,exports){
  26319. var Events = {
  26320. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26321. };
  26322. module.exports = Events;
  26323. },{}],111:[function(require,module,exports){
  26324. module.exports = {
  26325. getLanguages : function () {
  26326. var languages = [];
  26327. for(var lang in this)
  26328. {
  26329. if(typeof this[lang] === "string")
  26330. languages.push(this[lang]);
  26331. }
  26332. return languages;
  26333. },
  26334. EN: "en",
  26335. BG: "bg",
  26336. DE: "de",
  26337. TR: "tr",
  26338. FR: "fr"
  26339. }
  26340. },{}],112:[function(require,module,exports){
  26341. var XMPPEvents = {
  26342. CONNECTION_FAILED: "xmpp.connection.failed",
  26343. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26344. CALL_INCOMING: "xmpp.callincoming.jingle",
  26345. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26346. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26347. KICKED: "xmpp.kicked",
  26348. BRIDGE_DOWN: "xmpp.bridge_down",
  26349. USER_ID_CHANGED: "xmpp.user_id_changed",
  26350. // We joined the MUC
  26351. MUC_JOINED: "xmpp.muc_joined",
  26352. // A member joined the MUC
  26353. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26354. // A member left the MUC
  26355. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26356. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26357. MUC_DESTROYED: "xmpp.muc_destroyed",
  26358. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26359. REMOTE_STATS: "xmpp.remote_stats",
  26360. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26361. PRESENCE_STATUS: "xmpp.presence_status",
  26362. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26363. SUBJECT_CHANGED: "xmpp.subject_changed",
  26364. MESSAGE_RECEIVED: "xmpp.message_received",
  26365. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26366. PASSWORD_REQUIRED: "xmpp.password_required",
  26367. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26368. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26369. ETHERPAD: "xmpp.etherpad",
  26370. DEVICE_AVAILABLE: "xmpp.device_available",
  26371. START_MUTED: "xmpp.start_muted",
  26372. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  26373. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  26374. AUDIO_MUTED: "xmpp.audio_muted",
  26375. VIDEO_MUTED: "xmpp.video_muted"
  26376. };
  26377. module.exports = XMPPEvents;
  26378. },{}],113:[function(require,module,exports){
  26379. // Copyright Joyent, Inc. and other Node contributors.
  26380. //
  26381. // Permission is hereby granted, free of charge, to any person obtaining a
  26382. // copy of this software and associated documentation files (the
  26383. // "Software"), to deal in the Software without restriction, including
  26384. // without limitation the rights to use, copy, modify, merge, publish,
  26385. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26386. // persons to whom the Software is furnished to do so, subject to the
  26387. // following conditions:
  26388. //
  26389. // The above copyright notice and this permission notice shall be included
  26390. // in all copies or substantial portions of the Software.
  26391. //
  26392. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26393. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26394. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26395. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26396. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26397. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26398. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26399. function EventEmitter() {
  26400. this._events = this._events || {};
  26401. this._maxListeners = this._maxListeners || undefined;
  26402. }
  26403. module.exports = EventEmitter;
  26404. // Backwards-compat with node 0.10.x
  26405. EventEmitter.EventEmitter = EventEmitter;
  26406. EventEmitter.prototype._events = undefined;
  26407. EventEmitter.prototype._maxListeners = undefined;
  26408. // By default EventEmitters will print a warning if more than 10 listeners are
  26409. // added to it. This is a useful default which helps finding memory leaks.
  26410. EventEmitter.defaultMaxListeners = 10;
  26411. // Obviously not all Emitters should be limited to 10. This function allows
  26412. // that to be increased. Set to zero for unlimited.
  26413. EventEmitter.prototype.setMaxListeners = function(n) {
  26414. if (!isNumber(n) || n < 0 || isNaN(n))
  26415. throw TypeError('n must be a positive number');
  26416. this._maxListeners = n;
  26417. return this;
  26418. };
  26419. EventEmitter.prototype.emit = function(type) {
  26420. var er, handler, len, args, i, listeners;
  26421. if (!this._events)
  26422. this._events = {};
  26423. // If there is no 'error' event listener then throw.
  26424. if (type === 'error') {
  26425. if (!this._events.error ||
  26426. (isObject(this._events.error) && !this._events.error.length)) {
  26427. er = arguments[1];
  26428. if (er instanceof Error) {
  26429. throw er; // Unhandled 'error' event
  26430. }
  26431. throw TypeError('Uncaught, unspecified "error" event.');
  26432. }
  26433. }
  26434. handler = this._events[type];
  26435. if (isUndefined(handler))
  26436. return false;
  26437. if (isFunction(handler)) {
  26438. switch (arguments.length) {
  26439. // fast cases
  26440. case 1:
  26441. handler.call(this);
  26442. break;
  26443. case 2:
  26444. handler.call(this, arguments[1]);
  26445. break;
  26446. case 3:
  26447. handler.call(this, arguments[1], arguments[2]);
  26448. break;
  26449. // slower
  26450. default:
  26451. len = arguments.length;
  26452. args = new Array(len - 1);
  26453. for (i = 1; i < len; i++)
  26454. args[i - 1] = arguments[i];
  26455. handler.apply(this, args);
  26456. }
  26457. } else if (isObject(handler)) {
  26458. len = arguments.length;
  26459. args = new Array(len - 1);
  26460. for (i = 1; i < len; i++)
  26461. args[i - 1] = arguments[i];
  26462. listeners = handler.slice();
  26463. len = listeners.length;
  26464. for (i = 0; i < len; i++)
  26465. listeners[i].apply(this, args);
  26466. }
  26467. return true;
  26468. };
  26469. EventEmitter.prototype.addListener = function(type, listener) {
  26470. var m;
  26471. if (!isFunction(listener))
  26472. throw TypeError('listener must be a function');
  26473. if (!this._events)
  26474. this._events = {};
  26475. // To avoid recursion in the case that type === "newListener"! Before
  26476. // adding it to the listeners, first emit "newListener".
  26477. if (this._events.newListener)
  26478. this.emit('newListener', type,
  26479. isFunction(listener.listener) ?
  26480. listener.listener : listener);
  26481. if (!this._events[type])
  26482. // Optimize the case of one listener. Don't need the extra array object.
  26483. this._events[type] = listener;
  26484. else if (isObject(this._events[type]))
  26485. // If we've already got an array, just append.
  26486. this._events[type].push(listener);
  26487. else
  26488. // Adding the second element, need to change to array.
  26489. this._events[type] = [this._events[type], listener];
  26490. // Check for listener leak
  26491. if (isObject(this._events[type]) && !this._events[type].warned) {
  26492. var m;
  26493. if (!isUndefined(this._maxListeners)) {
  26494. m = this._maxListeners;
  26495. } else {
  26496. m = EventEmitter.defaultMaxListeners;
  26497. }
  26498. if (m && m > 0 && this._events[type].length > m) {
  26499. this._events[type].warned = true;
  26500. console.error('(node) warning: possible EventEmitter memory ' +
  26501. 'leak detected. %d listeners added. ' +
  26502. 'Use emitter.setMaxListeners() to increase limit.',
  26503. this._events[type].length);
  26504. if (typeof console.trace === 'function') {
  26505. // not supported in IE 10
  26506. console.trace();
  26507. }
  26508. }
  26509. }
  26510. return this;
  26511. };
  26512. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  26513. EventEmitter.prototype.once = function(type, listener) {
  26514. if (!isFunction(listener))
  26515. throw TypeError('listener must be a function');
  26516. var fired = false;
  26517. function g() {
  26518. this.removeListener(type, g);
  26519. if (!fired) {
  26520. fired = true;
  26521. listener.apply(this, arguments);
  26522. }
  26523. }
  26524. g.listener = listener;
  26525. this.on(type, g);
  26526. return this;
  26527. };
  26528. // emits a 'removeListener' event iff the listener was removed
  26529. EventEmitter.prototype.removeListener = function(type, listener) {
  26530. var list, position, length, i;
  26531. if (!isFunction(listener))
  26532. throw TypeError('listener must be a function');
  26533. if (!this._events || !this._events[type])
  26534. return this;
  26535. list = this._events[type];
  26536. length = list.length;
  26537. position = -1;
  26538. if (list === listener ||
  26539. (isFunction(list.listener) && list.listener === listener)) {
  26540. delete this._events[type];
  26541. if (this._events.removeListener)
  26542. this.emit('removeListener', type, listener);
  26543. } else if (isObject(list)) {
  26544. for (i = length; i-- > 0;) {
  26545. if (list[i] === listener ||
  26546. (list[i].listener && list[i].listener === listener)) {
  26547. position = i;
  26548. break;
  26549. }
  26550. }
  26551. if (position < 0)
  26552. return this;
  26553. if (list.length === 1) {
  26554. list.length = 0;
  26555. delete this._events[type];
  26556. } else {
  26557. list.splice(position, 1);
  26558. }
  26559. if (this._events.removeListener)
  26560. this.emit('removeListener', type, listener);
  26561. }
  26562. return this;
  26563. };
  26564. EventEmitter.prototype.removeAllListeners = function(type) {
  26565. var key, listeners;
  26566. if (!this._events)
  26567. return this;
  26568. // not listening for removeListener, no need to emit
  26569. if (!this._events.removeListener) {
  26570. if (arguments.length === 0)
  26571. this._events = {};
  26572. else if (this._events[type])
  26573. delete this._events[type];
  26574. return this;
  26575. }
  26576. // emit removeListener for all listeners on all events
  26577. if (arguments.length === 0) {
  26578. for (key in this._events) {
  26579. if (key === 'removeListener') continue;
  26580. this.removeAllListeners(key);
  26581. }
  26582. this.removeAllListeners('removeListener');
  26583. this._events = {};
  26584. return this;
  26585. }
  26586. listeners = this._events[type];
  26587. if (isFunction(listeners)) {
  26588. this.removeListener(type, listeners);
  26589. } else {
  26590. // LIFO order
  26591. while (listeners.length)
  26592. this.removeListener(type, listeners[listeners.length - 1]);
  26593. }
  26594. delete this._events[type];
  26595. return this;
  26596. };
  26597. EventEmitter.prototype.listeners = function(type) {
  26598. var ret;
  26599. if (!this._events || !this._events[type])
  26600. ret = [];
  26601. else if (isFunction(this._events[type]))
  26602. ret = [this._events[type]];
  26603. else
  26604. ret = this._events[type].slice();
  26605. return ret;
  26606. };
  26607. EventEmitter.listenerCount = function(emitter, type) {
  26608. var ret;
  26609. if (!emitter._events || !emitter._events[type])
  26610. ret = 0;
  26611. else if (isFunction(emitter._events[type]))
  26612. ret = 1;
  26613. else
  26614. ret = emitter._events[type].length;
  26615. return ret;
  26616. };
  26617. function isFunction(arg) {
  26618. return typeof arg === 'function';
  26619. }
  26620. function isNumber(arg) {
  26621. return typeof arg === 'number';
  26622. }
  26623. function isObject(arg) {
  26624. return typeof arg === 'object' && arg !== null;
  26625. }
  26626. function isUndefined(arg) {
  26627. return arg === void 0;
  26628. }
  26629. },{}],114:[function(require,module,exports){
  26630. // shim for using process in browser
  26631. var process = module.exports = {};
  26632. var queue = [];
  26633. var draining = false;
  26634. function drainQueue() {
  26635. if (draining) {
  26636. return;
  26637. }
  26638. draining = true;
  26639. var currentQueue;
  26640. var len = queue.length;
  26641. while(len) {
  26642. currentQueue = queue;
  26643. queue = [];
  26644. var i = -1;
  26645. while (++i < len) {
  26646. currentQueue[i]();
  26647. }
  26648. len = queue.length;
  26649. }
  26650. draining = false;
  26651. }
  26652. process.nextTick = function (fun) {
  26653. queue.push(fun);
  26654. if (!draining) {
  26655. setTimeout(drainQueue, 0);
  26656. }
  26657. };
  26658. process.title = 'browser';
  26659. process.browser = true;
  26660. process.env = {};
  26661. process.argv = [];
  26662. process.version = ''; // empty string to avoid regexp issues
  26663. function noop() {}
  26664. process.on = noop;
  26665. process.addListener = noop;
  26666. process.once = noop;
  26667. process.off = noop;
  26668. process.removeListener = noop;
  26669. process.removeAllListeners = noop;
  26670. process.emit = noop;
  26671. process.binding = function (name) {
  26672. throw new Error('process.binding is not supported');
  26673. };
  26674. // TODO(shtylman)
  26675. process.cwd = function () { return '/' };
  26676. process.chdir = function (dir) {
  26677. throw new Error('process.chdir is not supported');
  26678. };
  26679. process.umask = function() { return 0; };
  26680. },{}]},{},[1])(1)
  26681. });