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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  13. this.xmpp = require("./modules/xmpp/xmpp");
  14. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  15. this.translation = require("./modules/translation/translation");
  16. this.settings = require("./modules/settings/Settings");
  17. this.DTMF = require("./modules/DTMF/DTMF");
  18. this.members = require("./modules/members/MemberList");
  19. }
  20. };
  21. function init() {
  22. APP.desktopsharing.init();
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. APP.keyboardshortcut.init();
  28. APP.members.start();
  29. }
  30. $(document).ready(function () {
  31. var URLPRocessor = require("./modules/URLProcessor/URLProcessor");
  32. URLPRocessor.setConfigParametersFromUrl();
  33. APP.init();
  34. APP.translation.init();
  35. if(APP.API.isEnabled())
  36. APP.API.init();
  37. APP.UI.start(init);
  38. });
  39. $(window).bind('beforeunload', function () {
  40. if(APP.API.isEnabled())
  41. APP.API.dispose();
  42. });
  43. module.exports = APP;
  44. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":11,"./modules/URLProcessor/URLProcessor":42,"./modules/connectionquality/connectionquality":43,"./modules/desktopsharing/desktopsharing":44,"./modules/keyboardshortcut/keyboardshortcut":45,"./modules/members/MemberList":46,"./modules/settings/Settings":47,"./modules/statistics/statistics":51,"./modules/translation/translation":52,"./modules/xmpp/xmpp":66}],2:[function(require,module,exports){
  45. /**
  46. * Implements API class that communicates with external api class
  47. * and provides interface to access Jitsi Meet features by external
  48. * applications that embed Jitsi Meet
  49. */
  50. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  51. /**
  52. * List of the available commands.
  53. * @type {{
  54. * displayName: inputDisplayNameHandler,
  55. * muteAudio: toggleAudio,
  56. * muteVideo: toggleVideo,
  57. * filmStrip: toggleFilmStrip
  58. * }}
  59. */
  60. var commands = {};
  61. function initCommands() {
  62. commands =
  63. {
  64. displayName: APP.UI.inputDisplayNameHandler,
  65. muteAudio: APP.UI.toggleAudio,
  66. muteVideo: APP.UI.toggleVideo,
  67. toggleFilmStrip: APP.UI.toggleFilmStrip,
  68. toggleChat: APP.UI.toggleChat,
  69. toggleContactList: APP.UI.toggleContactList
  70. };
  71. }
  72. /**
  73. * Maps the supported events and their status
  74. * (true it the event is enabled and false if it is disabled)
  75. * @type {{
  76. * incomingMessage: boolean,
  77. * outgoingMessage: boolean,
  78. * displayNameChange: boolean,
  79. * participantJoined: boolean,
  80. * participantLeft: boolean
  81. * }}
  82. */
  83. var events =
  84. {
  85. incomingMessage: false,
  86. outgoingMessage:false,
  87. displayNameChange: false,
  88. participantJoined: false,
  89. participantLeft: false
  90. };
  91. var displayName = {};
  92. /**
  93. * Processes commands from external applicaiton.
  94. * @param message the object with the command
  95. */
  96. function processCommand(message)
  97. {
  98. if(message.action != "execute")
  99. {
  100. console.error("Unknown action of the message");
  101. return;
  102. }
  103. for(var key in message)
  104. {
  105. if(commands[key])
  106. commands[key].apply(null, message[key]);
  107. }
  108. }
  109. /**
  110. * Processes events objects from external applications
  111. * @param event the event
  112. */
  113. function processEvent(event) {
  114. if(!event.action)
  115. {
  116. console.error("Event with no action is received.");
  117. return;
  118. }
  119. var i = 0;
  120. switch(event.action)
  121. {
  122. case "add":
  123. for(; i < event.events.length; i++)
  124. {
  125. events[event.events[i]] = true;
  126. }
  127. break;
  128. case "remove":
  129. for(; i < event.events.length; i++)
  130. {
  131. events[event.events[i]] = false;
  132. }
  133. break;
  134. default:
  135. console.error("Unknown action for event.");
  136. }
  137. }
  138. /**
  139. * Sends message to the external application.
  140. * @param object
  141. */
  142. function sendMessage(object) {
  143. window.parent.postMessage(JSON.stringify(object), "*");
  144. }
  145. /**
  146. * Processes a message event from the external application
  147. * @param event the message event
  148. */
  149. function processMessage(event)
  150. {
  151. var message;
  152. try {
  153. message = JSON.parse(event.data);
  154. } catch (e) {}
  155. if(!message.type)
  156. return;
  157. switch (message.type)
  158. {
  159. case "command":
  160. processCommand(message);
  161. break;
  162. case "event":
  163. processEvent(message);
  164. break;
  165. default:
  166. console.error("Unknown type of the message");
  167. return;
  168. }
  169. }
  170. function setupListeners() {
  171. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  172. API.triggerEvent("participantJoined", {jid: from});
  173. });
  174. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  175. if (from != myjid)
  176. API.triggerEvent("incomingMessage",
  177. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  178. });
  179. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  180. API.triggerEvent("participantLeft", {jid: jid});
  181. });
  182. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  183. name = displayName[jid];
  184. if(!name || name != newDisplayName) {
  185. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  186. displayName[jid] = newDisplayName;
  187. }
  188. });
  189. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  190. APP.API.triggerEvent("outgoingMessage", {"message": body});
  191. });
  192. }
  193. var API = {
  194. /**
  195. * Check whether the API should be enabled or not.
  196. * @returns {boolean}
  197. */
  198. isEnabled: function () {
  199. var hash = location.hash;
  200. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  201. return true;
  202. return false;
  203. },
  204. /**
  205. * Initializes the APIConnector. Setups message event listeners that will
  206. * receive information from external applications that embed Jitsi Meet.
  207. * It also sends a message to the external application that APIConnector
  208. * is initialized.
  209. */
  210. init: function () {
  211. initCommands();
  212. if (window.addEventListener)
  213. {
  214. window.addEventListener('message',
  215. processMessage, false);
  216. }
  217. else
  218. {
  219. window.attachEvent('onmessage', processMessage);
  220. }
  221. sendMessage({type: "system", loaded: true});
  222. setupListeners();
  223. },
  224. /**
  225. * Checks whether the event is enabled ot not.
  226. * @param name the name of the event.
  227. * @returns {*}
  228. */
  229. isEventEnabled: function (name) {
  230. return events[name];
  231. },
  232. /**
  233. * Sends event object to the external application that has been subscribed
  234. * for that event.
  235. * @param name the name event
  236. * @param object data associated with the event
  237. */
  238. triggerEvent: function (name, object) {
  239. if(this.isEnabled() && this.isEventEnabled(name))
  240. sendMessage({
  241. type: "event", action: "result", event: name, result: object});
  242. },
  243. /**
  244. * Removes the listeners.
  245. */
  246. dispose: function () {
  247. if(window.removeEventListener)
  248. {
  249. window.removeEventListener("message",
  250. processMessage, false);
  251. }
  252. else
  253. {
  254. window.detachEvent('onmessage', processMessage);
  255. }
  256. }
  257. };
  258. module.exports = API;
  259. },{"../../service/xmpp/XMPPEvents":108}],3:[function(require,module,exports){
  260. /* global APP */
  261. /**
  262. * A module for sending DTMF tones.
  263. */
  264. var DTMFSender;
  265. var initDtmfSender = function() {
  266. // TODO: This needs to reset this if the peerconnection changes
  267. // (e.g. the call is re-made)
  268. if (DTMFSender)
  269. return;
  270. var localAudio = APP.RTC.localAudio;
  271. if (localAudio && localAudio.getTracks().length > 0)
  272. {
  273. var peerconnection
  274. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  275. if (peerconnection) {
  276. DTMFSender =
  277. peerconnection.peerconnection
  278. .createDTMFSender(localAudio.getTracks()[0]);
  279. console.log("Initialized DTMFSender");
  280. }
  281. else {
  282. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  283. }
  284. }
  285. else {
  286. console.log("Failed to initialize DTMFSender: no audio track.");
  287. }
  288. };
  289. var DTMF = {
  290. sendTones: function (tones, duration, pause) {
  291. if (!DTMFSender)
  292. initDtmfSender();
  293. if (DTMFSender){
  294. DTMFSender.insertDTMF(tones,
  295. (duration || 200),
  296. (pause || 200));
  297. }
  298. }
  299. };
  300. module.exports = DTMF;
  301. },{}],4:[function(require,module,exports){
  302. /* global Strophe, focusedVideoSrc*/
  303. // cache datachannels to avoid garbage collection
  304. // https://code.google.com/p/chromium/issues/detail?id=405545
  305. var RTCEvents = require("../../service/RTC/RTCEvents");
  306. var _dataChannels = [];
  307. var eventEmitter = null;
  308. var DataChannels =
  309. {
  310. /**
  311. * Callback triggered by PeerConnection when new data channel is opened
  312. * on the bridge.
  313. * @param event the event info object.
  314. */
  315. onDataChannel: function (event)
  316. {
  317. var dataChannel = event.channel;
  318. dataChannel.onopen = function () {
  319. console.info("Data channel opened by the Videobridge!", dataChannel);
  320. // Code sample for sending string and/or binary data
  321. // Sends String message to the bridge
  322. //dataChannel.send("Hello bridge!");
  323. // Sends 12 bytes binary message to the bridge
  324. //dataChannel.send(new ArrayBuffer(12));
  325. // when the data channel becomes available, tell the bridge about video
  326. // selections so that it can do adaptive simulcast,
  327. // we want the notification to trigger even if userJid is undefined,
  328. // or null.
  329. var userJid = APP.UI.getLargeVideoJid();
  330. // we want the notification to trigger even if userJid is undefined,
  331. // or null.
  332. onSelectedEndpointChanged(userJid);
  333. };
  334. dataChannel.onerror = function (error) {
  335. console.error("Data Channel Error:", error, dataChannel);
  336. };
  337. dataChannel.onmessage = function (event) {
  338. var data = event.data;
  339. // JSON
  340. var obj;
  341. try {
  342. obj = JSON.parse(data);
  343. }
  344. catch (e) {
  345. console.error(
  346. "Failed to parse data channel message as JSON: ",
  347. data,
  348. dataChannel);
  349. }
  350. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  351. var colibriClass = obj.colibriClass;
  352. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  353. // Endpoint ID from the Videobridge.
  354. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  355. console.info(
  356. "Data channel new dominant speaker event: ",
  357. dominantSpeakerEndpoint);
  358. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  359. }
  360. else if ("InLastNChangeEvent" === colibriClass)
  361. {
  362. var oldValue = obj.oldValue;
  363. var newValue = obj.newValue;
  364. // Make sure that oldValue and newValue are of type boolean.
  365. var type;
  366. if ((type = typeof oldValue) !== 'boolean') {
  367. if (type === 'string') {
  368. oldValue = (oldValue == "true");
  369. } else {
  370. oldValue = new Boolean(oldValue).valueOf();
  371. }
  372. }
  373. if ((type = typeof newValue) !== 'boolean') {
  374. if (type === 'string') {
  375. newValue = (newValue == "true");
  376. } else {
  377. newValue = new Boolean(newValue).valueOf();
  378. }
  379. }
  380. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  381. }
  382. else if ("LastNEndpointsChangeEvent" === colibriClass)
  383. {
  384. // The new/latest list of last-n endpoint IDs.
  385. var lastNEndpoints = obj.lastNEndpoints;
  386. // The list of endpoint IDs which are entering the list of
  387. // last-n at this time i.e. were not in the old list of last-n
  388. // endpoint IDs.
  389. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  390. var stream = obj.stream;
  391. console.log(
  392. "Data channel new last-n event: ",
  393. lastNEndpoints, endpointsEnteringLastN, obj);
  394. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  395. lastNEndpoints, endpointsEnteringLastN, obj);
  396. }
  397. else
  398. {
  399. console.debug("Data channel JSON-formatted message: ", obj);
  400. }
  401. }
  402. };
  403. dataChannel.onclose = function ()
  404. {
  405. console.info("The Data Channel closed", dataChannel);
  406. var idx = _dataChannels.indexOf(dataChannel);
  407. if (idx > -1)
  408. _dataChannels = _dataChannels.splice(idx, 1);
  409. };
  410. _dataChannels.push(dataChannel);
  411. },
  412. /**
  413. * Binds "ondatachannel" event listener to given PeerConnection instance.
  414. * @param peerConnection WebRTC peer connection instance.
  415. */
  416. init: function (peerConnection, emitter) {
  417. if(!config.openSctp)
  418. return;
  419. peerConnection.ondatachannel = this.onDataChannel;
  420. eventEmitter = emitter;
  421. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  422. // Although it's not a requirement to open separate channels from both bridge
  423. // and peer as single channel can be used for sending and receiving data.
  424. // So either channel opened by the bridge or the one opened here is enough
  425. // for communication with the bridge.
  426. /*var dataChannelOptions =
  427. {
  428. reliable: true
  429. };
  430. var dataChannel
  431. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  432. // Can be used only when is in open state
  433. dataChannel.onopen = function ()
  434. {
  435. dataChannel.send("My channel !!!");
  436. };
  437. dataChannel.onmessage = function (event)
  438. {
  439. var msgData = event.data;
  440. console.info("Got My Data Channel Message:", msgData, dataChannel);
  441. };*/
  442. },
  443. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  444. handlePinnedEndpointEvent: onPinnedEndpointChanged
  445. };
  446. function onSelectedEndpointChanged(userResource)
  447. {
  448. console.log('selected endpoint changed: ', userResource);
  449. if (_dataChannels && _dataChannels.length != 0)
  450. {
  451. _dataChannels.some(function (dataChannel) {
  452. if (dataChannel.readyState == 'open')
  453. {
  454. console.log('sending selected endpoint changed '
  455. + 'notification to the bridge: ', userResource);
  456. dataChannel.send(JSON.stringify({
  457. 'colibriClass': 'SelectedEndpointChangedEvent',
  458. 'selectedEndpoint':
  459. (!userResource || userResource === null)?
  460. null : userResource
  461. }));
  462. return true;
  463. }
  464. });
  465. }
  466. }
  467. function onPinnedEndpointChanged(userResource)
  468. {
  469. console.log('pinned endpoint changed: ', userResource);
  470. if (_dataChannels && _dataChannels.length != 0)
  471. {
  472. _dataChannels.some(function (dataChannel) {
  473. if (dataChannel.readyState == 'open')
  474. {
  475. dataChannel.send(JSON.stringify({
  476. 'colibriClass': 'PinnedEndpointChangedEvent',
  477. 'pinnedEndpoint':
  478. (!userResource || userResource == null)?
  479. null : userResource
  480. }));
  481. return true;
  482. }
  483. });
  484. }
  485. }
  486. module.exports = DataChannels;
  487. },{"../../service/RTC/RTCEvents":99}],5:[function(require,module,exports){
  488. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  489. var RTCEvents = require("../../service/RTC/RTCEvents");
  490. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  491. {
  492. this.stream = stream;
  493. this.eventEmitter = eventEmitter;
  494. this.type = type;
  495. this.videoType = videoType;
  496. this.isGUMStream = true;
  497. if(isGUMStream === false)
  498. this.isGUMStream = isGUMStream;
  499. var self = this;
  500. if(type == "audio")
  501. {
  502. this.getTracks = function () {
  503. return self.stream.getAudioTracks();
  504. };
  505. }
  506. else
  507. {
  508. this.getTracks = function () {
  509. return self.stream.getVideoTracks();
  510. };
  511. }
  512. this.stream.onended = function()
  513. {
  514. self.streamEnded();
  515. };
  516. }
  517. LocalStream.prototype.streamEnded = function () {
  518. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  519. }
  520. LocalStream.prototype.getOriginalStream = function()
  521. {
  522. return this.stream;
  523. }
  524. LocalStream.prototype.isAudioStream = function () {
  525. return this.type === "audio";
  526. };
  527. LocalStream.prototype.setMute = function(mute)
  528. {
  529. if((window.location.protocol != "https:" && this.isGUMStream) ||
  530. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  531. {
  532. var tracks = this.getTracks();
  533. for (var idx = 0; idx < tracks.length; idx++) {
  534. tracks[idx].enabled = mute;
  535. }
  536. this.eventEmitter.emit(
  537. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  538. !mute);
  539. }
  540. else
  541. {
  542. if(mute === false) {
  543. APP.xmpp.removeStream(this.stream);
  544. this.stream.stop();
  545. this.eventEmitter.emit(
  546. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  547. true);
  548. }
  549. else
  550. {
  551. var self = this;
  552. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  553. (this.isAudioStream() ? ["audio"] : ["video"]),
  554. function (stream) {
  555. if(self.isAudioStream())
  556. {
  557. APP.RTC.changeLocalAudio(stream,
  558. function () {
  559. self.eventEmitter.emit(
  560. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  561. true);
  562. });
  563. }
  564. else
  565. {
  566. APP.RTC.changeLocalVideo(stream, false,
  567. function () {
  568. self.eventEmitter.emit(
  569. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  570. true);
  571. });
  572. }
  573. });
  574. }
  575. }
  576. };
  577. LocalStream.prototype.isMuted = function () {
  578. var tracks = [];
  579. if(this.type == "audio")
  580. {
  581. tracks = this.stream.getAudioTracks();
  582. }
  583. else
  584. {
  585. if(this.stream.ended)
  586. return true;
  587. tracks = this.stream.getVideoTracks();
  588. }
  589. for (var idx = 0; idx < tracks.length; idx++) {
  590. if(tracks[idx].enabled)
  591. return false;
  592. }
  593. return true;
  594. }
  595. LocalStream.prototype.getId = function () {
  596. return this.stream.getTracks()[0].id;
  597. }
  598. module.exports = LocalStream;
  599. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes.js":101}],6:[function(require,module,exports){
  600. ////These lines should be uncommented when require works in app.js
  601. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  602. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  603. /**
  604. * Creates a MediaStream object for the given data, session id and ssrc.
  605. * It is a wrapper class for the MediaStream.
  606. *
  607. * @param data the data object from which we obtain the stream,
  608. * the peerjid, etc.
  609. * @param sid the session id
  610. * @param ssrc the ssrc corresponding to this MediaStream
  611. *
  612. * @constructor
  613. */
  614. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  615. // XXX(gp) to minimize headaches in the future, we should build our
  616. // abstractions around tracks and not streams. ORTC is track based API.
  617. // Mozilla expects m-lines to represent media tracks.
  618. //
  619. // Practically, what I'm saying is that we should have a MediaTrack class
  620. // and not a MediaStream class.
  621. //
  622. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  623. // a track might have an associated RTX and FEC sources.
  624. this.sid = sid;
  625. this.stream = data.stream;
  626. this.peerjid = data.peerjid;
  627. this.videoType = data.videoType;
  628. this.ssrc = ssrc;
  629. this.type = (this.stream.getVideoTracks().length > 0)?
  630. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  631. this.muted = false;
  632. this.eventEmitter = eventEmitter;
  633. }
  634. MediaStream.prototype.getOriginalStream = function()
  635. {
  636. return this.stream;
  637. };
  638. MediaStream.prototype.setMute = function (value)
  639. {
  640. this.stream.muted = value;
  641. this.muted = value;
  642. };
  643. module.exports = MediaStream;
  644. },{"../../service/RTC/MediaStreamTypes":98,"../../service/RTC/StreamEventTypes":101}],7:[function(require,module,exports){
  645. var EventEmitter = require("events");
  646. var RTCBrowserType = require("./RTCBrowserType");
  647. var RTCUtils = require("./RTCUtils.js");
  648. var LocalStream = require("./LocalStream.js");
  649. var DataChannels = require("./DataChannels");
  650. var MediaStream = require("./MediaStream.js");
  651. var DesktopSharingEventTypes
  652. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  653. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  654. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  655. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  656. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  657. var UIEvents = require("../../service/UI/UIEvents");
  658. var eventEmitter = new EventEmitter();
  659. function getMediaStreamUsage()
  660. {
  661. var result = {
  662. audio: true,
  663. video: true
  664. };
  665. /** There are some issues with the desktop sharing
  666. * when this property is enabled.
  667. * WARNING: We must change the implementation to start video/audio if we
  668. * receive from the focus that the peer is not muted.
  669. var isSecureConnection = window.location.protocol == "https:";
  670. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  671. {
  672. result = {
  673. audio: false,
  674. video: false
  675. };
  676. }
  677. **/
  678. return result;
  679. }
  680. var RTC = {
  681. rtcUtils: null,
  682. devices: {
  683. audio: true,
  684. video: true
  685. },
  686. localStreams: [],
  687. remoteStreams: {},
  688. localAudio: null,
  689. localVideo: null,
  690. addStreamListener: function (listener, eventType) {
  691. eventEmitter.on(eventType, listener);
  692. },
  693. addListener: function (type, listener) {
  694. eventEmitter.on(type, listener);
  695. },
  696. removeStreamListener: function (listener, eventType) {
  697. if(!(eventType instanceof StreamEventTypes))
  698. throw "Illegal argument";
  699. eventEmitter.removeListener(eventType, listener);
  700. },
  701. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  702. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  703. //in firefox we have only one stream object
  704. if(this.localStreams.length == 0 ||
  705. this.localStreams[0].getOriginalStream() != stream)
  706. this.localStreams.push(localStream);
  707. if(isMuted === true)
  708. localStream.setMute(false);
  709. if(type == "audio")
  710. {
  711. this.localAudio = localStream;
  712. }
  713. else
  714. {
  715. this.localVideo = localStream;
  716. }
  717. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  718. if(change)
  719. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  720. eventEmitter.emit(eventType, localStream, isMuted);
  721. return localStream;
  722. },
  723. removeLocalStream: function (stream) {
  724. for(var i = 0; i < this.localStreams.length; i++)
  725. {
  726. if(this.localStreams[i].getOriginalStream() === stream) {
  727. delete this.localStreams[i];
  728. return;
  729. }
  730. }
  731. },
  732. createRemoteStream: function (data, sid, thessrc) {
  733. var remoteStream = new MediaStream(data, sid, thessrc,
  734. RTCBrowserType.getBrowserType(), eventEmitter);
  735. var jid = data.peerjid || APP.xmpp.myJid();
  736. if(!this.remoteStreams[jid]) {
  737. this.remoteStreams[jid] = {};
  738. }
  739. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  740. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  741. return remoteStream;
  742. },
  743. getPCConstraints: function () {
  744. return this.rtcUtils.pc_constraints;
  745. },
  746. getUserMediaWithConstraints:function(um, success_callback,
  747. failure_callback, resolution,
  748. bandwidth, fps, desktopStream)
  749. {
  750. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  751. failure_callback, resolution, bandwidth, fps, desktopStream);
  752. },
  753. attachMediaStream: function (elSelector, stream) {
  754. this.rtcUtils.attachMediaStream(elSelector, stream);
  755. },
  756. getStreamID: function (stream) {
  757. return this.rtcUtils.getStreamID(stream);
  758. },
  759. getVideoSrc: function (element) {
  760. return this.rtcUtils.getVideoSrc(element);
  761. },
  762. setVideoSrc: function (element, src) {
  763. this.rtcUtils.setVideoSrc(element, src);
  764. },
  765. getVideoElementName: function () {
  766. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  767. },
  768. dispose: function() {
  769. if (this.rtcUtils) {
  770. this.rtcUtils = null;
  771. }
  772. },
  773. stop: function () {
  774. this.dispose();
  775. },
  776. start: function () {
  777. var self = this;
  778. APP.desktopsharing.addListener(
  779. function (stream, isUsingScreenStream, callback) {
  780. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  781. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  782. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  783. DataChannels.init(event.peerconnection, eventEmitter);
  784. });
  785. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  786. DataChannels.handleSelectedEndpointEvent);
  787. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  788. DataChannels.handlePinnedEndpointEvent);
  789. // In case of IE we continue from 'onReady' callback
  790. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  791. // once it is initialized.
  792. var onReady = function () {
  793. eventEmitter.emit(RTCEvents.RTC_READY, true);
  794. self.rtcUtils.obtainAudioAndVideoPermissions(
  795. null, null, getMediaStreamUsage());
  796. };
  797. this.rtcUtils = new RTCUtils(this, onReady);
  798. // Call onReady() if Temasys plugin is not used
  799. if (!RTCBrowserType.isTemasysPluginUsed()) {
  800. onReady();
  801. }
  802. },
  803. muteRemoteVideoStream: function (jid, value) {
  804. var stream;
  805. if(this.remoteStreams[jid] &&
  806. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  807. {
  808. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  809. }
  810. if(!stream)
  811. return true;
  812. if (value != stream.muted) {
  813. stream.setMute(value);
  814. return true;
  815. }
  816. return false;
  817. },
  818. switchVideoStreams: function (new_stream) {
  819. this.localVideo.stream = new_stream;
  820. this.localStreams = [];
  821. //in firefox we have only one stream object
  822. if (this.localAudio.getOriginalStream() != new_stream)
  823. this.localStreams.push(this.localAudio);
  824. this.localStreams.push(this.localVideo);
  825. },
  826. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  827. var oldStream = this.localVideo.getOriginalStream();
  828. var type = (isUsingScreenStream? "screen" : "video");
  829. var localCallback = callback;
  830. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  831. {
  832. localCallback = function() {
  833. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  834. callback();
  835. };
  836. }
  837. // FIXME: Workaround for FF/IE/Safari
  838. if (stream && stream.videoStream) {
  839. stream = stream.videoStream;
  840. }
  841. var videoStream = this.rtcUtils.createStream(stream, true);
  842. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  843. // Stop the stream to trigger onended event for old stream
  844. oldStream.stop();
  845. this.switchVideoStreams(videoStream, oldStream);
  846. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  847. },
  848. changeLocalAudio: function (stream, callback) {
  849. var oldStream = this.localAudio.getOriginalStream();
  850. var newStream = this.rtcUtils.createStream(stream);
  851. this.localAudio = this.createLocalStream(newStream, "audio", true);
  852. // Stop the stream to trigger onended event for old stream
  853. oldStream.stop();
  854. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  855. },
  856. isVideoMuted: function (jid) {
  857. if (jid === APP.xmpp.myJid()) {
  858. var localVideo = APP.RTC.localVideo;
  859. return (!localVideo || localVideo.isMuted());
  860. }
  861. else
  862. {
  863. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  864. return null;
  865. }
  866. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  867. }
  868. },
  869. /**
  870. * Checks if video identified by given src is desktop stream.
  871. * @param videoSrc eg.
  872. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  873. * @returns {boolean}
  874. */
  875. isVideoSrcDesktop: function (jid) {
  876. if(!jid)
  877. return false;
  878. var isDesktop = false;
  879. var stream = null;
  880. if (APP.xmpp.myJid() === jid) {
  881. // local video
  882. stream = this.localVideo;
  883. } else {
  884. var peerStreams = this.remoteStreams[jid];
  885. if(!peerStreams)
  886. return false;
  887. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  888. }
  889. if(stream)
  890. isDesktop = (stream.videoType === "screen");
  891. return isDesktop;
  892. },
  893. setVideoMute: function(mute, callback, options) {
  894. if(!this.localVideo)
  895. return;
  896. if (mute == APP.RTC.localVideo.isMuted())
  897. {
  898. APP.xmpp.sendVideoInfoPresence(mute);
  899. if(callback)
  900. callback(mute);
  901. }
  902. else
  903. {
  904. APP.RTC.localVideo.setMute(!mute);
  905. APP.xmpp.setVideoMute(
  906. mute,
  907. callback,
  908. options);
  909. }
  910. },
  911. setDeviceAvailability: function (devices) {
  912. if(!devices)
  913. return;
  914. if(devices.audio === true || devices.audio === false)
  915. this.devices.audio = devices.audio;
  916. if(devices.video === true || devices.video === false)
  917. this.devices.video = devices.video;
  918. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  919. }
  920. };
  921. module.exports = RTC;
  922. },{"../../service/RTC/MediaStreamTypes":98,"../../service/RTC/RTCEvents.js":99,"../../service/RTC/StreamEventTypes.js":101,"../../service/UI/UIEvents":102,"../../service/desktopsharing/DesktopSharingEventTypes":105,"../../service/xmpp/XMPPEvents":108,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":109}],8:[function(require,module,exports){
  923. var currentBrowser;
  924. var browserVersion;
  925. var RTCBrowserType = {
  926. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  927. RTC_BROWSER_OPERA: "rtc_browser.opera",
  928. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  929. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  930. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  931. getBrowserType: function () {
  932. return currentBrowser;
  933. },
  934. isChrome: function () {
  935. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  936. },
  937. isOpera: function () {
  938. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  939. },
  940. isFirefox: function () {
  941. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  942. },
  943. isIExplorer: function () {
  944. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  945. },
  946. isSafari: function () {
  947. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  948. },
  949. isTemasysPluginUsed: function () {
  950. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  951. },
  952. getFirefoxVersion: function () {
  953. return RTCBrowserType.isFirefox() ? browserVersion : null;
  954. },
  955. getChromeVersion: function () {
  956. return RTCBrowserType.isChrome() ? browserVersion : null;
  957. },
  958. usesPlanB: function() {
  959. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  960. || RTCBrowserType.isTemasysPluginUsed();
  961. },
  962. usesUnifiedPlan: function() {
  963. return RTCBrowserType.isFirefox();
  964. }
  965. // Add version getters for other browsers when needed
  966. };
  967. // detectOpera() must be called before detectChrome() !!!
  968. // otherwise Opera wil be detected as Chrome
  969. function detectChrome() {
  970. if (navigator.webkitGetUserMedia) {
  971. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  972. var userAgent = navigator.userAgent.toLowerCase();
  973. // We can assume that user agent is chrome, because it's
  974. // enforced when 'ext' streaming method is set
  975. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  976. console.log("This appears to be Chrome, ver: " + ver);
  977. return ver;
  978. }
  979. return null;
  980. }
  981. function detectOpera() {
  982. var userAgent = navigator.userAgent;
  983. if (userAgent.match(/Opera|OPR/)) {
  984. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  985. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  986. console.info("This appears to be Opera, ver: " + version);
  987. return version;
  988. }
  989. return null;
  990. }
  991. function detectFirefox() {
  992. if (navigator.mozGetUserMedia) {
  993. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  994. var version = parseInt(
  995. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  996. console.log('This appears to be Firefox, ver: ' + version);
  997. return version;
  998. }
  999. return null;
  1000. }
  1001. function detectSafari() {
  1002. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1003. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1004. console.info("This appears to be Safari");
  1005. // FIXME detect Safari version when needed
  1006. return 1;
  1007. }
  1008. return null;
  1009. }
  1010. function detectIE() {
  1011. var version;
  1012. var ua = window.navigator.userAgent;
  1013. var msie = ua.indexOf('MSIE ');
  1014. if (msie > 0) {
  1015. // IE 10 or older => return version number
  1016. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1017. }
  1018. var trident = ua.indexOf('Trident/');
  1019. if (!version && trident > 0) {
  1020. // IE 11 => return version number
  1021. var rv = ua.indexOf('rv:');
  1022. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1023. }
  1024. var edge = ua.indexOf('Edge/');
  1025. if (!version && edge > 0) {
  1026. // IE 12 => return version number
  1027. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1028. }
  1029. if (version) {
  1030. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1031. console.info("This appears to be IExplorer, ver: " + version);
  1032. }
  1033. return version;
  1034. }
  1035. function detectBrowser() {
  1036. var version;
  1037. var detectors = [
  1038. detectOpera,
  1039. detectChrome,
  1040. detectFirefox,
  1041. detectIE,
  1042. detectSafari
  1043. ];
  1044. // Try all browser detectors
  1045. for (var i = 0; i < detectors.length; i++) {
  1046. version = detectors[i]();
  1047. if (version)
  1048. return version;
  1049. }
  1050. console.error("Failed to detect browser type");
  1051. return undefined;
  1052. }
  1053. browserVersion = detectBrowser();
  1054. module.exports = RTCBrowserType;
  1055. },{}],9:[function(require,module,exports){
  1056. var RTCBrowserType = require("./RTCBrowserType");
  1057. var Resolutions = require("../../service/RTC/Resolutions");
  1058. var AdapterJS = require("./adapter.screenshare");
  1059. var SDPUtil = require("../xmpp/SDPUtil");
  1060. var currentResolution = null;
  1061. function getPreviousResolution(resolution) {
  1062. if(!Resolutions[resolution])
  1063. return null;
  1064. var order = Resolutions[resolution].order;
  1065. var res = null;
  1066. var resName = null;
  1067. for(var i in Resolutions)
  1068. {
  1069. var tmp = Resolutions[i];
  1070. if(res == null || (res.order < tmp.order && tmp.order < order))
  1071. {
  1072. resName = i;
  1073. res = tmp;
  1074. }
  1075. }
  1076. return resName;
  1077. }
  1078. function setResolutionConstraints(constraints, resolution, isAndroid)
  1079. {
  1080. if (resolution && !constraints.video || isAndroid) {
  1081. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1082. }
  1083. if(Resolutions[resolution])
  1084. {
  1085. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1086. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1087. }
  1088. else
  1089. {
  1090. if (isAndroid) {
  1091. constraints.video.mandatory.minWidth = 320;
  1092. constraints.video.mandatory.minHeight = 240;
  1093. constraints.video.mandatory.maxFrameRate = 15;
  1094. }
  1095. }
  1096. if (constraints.video.mandatory.minWidth)
  1097. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1098. if (constraints.video.mandatory.minHeight)
  1099. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1100. }
  1101. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1102. {
  1103. var constraints = {audio: false, video: false};
  1104. if (um.indexOf('video') >= 0) {
  1105. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1106. }
  1107. if (um.indexOf('audio') >= 0) {
  1108. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1109. }
  1110. if (um.indexOf('screen') >= 0) {
  1111. if (RTCBrowserType.isChrome()) {
  1112. constraints.video = {
  1113. mandatory: {
  1114. chromeMediaSource: "screen",
  1115. googLeakyBucket: true,
  1116. maxWidth: window.screen.width,
  1117. maxHeight: window.screen.height,
  1118. maxFrameRate: 3
  1119. },
  1120. optional: []
  1121. };
  1122. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1123. constraints.video = {
  1124. optional: [
  1125. {
  1126. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1127. }
  1128. ]
  1129. };
  1130. } else {
  1131. console.error(
  1132. "'screen' WebRTC media source is supported only in Chrome" +
  1133. " and with Temasys plugin");
  1134. }
  1135. }
  1136. if (um.indexOf('desktop') >= 0) {
  1137. constraints.video = {
  1138. mandatory: {
  1139. chromeMediaSource: "desktop",
  1140. chromeMediaSourceId: desktopStream,
  1141. googLeakyBucket: true,
  1142. maxWidth: window.screen.width,
  1143. maxHeight: window.screen.height,
  1144. maxFrameRate: 3
  1145. },
  1146. optional: []
  1147. };
  1148. }
  1149. if (constraints.audio) {
  1150. // if it is good enough for hangouts...
  1151. constraints.audio.optional.push(
  1152. {googEchoCancellation: true},
  1153. {googAutoGainControl: true},
  1154. {googNoiseSupression: true},
  1155. {googHighpassFilter: true},
  1156. {googNoisesuppression2: true},
  1157. {googEchoCancellation2: true},
  1158. {googAutoGainControl2: true}
  1159. );
  1160. }
  1161. if (constraints.video) {
  1162. constraints.video.optional.push(
  1163. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1164. );
  1165. if (um.indexOf('video') >= 0) {
  1166. constraints.video.optional.push(
  1167. {googLeakyBucket: true}
  1168. );
  1169. }
  1170. }
  1171. if (um.indexOf('video') >= 0) {
  1172. setResolutionConstraints(constraints, resolution, isAndroid);
  1173. }
  1174. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1175. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1176. constraints.video.optional.push({bandwidth: bandwidth});
  1177. }
  1178. if (fps) { // for some cameras it might be necessary to request 30fps
  1179. // so they choose 30fps mjpg over 10fps yuy2
  1180. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1181. constraints.video.mandatory.minFrameRate = fps;
  1182. }
  1183. return constraints;
  1184. }
  1185. function RTCUtils(RTCService, onTemasysPluginReady)
  1186. {
  1187. var self = this;
  1188. this.service = RTCService;
  1189. if (RTCBrowserType.isFirefox()) {
  1190. var FFversion = RTCBrowserType.getFirefoxVersion();
  1191. if (FFversion >= 40 && config.useBundle && config.useRtcpMux) {
  1192. this.peerconnection = mozRTCPeerConnection;
  1193. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1194. this.pc_constraints = {};
  1195. this.attachMediaStream = function (element, stream) {
  1196. // srcObject is being standardized and FF will eventually
  1197. // support that unprefixed. FF also supports the
  1198. // "element.src = URL.createObjectURL(...)" combo, but that
  1199. // will be deprecated in favour of srcObject.
  1200. //
  1201. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1202. // https://github.com/webrtc/samples/issues/302
  1203. if(!element[0])
  1204. return;
  1205. element[0].mozSrcObject = stream;
  1206. element[0].play();
  1207. };
  1208. this.getStreamID = function (stream) {
  1209. var id = stream.id;
  1210. if (!id) {
  1211. var tracks = stream.getVideoTracks();
  1212. if (!tracks || tracks.length === 0)
  1213. {
  1214. tracks = stream.getAudioTracks();
  1215. }
  1216. id = tracks[0].id;
  1217. }
  1218. return SDPUtil.filter_special_chars(id);
  1219. };
  1220. this.getVideoSrc = function (element) {
  1221. if(!element)
  1222. return null;
  1223. return element.mozSrcObject;
  1224. };
  1225. this.setVideoSrc = function (element, src) {
  1226. if(element)
  1227. element.mozSrcObject = src;
  1228. };
  1229. RTCSessionDescription = mozRTCSessionDescription;
  1230. RTCIceCandidate = mozRTCIceCandidate;
  1231. } else {
  1232. console.error(
  1233. "Firefox requirements not met, ver: " + FFversion +
  1234. ", bundle: " + config.useBundle +
  1235. ", rtcp-mux: " + config.useRtcpMux);
  1236. window.location.href = 'unsupported_browser.html';
  1237. return;
  1238. }
  1239. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1240. this.peerconnection = webkitRTCPeerConnection;
  1241. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1242. this.attachMediaStream = function (element, stream) {
  1243. element.attr('src', webkitURL.createObjectURL(stream));
  1244. };
  1245. this.getStreamID = function (stream) {
  1246. // streams from FF endpoints have the characters '{' and '}'
  1247. // that make jQuery choke.
  1248. return SDPUtil.filter_special_chars(stream.id);
  1249. };
  1250. this.getVideoSrc = function (element) {
  1251. if(!element)
  1252. return null;
  1253. return element.getAttribute("src");
  1254. };
  1255. this.setVideoSrc = function (element, src) {
  1256. if(element)
  1257. element.setAttribute("src", src);
  1258. };
  1259. // DTLS should now be enabled by default but..
  1260. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1261. if (navigator.userAgent.indexOf('Android') != -1) {
  1262. this.pc_constraints = {}; // disable DTLS on Android
  1263. }
  1264. if (!webkitMediaStream.prototype.getVideoTracks) {
  1265. webkitMediaStream.prototype.getVideoTracks = function () {
  1266. return this.videoTracks;
  1267. };
  1268. }
  1269. if (!webkitMediaStream.prototype.getAudioTracks) {
  1270. webkitMediaStream.prototype.getAudioTracks = function () {
  1271. return this.audioTracks;
  1272. };
  1273. }
  1274. }
  1275. // Detect IE/Safari
  1276. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1277. AdapterJS.WebRTCPlugin.setLogLevel(
  1278. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1279. AdapterJS.webRTCReady(function (isPlugin) {
  1280. self.peerconnection = RTCPeerConnection;
  1281. self.getUserMedia = getUserMedia;
  1282. self.attachMediaStream = function (elSel, stream) {
  1283. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1284. return;
  1285. }
  1286. attachMediaStream(elSel[0], stream);
  1287. };
  1288. self.getStreamID = function (stream) {
  1289. var id = SDPUtil.filter_special_chars(stream.label);
  1290. return id;
  1291. };
  1292. self.getVideoSrc = function (element) {
  1293. if (!element) {
  1294. console.warn("Attempt to get video SRC of null element");
  1295. return null;
  1296. }
  1297. var src = null;
  1298. var children = element.children;
  1299. for (var i = 0; i !== children.length; ++i) {
  1300. if (children[i].name === 'streamId') {
  1301. return children[i].value;
  1302. }
  1303. }
  1304. //console.info(element.id + " SRC: " + src);
  1305. return null;
  1306. };
  1307. self.setVideoSrc = function (element, src) {
  1308. //console.info("Set video src: ", element, src);
  1309. if (!src) {
  1310. console.warn("Not attaching video stream, 'src' is null");
  1311. return;
  1312. }
  1313. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1314. var stream = AdapterJS.WebRTCPlugin.plugin
  1315. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1316. attachMediaStream(element, stream);
  1317. };
  1318. onTemasysPluginReady(isPlugin);
  1319. });
  1320. } else {
  1321. try {
  1322. console.log('Browser does not appear to be WebRTC-capable');
  1323. } catch (e) { }
  1324. window.location.href = 'unsupported_browser.html';
  1325. }
  1326. }
  1327. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1328. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1329. desktopStream)
  1330. {
  1331. currentResolution = resolution;
  1332. // Check if we are running on Android device
  1333. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1334. var constraints = getConstraints(
  1335. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1336. console.info("Get media constraints", constraints);
  1337. var self = this;
  1338. try {
  1339. this.getUserMedia(constraints,
  1340. function (stream) {
  1341. console.log('onUserMediaSuccess');
  1342. self.setAvailableDevices(um, true);
  1343. success_callback(stream);
  1344. },
  1345. function (error) {
  1346. self.setAvailableDevices(um, false);
  1347. console.warn('Failed to get access to local media. Error ',
  1348. error, constraints);
  1349. if (failure_callback) {
  1350. failure_callback(error);
  1351. }
  1352. });
  1353. } catch (e) {
  1354. console.error('GUM failed: ', e);
  1355. if(failure_callback) {
  1356. failure_callback(e);
  1357. }
  1358. }
  1359. };
  1360. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1361. var devices = {};
  1362. if(um.indexOf("video") != -1)
  1363. {
  1364. devices.video = available;
  1365. }
  1366. if(um.indexOf("audio") != -1)
  1367. {
  1368. devices.audio = available;
  1369. }
  1370. this.service.setDeviceAvailability(devices);
  1371. }
  1372. /**
  1373. * We ask for audio and video combined stream in order to get permissions and
  1374. * not to ask twice.
  1375. */
  1376. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1377. function(devices, callback, usageOptions)
  1378. {
  1379. var self = this;
  1380. // Get AV
  1381. var successCallback = function (stream) {
  1382. if(callback)
  1383. callback(stream, usageOptions);
  1384. else
  1385. self.successCallback(stream, usageOptions);
  1386. };
  1387. if(!devices)
  1388. devices = ['audio', 'video'];
  1389. var newDevices = [];
  1390. if(usageOptions)
  1391. for(var i = 0; i < devices.length; i++)
  1392. {
  1393. var device = devices[i];
  1394. if(usageOptions[device] === true)
  1395. newDevices.push(device);
  1396. }
  1397. else
  1398. newDevices = devices;
  1399. if(newDevices.length === 0)
  1400. {
  1401. successCallback();
  1402. return;
  1403. }
  1404. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1405. // With FF/IE we can't split the stream into audio and video because FF
  1406. // doesn't support media stream constructors. So, we need to get the
  1407. // audio stream separately from the video stream using two distinct GUM
  1408. // calls. Not very user friendly :-( but we don't have many other
  1409. // options neither.
  1410. //
  1411. // Note that we pack those 2 streams in a single object and pass it to
  1412. // the successCallback method.
  1413. var obtainVideo = function (audioStream) {
  1414. self.getUserMediaWithConstraints(
  1415. ['video'],
  1416. function (videoStream) {
  1417. return successCallback({
  1418. audioStream: audioStream,
  1419. videoStream: videoStream
  1420. });
  1421. },
  1422. function (error) {
  1423. console.error(
  1424. 'failed to obtain video stream - stop', error);
  1425. self.errorCallback(error);
  1426. },
  1427. config.resolution || '360');
  1428. };
  1429. var obtainAudio = function () {
  1430. self.getUserMediaWithConstraints(
  1431. ['audio'],
  1432. function (audioStream) {
  1433. if (newDevices.indexOf('video') !== -1)
  1434. obtainVideo(audioStream);
  1435. },
  1436. function (error) {
  1437. console.error(
  1438. 'failed to obtain audio stream - stop', error);
  1439. self.errorCallback(error);
  1440. }
  1441. );
  1442. };
  1443. if (newDevices.indexOf('audio') !== -1) {
  1444. obtainAudio();
  1445. } else {
  1446. obtainVideo(null);
  1447. }
  1448. } else {
  1449. this.getUserMediaWithConstraints(
  1450. newDevices,
  1451. function (stream) {
  1452. successCallback(stream);
  1453. },
  1454. function (error) {
  1455. self.errorCallback(error);
  1456. },
  1457. config.resolution || '360');
  1458. }
  1459. };
  1460. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1461. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1462. // it's an object with two properties: audioStream, videoStream.
  1463. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1464. console.log('got', stream, stream.getAudioTracks().length,
  1465. stream.getVideoTracks().length);
  1466. this.handleLocalStream(stream, usageOptions);
  1467. };
  1468. RTCUtils.prototype.errorCallback = function (error) {
  1469. var self = this;
  1470. console.error('failed to obtain audio/video stream - trying audio only', error);
  1471. var resolution = getPreviousResolution(currentResolution);
  1472. if(typeof error == "object" && error.constraintName && error.name
  1473. && (error.name == "ConstraintNotSatisfiedError" ||
  1474. error.name == "OverconstrainedError") &&
  1475. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1476. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1477. && resolution != null)
  1478. {
  1479. self.getUserMediaWithConstraints(['audio', 'video'],
  1480. function (stream) {
  1481. return self.successCallback(stream);
  1482. }, function (error) {
  1483. return self.errorCallback(error);
  1484. }, resolution);
  1485. }
  1486. else
  1487. {
  1488. self.getUserMediaWithConstraints(
  1489. ['audio'],
  1490. function (stream) {
  1491. return self.successCallback(stream);
  1492. },
  1493. function (error) {
  1494. console.error('failed to obtain audio/video stream - stop',
  1495. error);
  1496. return self.successCallback(null);
  1497. }
  1498. );
  1499. }
  1500. }
  1501. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1502. {
  1503. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1504. // an object with two properties: audioStream, videoStream.
  1505. var audioStream, videoStream;
  1506. if(window.webkitMediaStream)
  1507. {
  1508. audioStream = new webkitMediaStream();
  1509. videoStream = new webkitMediaStream();
  1510. if(stream) {
  1511. var audioTracks = stream.getAudioTracks();
  1512. for (var i = 0; i < audioTracks.length; i++) {
  1513. audioStream.addTrack(audioTracks[i]);
  1514. }
  1515. var videoTracks = stream.getVideoTracks();
  1516. for (i = 0; i < videoTracks.length; i++) {
  1517. videoStream.addTrack(videoTracks[i]);
  1518. }
  1519. }
  1520. }
  1521. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1522. { // Firefox and Temasys plugin
  1523. if (stream && stream.audioStream)
  1524. audioStream = stream.audioStream;
  1525. else
  1526. audioStream = new DummyMediaStream("dummyAudio");
  1527. if (stream && stream.videoStream)
  1528. videoStream = stream.videoStream;
  1529. else
  1530. videoStream = new DummyMediaStream("dummyVideo");
  1531. }
  1532. var audioMuted = (usageOptions && usageOptions.audio === false),
  1533. videoMuted = (usageOptions && usageOptions.video === false);
  1534. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1535. videoGUM = (!usageOptions || usageOptions.video !== false);
  1536. this.service.createLocalStream(audioStream, "audio", null, null,
  1537. audioMuted, audioGUM);
  1538. this.service.createLocalStream(videoStream, "video", null, null,
  1539. videoMuted, videoGUM);
  1540. };
  1541. function DummyMediaStream(id) {
  1542. this.id = id;
  1543. this.label = id;
  1544. this.stop = function() { };
  1545. this.getAudioTracks = function() { return []; }
  1546. this.getVideoTracks = function() { return []; }
  1547. }
  1548. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1549. var newStream = null;
  1550. if (window.webkitMediaStream) {
  1551. newStream = new webkitMediaStream();
  1552. if (newStream) {
  1553. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1554. for (i = 0; i < tracks.length; i++) {
  1555. newStream.addTrack(tracks[i]);
  1556. }
  1557. }
  1558. }
  1559. else {
  1560. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1561. if (stream) {
  1562. newStream = stream;
  1563. } else {
  1564. newStream = new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1565. }
  1566. }
  1567. return newStream;
  1568. };
  1569. module.exports = RTCUtils;
  1570. },{"../../service/RTC/Resolutions":100,"../xmpp/SDPUtil":56,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1571. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1572. // Adapter's interface.
  1573. var AdapterJS = AdapterJS || {};
  1574. // Browserify compatibility
  1575. if(typeof exports !== 'undefined') {
  1576. module.exports = AdapterJS;
  1577. }
  1578. AdapterJS.options = AdapterJS.options || {};
  1579. // uncomment to get virtual webcams
  1580. // AdapterJS.options.getAllCams = true;
  1581. // uncomment to prevent the install prompt when the plugin in not yet installed
  1582. // AdapterJS.options.hidePluginInstallPrompt = true;
  1583. // AdapterJS version
  1584. AdapterJS.VERSION = '0.11.0';
  1585. // This function will be called when the WebRTC API is ready to be used
  1586. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1587. // the plugin
  1588. // You may Override this function to synchronise the start of your application
  1589. // with the WebRTC API being ready.
  1590. // If you decide not to override use this synchronisation, it may result in
  1591. // an extensive CPU usage on the plugin start (once per tab loaded)
  1592. // Params:
  1593. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1594. //
  1595. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1596. // The WebRTC API is ready.
  1597. // Override me and do whatever you want here
  1598. };
  1599. // Sets a callback function to be called when the WebRTC interface is ready.
  1600. // The first argument is the function to callback.\
  1601. // Throws an error if the first argument is not a function
  1602. AdapterJS.webRTCReady = function (callback) {
  1603. if (typeof callback !== 'function') {
  1604. throw new Error('Callback provided is not a function');
  1605. }
  1606. if (true === AdapterJS.onwebrtcreadyDone) {
  1607. // All WebRTC interfaces are ready, just call the callback
  1608. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1609. } else {
  1610. // will be triggered automatically when your browser/plugin is ready.
  1611. AdapterJS.onwebrtcready = callback;
  1612. }
  1613. };
  1614. // Plugin namespace
  1615. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1616. // The object to store plugin information
  1617. AdapterJS.WebRTCPlugin.pluginInfo = {
  1618. prefix : 'Tem',
  1619. plugName : 'TemWebRTCPlugin',
  1620. pluginId : 'plugin0',
  1621. type : 'application/x-temwebrtcplugin',
  1622. onload : '__TemWebRTCReady0',
  1623. portalLink : 'http://skylink.io/plugin/',
  1624. downloadLink : null, //set below
  1625. companyName: 'Temasys'
  1626. };
  1627. if(!!navigator.platform.match(/^Mac/i)) {
  1628. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1629. }
  1630. else if(!!navigator.platform.match(/^Win/i)) {
  1631. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1632. }
  1633. // Unique identifier of each opened page
  1634. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1635. // Use this whenever you want to call the plugin.
  1636. AdapterJS.WebRTCPlugin.plugin = null;
  1637. // Set log level for the plugin once it is ready.
  1638. // The different values are
  1639. // This is an asynchronous function that will run when the plugin is ready
  1640. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1641. // Defines webrtc's JS interface according to the plugin's implementation.
  1642. // Define plugin Browsers as WebRTC Interface.
  1643. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1644. // This function detects whether or not a plugin is installed.
  1645. // Checks if Not IE (firefox, for example), else if it's IE,
  1646. // we're running IE and do something. If not it is not supported.
  1647. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1648. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1649. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1650. // Inject the HTML DOM object element into the page.
  1651. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1652. // States of readiness that the plugin goes through when
  1653. // being injected and stated
  1654. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1655. NONE : 0, // no plugin use
  1656. INITIALIZING : 1, // Detected need for plugin
  1657. INJECTING : 2, // Injecting plugin
  1658. INJECTED: 3, // Plugin element injected but not usable yet
  1659. READY: 4 // Plugin ready to be used
  1660. };
  1661. // Current state of the plugin. You cannot use the plugin before this is
  1662. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1663. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1664. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1665. // Used to make sure AdapterJS.onwebrtcready is only called once
  1666. AdapterJS.onwebrtcreadyDone = false;
  1667. // Log levels for the plugin.
  1668. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1669. /*
  1670. Log outputs are prefixed in some cases.
  1671. INFO: Information reported by the plugin.
  1672. ERROR: Errors originating from within the plugin.
  1673. WEBRTC: Error originating from within the libWebRTC library
  1674. */
  1675. // From the least verbose to the most verbose
  1676. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1677. NONE : 'NONE',
  1678. ERROR : 'ERROR',
  1679. WARNING : 'WARNING',
  1680. INFO: 'INFO',
  1681. VERBOSE: 'VERBOSE',
  1682. SENSITIVE: 'SENSITIVE'
  1683. };
  1684. // Does a waiting check before proceeding to load the plugin.
  1685. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1686. // This methid will use an interval to wait for the plugin to be ready.
  1687. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1688. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1689. // This function will be called when plugin is ready. It sends necessary
  1690. // details to the plugin.
  1691. // The function will wait for the document to be ready and the set the
  1692. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1693. // indicating that it can start being requested.
  1694. // This function is not in the IE/Safari condition brackets so that
  1695. // TemPluginLoaded function might be called on Chrome/Firefox.
  1696. // This function is the only private function that is not encapsulated to
  1697. // allow the plugin method to be called.
  1698. __TemWebRTCReady0 = function () {
  1699. if (document.readyState === 'complete') {
  1700. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1701. AdapterJS.maybeThroughWebRTCReady();
  1702. } else {
  1703. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1704. if (document.readyState === 'complete') {
  1705. // TODO: update comments, we wait for the document to be ready
  1706. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1707. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1708. AdapterJS.maybeThroughWebRTCReady();
  1709. }
  1710. }, 100);
  1711. }
  1712. };
  1713. AdapterJS.maybeThroughWebRTCReady = function() {
  1714. if (!AdapterJS.onwebrtcreadyDone) {
  1715. AdapterJS.onwebrtcreadyDone = true;
  1716. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1717. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1718. }
  1719. }
  1720. };
  1721. // Text namespace
  1722. AdapterJS.TEXT = {
  1723. PLUGIN: {
  1724. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1725. 'to work on this browser.',
  1726. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1727. BUTTON: 'Install Now'
  1728. },
  1729. REFRESH: {
  1730. REQUIRE_REFRESH: 'Please refresh page',
  1731. BUTTON: 'Refresh Page'
  1732. }
  1733. };
  1734. // The result of ice connection states.
  1735. // - starting: Ice connection is starting.
  1736. // - checking: Ice connection is checking.
  1737. // - connected Ice connection is connected.
  1738. // - completed Ice connection is connected.
  1739. // - done Ice connection has been completed.
  1740. // - disconnected Ice connection has been disconnected.
  1741. // - failed Ice connection has failed.
  1742. // - closed Ice connection is closed.
  1743. AdapterJS._iceConnectionStates = {
  1744. starting : 'starting',
  1745. checking : 'checking',
  1746. connected : 'connected',
  1747. completed : 'connected',
  1748. done : 'completed',
  1749. disconnected : 'disconnected',
  1750. failed : 'failed',
  1751. closed : 'closed'
  1752. };
  1753. //The IceConnection states that has been fired for each peer.
  1754. AdapterJS._iceConnectionFiredStates = [];
  1755. // Check if WebRTC Interface is defined.
  1756. AdapterJS.isDefined = null;
  1757. // This function helps to retrieve the webrtc detected browser information.
  1758. // This sets:
  1759. // - webrtcDetectedBrowser: The browser agent name.
  1760. // - webrtcDetectedVersion: The browser version.
  1761. // - webrtcDetectedType: The types of webRTC support.
  1762. // - 'moz': Mozilla implementation of webRTC.
  1763. // - 'webkit': WebKit implementation of webRTC.
  1764. // - 'plugin': Using the plugin implementation.
  1765. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1766. var hasMatch, checkMatch = navigator.userAgent.match(
  1767. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1768. if (/trident/i.test(checkMatch[1])) {
  1769. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1770. webrtcDetectedBrowser = 'IE';
  1771. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1772. } else if (checkMatch[1] === 'Chrome') {
  1773. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1774. if (hasMatch !== null) {
  1775. webrtcDetectedBrowser = 'opera';
  1776. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1777. }
  1778. }
  1779. if (navigator.userAgent.indexOf('Safari')) {
  1780. if (typeof InstallTrigger !== 'undefined') {
  1781. webrtcDetectedBrowser = 'firefox';
  1782. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1783. webrtcDetectedBrowser = 'IE';
  1784. } else if (
  1785. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1786. webrtcDetectedBrowser = 'safari';
  1787. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1788. webrtcDetectedBrowser = 'opera';
  1789. } else if (!!window.chrome) {
  1790. webrtcDetectedBrowser = 'chrome';
  1791. }
  1792. }
  1793. if (!webrtcDetectedBrowser) {
  1794. webrtcDetectedVersion = checkMatch[1];
  1795. }
  1796. if (!webrtcDetectedVersion) {
  1797. try {
  1798. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1799. [navigator.appName, navigator.appVersion, '-?'];
  1800. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1801. checkMatch.splice(1, 1, hasMatch[1]);
  1802. }
  1803. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1804. } catch (error) { }
  1805. }
  1806. };
  1807. // To fix configuration as some browsers does not support
  1808. // the 'urls' attribute.
  1809. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1810. if (pcConfig === null) {
  1811. return;
  1812. }
  1813. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1814. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1815. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1816. delete pcConfig.iceServers[i].urls;
  1817. }
  1818. }
  1819. };
  1820. AdapterJS.addEvent = function(elem, evnt, func) {
  1821. if (elem.addEventListener) { // W3C DOM
  1822. elem.addEventListener(evnt, func, false);
  1823. } else if (elem.attachEvent) {// OLD IE DOM
  1824. elem.attachEvent('on'+evnt, func);
  1825. } else { // No much to do
  1826. elem[evnt] = func;
  1827. }
  1828. };
  1829. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1830. // only inject once the page is ready
  1831. if (document.readyState !== 'complete') {
  1832. return;
  1833. }
  1834. var w = window;
  1835. var i = document.createElement('iframe');
  1836. i.style.position = 'fixed';
  1837. i.style.top = '-41px';
  1838. i.style.left = 0;
  1839. i.style.right = 0;
  1840. i.style.width = '100%';
  1841. i.style.height = '40px';
  1842. i.style.backgroundColor = '#ffffe1';
  1843. i.style.border = 'none';
  1844. i.style.borderBottom = '1px solid #888888';
  1845. i.style.zIndex = '9999999';
  1846. if(typeof i.style.webkitTransition === 'string') {
  1847. i.style.webkitTransition = 'all .5s ease-out';
  1848. } else if(typeof i.style.transition === 'string') {
  1849. i.style.transition = 'all .5s ease-out';
  1850. }
  1851. document.body.appendChild(i);
  1852. c = (i.contentWindow) ? i.contentWindow :
  1853. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1854. c.document.open();
  1855. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1856. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1857. 'middle; cursor: default;">' + text + '</span>');
  1858. if(buttonText && buttonLink) {
  1859. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1860. c.document.close();
  1861. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1862. if (!!displayRefreshBar) {
  1863. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1864. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1865. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1866. }
  1867. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1868. e.preventDefault();
  1869. try {
  1870. event.cancelBubble = true;
  1871. } catch(error) { }
  1872. });
  1873. }
  1874. else {
  1875. c.document.close();
  1876. }
  1877. AdapterJS.addEvent(c.document, 'click', function() {
  1878. w.document.body.removeChild(i);
  1879. });
  1880. setTimeout(function() {
  1881. if(typeof i.style.webkitTransform === 'string') {
  1882. i.style.webkitTransform = 'translateY(40px)';
  1883. } else if(typeof i.style.transform === 'string') {
  1884. i.style.transform = 'translateY(40px)';
  1885. } else {
  1886. i.style.top = '0px';
  1887. }
  1888. }, 300);
  1889. };
  1890. // -----------------------------------------------------------
  1891. // Detected webrtc implementation. Types are:
  1892. // - 'moz': Mozilla implementation of webRTC.
  1893. // - 'webkit': WebKit implementation of webRTC.
  1894. // - 'plugin': Using the plugin implementation.
  1895. webrtcDetectedType = null;
  1896. // Detected webrtc datachannel support. Types are:
  1897. // - 'SCTP': SCTP datachannel support.
  1898. // - 'RTP': RTP datachannel support.
  1899. webrtcDetectedDCSupport = null;
  1900. // Set the settings for creating DataChannels, MediaStream for
  1901. // Cross-browser compability.
  1902. // - This is only for SCTP based support browsers.
  1903. // the 'urls' attribute.
  1904. checkMediaDataChannelSettings =
  1905. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1906. if (typeof callback !== 'function') {
  1907. return;
  1908. }
  1909. var beOfferer = true;
  1910. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1911. // Nightly version does not require MozDontOfferDataChannel for interop
  1912. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1913. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1914. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1915. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1916. // Resends an updated version of constraints for MozDataChannel to work
  1917. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1918. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1919. try {
  1920. delete constraints.mandatory.MozDontOfferDataChannel;
  1921. } catch (error) {
  1922. console.error('Failed deleting MozDontOfferDataChannel');
  1923. console.error(error);
  1924. }
  1925. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1926. constraints.mandatory.MozDontOfferDataChannel = true;
  1927. }
  1928. if (!isLocalFirefox) {
  1929. // temporary measure to remove Moz* constraints in non Firefox browsers
  1930. for (var prop in constraints.mandatory) {
  1931. if (constraints.mandatory.hasOwnProperty(prop)) {
  1932. if (prop.indexOf('Moz') !== -1) {
  1933. delete constraints.mandatory[prop];
  1934. }
  1935. }
  1936. }
  1937. }
  1938. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1939. // interopability of the media stream
  1940. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1941. beOfferer = false;
  1942. }
  1943. callback(beOfferer, constraints);
  1944. };
  1945. // Handles the differences for all browsers ice connection state output.
  1946. // - Tested outcomes are:
  1947. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1948. // - Chrome (answerer) : 'checking' > 'connected'
  1949. // - Firefox (offerer) : 'checking' > 'connected'
  1950. // - Firefox (answerer): 'checking' > 'connected'
  1951. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1952. if (typeof callback !== 'function') {
  1953. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1954. return;
  1955. }
  1956. peerId = (peerId) ? peerId : 'peer';
  1957. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1958. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1959. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1960. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1961. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1962. }
  1963. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1964. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1965. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1966. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1967. setTimeout(function () {
  1968. AdapterJS._iceConnectionFiredStates[peerId]
  1969. .push(AdapterJS._iceConnectionStates.done);
  1970. callback(AdapterJS._iceConnectionStates.done);
  1971. }, 1000);
  1972. }
  1973. callback(iceConnectionState);
  1974. }
  1975. return;
  1976. };
  1977. // Firefox:
  1978. // - Creates iceServer from the url for Firefox.
  1979. // - Create iceServer with stun url.
  1980. // - Create iceServer with turn url.
  1981. // - Ignore the transport parameter from TURN url for FF version <=27.
  1982. // - Return null for createIceServer if transport=tcp.
  1983. // - FF 27 and above supports transport parameters in TURN url,
  1984. // - So passing in the full url to create iceServer.
  1985. // Chrome:
  1986. // - Creates iceServer from the url for Chrome M33 and earlier.
  1987. // - Create iceServer with stun url.
  1988. // - Chrome M28 & above uses below TURN format.
  1989. // Plugin:
  1990. // - Creates Ice Server for Plugin Browsers
  1991. // - If Stun - Create iceServer with stun url.
  1992. // - Else - Create iceServer with turn url
  1993. // - This is a WebRTC Function
  1994. createIceServer = null;
  1995. // Firefox:
  1996. // - Creates IceServers for Firefox
  1997. // - Use .url for FireFox.
  1998. // - Multiple Urls support
  1999. // Chrome:
  2000. // - Creates iceServers from the urls for Chrome M34 and above.
  2001. // - .urls is supported since Chrome M34.
  2002. // - Multiple Urls support
  2003. // Plugin:
  2004. // - Creates Ice Servers for Plugin Browsers
  2005. // - Multiple Urls support
  2006. // - This is a WebRTC Function
  2007. createIceServers = null;
  2008. //------------------------------------------------------------
  2009. //The RTCPeerConnection object.
  2010. RTCPeerConnection = null;
  2011. // Creates RTCSessionDescription object for Plugin Browsers
  2012. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2013. RTCSessionDescription : null;
  2014. // Creates RTCIceCandidate object for Plugin Browsers
  2015. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2016. RTCIceCandidate : null;
  2017. // Get UserMedia (only difference is the prefix).
  2018. // Code from Adam Barth.
  2019. getUserMedia = null;
  2020. // Attach a media stream to an element.
  2021. attachMediaStream = null;
  2022. // Re-attach a media stream to an element.
  2023. reattachMediaStream = null;
  2024. // Detected browser agent name. Types are:
  2025. // - 'firefox': Firefox browser.
  2026. // - 'chrome': Chrome browser.
  2027. // - 'opera': Opera browser.
  2028. // - 'safari': Safari browser.
  2029. // - 'IE' - Internet Explorer browser.
  2030. webrtcDetectedBrowser = null;
  2031. // Detected browser version.
  2032. webrtcDetectedVersion = null;
  2033. // Check for browser types and react accordingly
  2034. if (navigator.mozGetUserMedia) {
  2035. webrtcDetectedBrowser = 'firefox';
  2036. webrtcDetectedVersion = parseInt(navigator
  2037. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2038. webrtcDetectedType = 'moz';
  2039. webrtcDetectedDCSupport = 'SCTP';
  2040. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2041. AdapterJS.maybeFixConfiguration(pcConfig);
  2042. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2043. };
  2044. // The RTCSessionDescription object.
  2045. RTCSessionDescription = mozRTCSessionDescription;
  2046. window.RTCSessionDescription = RTCSessionDescription;
  2047. // The RTCIceCandidate object.
  2048. RTCIceCandidate = mozRTCIceCandidate;
  2049. window.RTCIceCandidate = RTCIceCandidate;
  2050. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2051. navigator.getUserMedia = window.getUserMedia;
  2052. // Shim for MediaStreamTrack.getSources.
  2053. MediaStreamTrack.getSources = function(successCb) {
  2054. setTimeout(function() {
  2055. var infos = [
  2056. { kind: 'audio', id: 'default', label:'', facing:'' },
  2057. { kind: 'video', id: 'default', label:'', facing:'' }
  2058. ];
  2059. successCb(infos);
  2060. }, 0);
  2061. };
  2062. createIceServer = function (url, username, password) {
  2063. var iceServer = null;
  2064. var url_parts = url.split(':');
  2065. if (url_parts[0].indexOf('stun') === 0) {
  2066. iceServer = { url : url };
  2067. } else if (url_parts[0].indexOf('turn') === 0) {
  2068. if (webrtcDetectedVersion < 27) {
  2069. var turn_url_parts = url.split('?');
  2070. if (turn_url_parts.length === 1 ||
  2071. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2072. iceServer = {
  2073. url : turn_url_parts[0],
  2074. credential : password,
  2075. username : username
  2076. };
  2077. }
  2078. } else {
  2079. iceServer = {
  2080. url : url,
  2081. credential : password,
  2082. username : username
  2083. };
  2084. }
  2085. }
  2086. return iceServer;
  2087. };
  2088. createIceServers = function (urls, username, password) {
  2089. var iceServers = [];
  2090. for (i = 0; i < urls.length; i++) {
  2091. var iceServer = createIceServer(urls[i], username, password);
  2092. if (iceServer !== null) {
  2093. iceServers.push(iceServer);
  2094. }
  2095. }
  2096. return iceServers;
  2097. };
  2098. attachMediaStream = function (element, stream) {
  2099. element.mozSrcObject = stream;
  2100. if (stream !== null)
  2101. element.play();
  2102. return element;
  2103. };
  2104. reattachMediaStream = function (to, from) {
  2105. to.mozSrcObject = from.mozSrcObject;
  2106. to.play();
  2107. return to;
  2108. };
  2109. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2110. if (!callback) {
  2111. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2112. ': 1 argument required, but only 0 present.');
  2113. }
  2114. return callback([]);
  2115. };
  2116. // Fake get{Video,Audio}Tracks
  2117. if (!MediaStream.prototype.getVideoTracks) {
  2118. MediaStream.prototype.getVideoTracks = function () {
  2119. return [];
  2120. };
  2121. }
  2122. if (!MediaStream.prototype.getAudioTracks) {
  2123. MediaStream.prototype.getAudioTracks = function () {
  2124. return [];
  2125. };
  2126. }
  2127. AdapterJS.maybeThroughWebRTCReady();
  2128. } else if (navigator.webkitGetUserMedia) {
  2129. webrtcDetectedBrowser = 'chrome';
  2130. webrtcDetectedType = 'webkit';
  2131. webrtcDetectedVersion = parseInt(navigator
  2132. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2133. // check if browser is opera 20+
  2134. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2135. if (checkIfOpera !== null) {
  2136. webrtcDetectedBrowser = 'opera';
  2137. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2138. }
  2139. // check browser datachannel support
  2140. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2141. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2142. webrtcDetectedDCSupport = 'SCTP';
  2143. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2144. webrtcDetectedVersion > 24) {
  2145. webrtcDetectedDCSupport = 'RTP';
  2146. } else {
  2147. webrtcDetectedDCSupport = '';
  2148. }
  2149. createIceServer = function (url, username, password) {
  2150. var iceServer = null;
  2151. var url_parts = url.split(':');
  2152. if (url_parts[0].indexOf('stun') === 0) {
  2153. iceServer = { 'url' : url };
  2154. } else if (url_parts[0].indexOf('turn') === 0) {
  2155. iceServer = {
  2156. 'url' : url,
  2157. 'credential' : password,
  2158. 'username' : username
  2159. };
  2160. }
  2161. return iceServer;
  2162. };
  2163. createIceServers = function (urls, username, password) {
  2164. var iceServers = [];
  2165. if (webrtcDetectedVersion >= 34) {
  2166. iceServers = {
  2167. 'urls' : urls,
  2168. 'credential' : password,
  2169. 'username' : username
  2170. };
  2171. } else {
  2172. for (i = 0; i < urls.length; i++) {
  2173. var iceServer = createIceServer(urls[i], username, password);
  2174. if (iceServer !== null) {
  2175. iceServers.push(iceServer);
  2176. }
  2177. }
  2178. }
  2179. return iceServers;
  2180. };
  2181. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2182. if (webrtcDetectedVersion < 34) {
  2183. AdapterJS.maybeFixConfiguration(pcConfig);
  2184. }
  2185. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2186. };
  2187. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2188. navigator.getUserMedia = window.getUserMedia;
  2189. attachMediaStream = function (element, stream) {
  2190. if (typeof element.srcObject !== 'undefined') {
  2191. element.srcObject = stream;
  2192. } else if (typeof element.mozSrcObject !== 'undefined') {
  2193. element.mozSrcObject = stream;
  2194. } else if (typeof element.src !== 'undefined') {
  2195. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2196. } else {
  2197. console.log('Error attaching stream to element.');
  2198. }
  2199. return element;
  2200. };
  2201. reattachMediaStream = function (to, from) {
  2202. to.src = from.src;
  2203. return to;
  2204. };
  2205. AdapterJS.maybeThroughWebRTCReady();
  2206. } else { // TRY TO USE PLUGIN
  2207. // IE 9 is not offering an implementation of console.log until you open a console
  2208. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2209. /* jshint -W020 */
  2210. console = {} || console;
  2211. // Implemented based on console specs from MDN
  2212. // You may override these functions
  2213. console.log = function (arg) {};
  2214. console.info = function (arg) {};
  2215. console.error = function (arg) {};
  2216. console.dir = function (arg) {};
  2217. console.exception = function (arg) {};
  2218. console.trace = function (arg) {};
  2219. console.warn = function (arg) {};
  2220. console.count = function (arg) {};
  2221. console.debug = function (arg) {};
  2222. console.count = function (arg) {};
  2223. console.time = function (arg) {};
  2224. console.timeEnd = function (arg) {};
  2225. console.group = function (arg) {};
  2226. console.groupCollapsed = function (arg) {};
  2227. console.groupEnd = function (arg) {};
  2228. /* jshint +W020 */
  2229. }
  2230. webrtcDetectedType = 'plugin';
  2231. webrtcDetectedDCSupport = 'plugin';
  2232. AdapterJS.parseWebrtcDetectedBrowser();
  2233. isIE = webrtcDetectedBrowser === 'IE';
  2234. /* jshint -W035 */
  2235. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2236. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2237. /* empty because it needs to prevent the function from running. */
  2238. }
  2239. };
  2240. /* jshint +W035 */
  2241. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2242. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2243. // Call immediately if possible
  2244. // Once the plugin is set, the code will always take this path
  2245. callback();
  2246. } else {
  2247. // otherwise start a 100ms interval
  2248. var checkPluginReadyState = setInterval(function () {
  2249. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2250. clearInterval(checkPluginReadyState);
  2251. callback();
  2252. }
  2253. }, 100);
  2254. }
  2255. };
  2256. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2257. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2258. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2259. });
  2260. };
  2261. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2262. // only inject once the page is ready
  2263. if (document.readyState !== 'complete') {
  2264. return;
  2265. }
  2266. // Prevent multiple injections
  2267. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2268. return;
  2269. }
  2270. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2271. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2272. var frag = document.createDocumentFragment();
  2273. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2274. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2275. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2276. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2277. '<param name="pluginId" value="' +
  2278. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2279. '<param name="windowless" value="false" /> ' +
  2280. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2281. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2282. '" />' +
  2283. // uncomment to be able to use virtual cams
  2284. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2285. '</object>';
  2286. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2287. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2288. }
  2289. document.body.appendChild(frag);
  2290. // Need to re-fetch the plugin
  2291. AdapterJS.WebRTCPlugin.plugin =
  2292. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2293. } else {
  2294. // Load Plugin
  2295. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2296. AdapterJS.WebRTCPlugin.plugin.id =
  2297. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2298. // IE will only start the plugin if it's ACTUALLY visible
  2299. if (isIE) {
  2300. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2301. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2302. } else { // The size of the plugin on Safari should be 0x0px
  2303. // so that the autorisation prompt is at the top
  2304. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2305. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2306. }
  2307. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2308. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2309. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2310. '<param name="pluginId" value="' +
  2311. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2312. '<param name="windowless" value="false" /> ' +
  2313. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2314. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2315. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2316. }
  2317. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2318. };
  2319. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2320. function (comName, plugName, installedCb, notInstalledCb) {
  2321. if (!isIE) {
  2322. var pluginArray = navigator.plugins;
  2323. for (var i = 0; i < pluginArray.length; i++) {
  2324. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2325. installedCb();
  2326. return;
  2327. }
  2328. }
  2329. notInstalledCb();
  2330. } else {
  2331. try {
  2332. var axo = new ActiveXObject(comName + '.' + plugName);
  2333. } catch (e) {
  2334. notInstalledCb();
  2335. return;
  2336. }
  2337. installedCb();
  2338. }
  2339. };
  2340. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2341. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2342. AdapterJS.isDefined = function (variable) {
  2343. return variable !== null && variable !== undefined;
  2344. };
  2345. createIceServer = function (url, username, password) {
  2346. var iceServer = null;
  2347. var url_parts = url.split(':');
  2348. if (url_parts[0].indexOf('stun') === 0) {
  2349. iceServer = {
  2350. 'url' : url,
  2351. 'hasCredentials' : false
  2352. };
  2353. } else if (url_parts[0].indexOf('turn') === 0) {
  2354. iceServer = {
  2355. 'url' : url,
  2356. 'hasCredentials' : true,
  2357. 'credential' : password,
  2358. 'username' : username
  2359. };
  2360. }
  2361. return iceServer;
  2362. };
  2363. createIceServers = function (urls, username, password) {
  2364. var iceServers = [];
  2365. for (var i = 0; i < urls.length; ++i) {
  2366. iceServers.push(createIceServer(urls[i], username, password));
  2367. }
  2368. return iceServers;
  2369. };
  2370. RTCSessionDescription = function (info) {
  2371. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2372. return AdapterJS.WebRTCPlugin.plugin.
  2373. ConstructSessionDescription(info.type, info.sdp);
  2374. };
  2375. RTCPeerConnection = function (servers, constraints) {
  2376. var iceServers = null;
  2377. if (servers) {
  2378. iceServers = servers.iceServers;
  2379. for (var i = 0; i < iceServers.length; i++) {
  2380. if (iceServers[i].urls && !iceServers[i].url) {
  2381. iceServers[i].url = iceServers[i].urls;
  2382. }
  2383. iceServers[i].hasCredentials = AdapterJS.
  2384. isDefined(iceServers[i].username) &&
  2385. AdapterJS.isDefined(iceServers[i].credential);
  2386. }
  2387. }
  2388. var mandatory = (constraints && constraints.mandatory) ?
  2389. constraints.mandatory : null;
  2390. var optional = (constraints && constraints.optional) ?
  2391. constraints.optional : null;
  2392. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2393. return AdapterJS.WebRTCPlugin.plugin.
  2394. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2395. iceServers, mandatory, optional);
  2396. };
  2397. MediaStreamTrack = {};
  2398. MediaStreamTrack.getSources = function (callback) {
  2399. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2400. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2401. });
  2402. };
  2403. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2404. constraints.audio = constraints.audio || false;
  2405. constraints.video = constraints.video || false;
  2406. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2407. AdapterJS.WebRTCPlugin.plugin.
  2408. getUserMedia(constraints, successCallback, failureCallback);
  2409. });
  2410. };
  2411. window.navigator.getUserMedia = window.getUserMedia;
  2412. attachMediaStream = function (element, stream) {
  2413. if (!element || !element.parentNode) {
  2414. return;
  2415. }
  2416. var streamId
  2417. if (stream === null) {
  2418. streamId = '';
  2419. }
  2420. else {
  2421. stream.enableSoundTracks(true);
  2422. streamId = stream.id;
  2423. }
  2424. if (element.nodeName.toLowerCase() !== 'audio') {
  2425. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2426. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2427. var frag = document.createDocumentFragment();
  2428. var temp = document.createElement('div');
  2429. var classHTML = '';
  2430. if (element.className) {
  2431. classHTML = 'class="' + element.className + '" ';
  2432. } else if (element.attributes && element.attributes['class']) {
  2433. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2434. }
  2435. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2436. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2437. '<param name="pluginId" value="' + elementId + '" /> ' +
  2438. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2439. '<param name="windowless" value="true" /> ' +
  2440. '<param name="streamId" value="' + streamId + '" /> ' +
  2441. '</object>';
  2442. while (temp.firstChild) {
  2443. frag.appendChild(temp.firstChild);
  2444. }
  2445. var height = '';
  2446. var width = '';
  2447. if (element.getBoundingClientRect) {
  2448. var rectObject = element.getBoundingClientRect();
  2449. width = rectObject.width + 'px';
  2450. height = rectObject.height + 'px';
  2451. }
  2452. else if (element.width) {
  2453. width = element.width;
  2454. height = element.height;
  2455. } else {
  2456. // TODO: What scenario could bring us here?
  2457. }
  2458. element.parentNode.insertBefore(frag, element);
  2459. frag = document.getElementById(elementId);
  2460. frag.width = width;
  2461. frag.height = height;
  2462. element.parentNode.removeChild(element);
  2463. } else {
  2464. var children = element.children;
  2465. for (var i = 0; i !== children.length; ++i) {
  2466. if (children[i].name === 'streamId') {
  2467. children[i].value = streamId;
  2468. break;
  2469. }
  2470. }
  2471. element.setStreamId(streamId);
  2472. }
  2473. var newElement = document.getElementById(elementId);
  2474. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2475. if (isIE) { // on IE the event needs to be plugged manually
  2476. newElement.attachEvent('onplaying', newElement.onplaying);
  2477. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2478. newElement._TemOnClick = function (id) {
  2479. var arg = {
  2480. srcElement : document.getElementById(id)
  2481. };
  2482. newElement.onclick(arg);
  2483. };
  2484. }
  2485. return newElement;
  2486. } else {
  2487. return element;
  2488. }
  2489. };
  2490. reattachMediaStream = function (to, from) {
  2491. var stream = null;
  2492. var children = from.children;
  2493. for (var i = 0; i !== children.length; ++i) {
  2494. if (children[i].name === 'streamId') {
  2495. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2496. stream = AdapterJS.WebRTCPlugin.plugin
  2497. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2498. break;
  2499. }
  2500. }
  2501. if (stream !== null) {
  2502. return attachMediaStream(to, stream);
  2503. } else {
  2504. console.log('Could not find the stream associated with this element');
  2505. }
  2506. };
  2507. RTCIceCandidate = function (candidate) {
  2508. if (!candidate.sdpMid) {
  2509. candidate.sdpMid = '';
  2510. }
  2511. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2512. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2513. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2514. );
  2515. };
  2516. // inject plugin
  2517. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2518. AdapterJS.WebRTCPlugin.injectPlugin();
  2519. };
  2520. // This function will be called if the plugin is needed (browser different
  2521. // from Chrome or Firefox), but the plugin is not installed.
  2522. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2523. function() {
  2524. AdapterJS.addEvent(document,
  2525. 'readystatechange',
  2526. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2527. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2528. };
  2529. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2530. if (AdapterJS.options.hidePluginInstallPrompt) {
  2531. return;
  2532. }
  2533. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2534. if(downloadLink) { // if download link
  2535. var popupString;
  2536. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2537. popupString = 'This website requires you to install the ' +
  2538. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2539. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2540. ' WebRTC Plugin</a>' +
  2541. ' to work on this browser.';
  2542. } else { // no portal link, just print a generic explanation
  2543. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2544. }
  2545. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2546. } else { // no download link, just print a generic explanation
  2547. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2548. }
  2549. };
  2550. // Try to detect the plugin and act accordingly
  2551. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2552. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2553. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2554. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2555. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2556. }
  2557. (function () {
  2558. 'use strict';
  2559. var baseGetUserMedia = null;
  2560. AdapterJS.TEXT.EXTENSION = {
  2561. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2562. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2563. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2564. BUTTON_FF: 'Install Now',
  2565. BUTTON_CHROME: 'Go to Chrome Web Store'
  2566. };
  2567. var clone = function(obj) {
  2568. if (null == obj || "object" != typeof obj) return obj;
  2569. var copy = obj.constructor();
  2570. for (var attr in obj) {
  2571. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2572. }
  2573. return copy;
  2574. };
  2575. if (window.navigator.mozGetUserMedia) {
  2576. baseGetUserMedia = window.navigator.getUserMedia;
  2577. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2578. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2579. // intercepting screensharing requests
  2580. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2581. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2582. }
  2583. var updatedConstraints = clone(constraints);
  2584. //constraints.video.mediaSource = constraints.video.mediaSource;
  2585. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2586. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2587. // strange but this works anyway
  2588. var checkIfReady = setInterval(function () {
  2589. if (document.readyState === 'complete') {
  2590. clearInterval(checkIfReady);
  2591. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2592. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2593. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2594. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2595. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2596. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2597. } else {
  2598. failureCb(error);
  2599. }
  2600. });
  2601. }
  2602. }, 1);
  2603. } else { // regular GetUserMediaRequest
  2604. baseGetUserMedia(constraints, successCb, failureCb);
  2605. }
  2606. };
  2607. getUserMedia = navigator.getUserMedia;
  2608. } else if (window.navigator.webkitGetUserMedia) {
  2609. baseGetUserMedia = window.navigator.getUserMedia;
  2610. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2611. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2612. if (window.webrtcDetectedBrowser !== 'chrome') {
  2613. throw new Error('Current browser does not support screensharing');
  2614. }
  2615. // would be fine since no methods
  2616. var updatedConstraints = clone(constraints);
  2617. var chromeCallback = function(error, sourceId) {
  2618. if(!error) {
  2619. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2620. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2621. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2622. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2623. if (sourceId) {
  2624. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2625. }
  2626. delete updatedConstraints.video.mediaSource;
  2627. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2628. } else {
  2629. if (error === 'permission-denied') {
  2630. throw new Error('Permission denied for screen retrieval');
  2631. } else {
  2632. throw new Error('Failed retrieving selected screen');
  2633. }
  2634. }
  2635. };
  2636. var onIFrameCallback = function (event) {
  2637. if (!event.data) {
  2638. return;
  2639. }
  2640. if (event.data.chromeMediaSourceId) {
  2641. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2642. chromeCallback('permission-denied');
  2643. } else {
  2644. chromeCallback(null, event.data.chromeMediaSourceId);
  2645. }
  2646. }
  2647. if (event.data.chromeExtensionStatus) {
  2648. if (event.data.chromeExtensionStatus === 'not-installed') {
  2649. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2650. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2651. event.data.data, true, true);
  2652. } else {
  2653. chromeCallback(event.data.chromeExtensionStatus, null);
  2654. }
  2655. }
  2656. // this event listener is no more needed
  2657. window.removeEventListener('message', onIFrameCallback);
  2658. };
  2659. window.addEventListener('message', onIFrameCallback);
  2660. postFrameMessage({
  2661. captureSourceId: true
  2662. });
  2663. } else {
  2664. baseGetUserMedia(constraints, successCb, failureCb);
  2665. }
  2666. };
  2667. getUserMedia = navigator.getUserMedia;
  2668. } else {
  2669. baseGetUserMedia = window.navigator.getUserMedia;
  2670. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2671. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2672. // would be fine since no methods
  2673. var updatedConstraints = clone(constraints);
  2674. // wait for plugin to be ready
  2675. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2676. // check if screensharing feature is available
  2677. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2678. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2679. // set the constraints
  2680. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2681. updatedConstraints.video.optional.push({
  2682. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2683. });
  2684. delete updatedConstraints.video.mediaSource;
  2685. } else {
  2686. throw new Error('Your WebRTC plugin does not support screensharing');
  2687. }
  2688. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2689. });
  2690. } else {
  2691. baseGetUserMedia(constraints, successCb, failureCb);
  2692. }
  2693. };
  2694. getUserMedia = window.navigator.getUserMedia;
  2695. }
  2696. if (window.webrtcDetectedBrowser === 'chrome') {
  2697. var iframe = document.createElement('iframe');
  2698. iframe.onload = function() {
  2699. iframe.isLoaded = true;
  2700. };
  2701. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2702. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2703. iframe.style.display = 'none';
  2704. (document.body || document.documentElement).appendChild(iframe);
  2705. var postFrameMessage = function (object) {
  2706. object = object || {};
  2707. if (!iframe.isLoaded) {
  2708. setTimeout(function () {
  2709. iframe.contentWindow.postMessage(object, '*');
  2710. }, 100);
  2711. return;
  2712. }
  2713. iframe.contentWindow.postMessage(object, '*');
  2714. };
  2715. }
  2716. })();
  2717. },{}],11:[function(require,module,exports){
  2718. var UI = {};
  2719. var VideoLayout = require("./videolayout/VideoLayout.js");
  2720. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2721. var Prezi = require("./prezi/Prezi.js");
  2722. var Etherpad = require("./etherpad/Etherpad.js");
  2723. var Chat = require("./side_pannels/chat/Chat.js");
  2724. var Toolbar = require("./toolbars/Toolbar");
  2725. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2726. var BottomToolbar = require("./toolbars/BottomToolbar");
  2727. var ContactList = require("./side_pannels/contactlist/ContactList");
  2728. var Avatar = require("./avatar/Avatar");
  2729. var EventEmitter = require("events");
  2730. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2731. var Settings = require("./../settings/Settings");
  2732. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2733. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2734. UI.messageHandler = require("./util/MessageHandler");
  2735. var messageHandler = UI.messageHandler;
  2736. var Authentication = require("./authentication/Authentication");
  2737. var UIUtil = require("./util/UIUtil");
  2738. var NicknameHandler = require("./util/NicknameHandler");
  2739. var CQEvents = require("../../service/connectionquality/CQEvents");
  2740. var DesktopSharingEventTypes
  2741. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2742. var RTCEvents = require("../../service/RTC/RTCEvents");
  2743. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2744. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2745. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2746. var MemberEvents = require("../../service/members/Events");
  2747. var eventEmitter = new EventEmitter();
  2748. var roomName = null;
  2749. function promptDisplayName() {
  2750. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2751. message += APP.translation.translateString(
  2752. "dialog.displayNameRequired");
  2753. message += '</h2>' +
  2754. '<input name="displayName" type="text" data-i18n=' +
  2755. '"[placeholder]defaultNickname" placeholder="' +
  2756. APP.translation.translateString(
  2757. "defaultNickname", {name: "Jane Pink"}) +
  2758. '" autofocus>';
  2759. var buttonTxt
  2760. = APP.translation.generateTranslationHTML("dialog.Ok");
  2761. var buttons = [];
  2762. buttons.push({title: buttonTxt, value: "ok"});
  2763. messageHandler.openDialog(null, message,
  2764. true,
  2765. buttons,
  2766. function (e, v, m, f) {
  2767. if (v == "ok") {
  2768. var displayName = f.displayName;
  2769. if (displayName) {
  2770. VideoLayout.inputDisplayNameHandler(displayName);
  2771. return true;
  2772. }
  2773. }
  2774. e.preventDefault();
  2775. },
  2776. function () {
  2777. var form = $.prompt.getPrompt();
  2778. var input = form.find("input[name='displayName']");
  2779. input.focus();
  2780. var button = form.find("button");
  2781. button.attr("disabled", "disabled");
  2782. input.keyup(function () {
  2783. if(!input.val())
  2784. button.attr("disabled", "disabled");
  2785. else
  2786. button.removeAttr("disabled");
  2787. });
  2788. }
  2789. );
  2790. }
  2791. function notifyForInitialMute()
  2792. {
  2793. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2794. "notify.muted", null, {timeOut: 120000});
  2795. }
  2796. function setupPrezi()
  2797. {
  2798. $("#reloadPresentationLink").click(function()
  2799. {
  2800. Prezi.reloadPresentation();
  2801. });
  2802. }
  2803. function setupChat()
  2804. {
  2805. Chat.init();
  2806. $("#toggle_smileys").click(function() {
  2807. Chat.toggleSmileys();
  2808. });
  2809. }
  2810. function setupToolbars() {
  2811. Toolbar.init(UI);
  2812. Toolbar.setupButtonsFromConfig();
  2813. BottomToolbar.init();
  2814. }
  2815. function streamHandler(stream, isMuted) {
  2816. switch (stream.type)
  2817. {
  2818. case "audio":
  2819. VideoLayout.changeLocalAudio(stream, isMuted);
  2820. break;
  2821. case "video":
  2822. VideoLayout.changeLocalVideo(stream, isMuted);
  2823. break;
  2824. case "stream":
  2825. VideoLayout.changeLocalStream(stream, isMuted);
  2826. break;
  2827. }
  2828. }
  2829. function onXmppConnectionFailed(stropheErrorMsg) {
  2830. var title = APP.translation.generateTranslationHTML(
  2831. "dialog.error");
  2832. var message;
  2833. if (stropheErrorMsg) {
  2834. message = APP.translation.generateTranslationHTML(
  2835. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2836. } else {
  2837. message = APP.translation.generateTranslationHTML(
  2838. "dialog.connectError");
  2839. }
  2840. messageHandler.openDialog(
  2841. title, message, true, {}, function (e, v, m, f) { return false; });
  2842. }
  2843. function onDisposeConference(unload) {
  2844. Toolbar.showAuthenticateButton(false);
  2845. }
  2846. function onDisplayNameChanged(jid, displayName) {
  2847. ContactList.onDisplayNameChange(jid, displayName);
  2848. SettingsMenu.onDisplayNameChange(jid, displayName);
  2849. VideoLayout.onDisplayNameChanged(jid, displayName);
  2850. }
  2851. function registerListeners() {
  2852. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2853. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2854. APP.RTC.addStreamListener(function (stream) {
  2855. VideoLayout.onRemoteStreamAdded(stream);
  2856. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2857. APP.RTC.addStreamListener(function (jid) {
  2858. VideoLayout.onVideoTypeChanged(jid);
  2859. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  2860. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2861. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  2862. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2863. });
  2864. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2865. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2866. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2867. endpointsEnteringLastN, stream);
  2868. });
  2869. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2870. function (devices) {
  2871. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2872. })
  2873. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  2874. {
  2875. var resourceJid;
  2876. if(jid === APP.statistics.LOCAL_JID)
  2877. {
  2878. resourceJid = AudioLevels.LOCAL_LEVEL;
  2879. if(APP.RTC.localAudio.isMuted())
  2880. {
  2881. audioLevel = 0;
  2882. }
  2883. }
  2884. else
  2885. {
  2886. resourceJid = Strophe.getResourceFromJid(jid);
  2887. }
  2888. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2889. UI.getLargeVideoJid());
  2890. });
  2891. APP.desktopsharing.addListener(function () {
  2892. ToolbarToggler.showDesktopSharingButton();
  2893. }, DesktopSharingEventTypes.INIT);
  2894. APP.desktopsharing.addListener(
  2895. Toolbar.changeDesktopSharingButtonState,
  2896. DesktopSharingEventTypes.SWITCHING_DONE);
  2897. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2898. VideoLayout.updateLocalConnectionStats);
  2899. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2900. VideoLayout.updateConnectionStats);
  2901. APP.connectionquality.addListener(CQEvents.STOP,
  2902. VideoLayout.onStatsStop);
  2903. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2904. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2905. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2906. messageHandler.openMessageDialog(
  2907. 'dialog.serviceUnavailable',
  2908. 'dialog.gracefulShutdown'
  2909. );
  2910. });
  2911. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2912. var title = APP.translation.generateTranslationHTML(
  2913. "dialog.reservationError");
  2914. var message = APP.translation.generateTranslationHTML(
  2915. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2916. messageHandler.openDialog(
  2917. title,
  2918. message,
  2919. true, {},
  2920. function (event, value, message, formVals)
  2921. {
  2922. return false;
  2923. }
  2924. );
  2925. });
  2926. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2927. messageHandler.openMessageDialog("dialog.sessTerminated",
  2928. "dialog.kickMessage");
  2929. });
  2930. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2931. //FIXME: use Session Terminated from translation, but
  2932. // 'reason' text comes from XMPP packet and is not translated
  2933. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2934. messageHandler.openDialog(
  2935. title, reason, true, {},
  2936. function (event, value, message, formVals)
  2937. {
  2938. return false;
  2939. }
  2940. );
  2941. });
  2942. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2943. messageHandler.showError("dialog.error",
  2944. "dialog.bridgeUnavailable");
  2945. });
  2946. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2947. Avatar.setUserAvatar(from, id);
  2948. });
  2949. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2950. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2951. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2952. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2953. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2954. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2955. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2956. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2957. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2958. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2959. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2960. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2961. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2962. onAuthenticationRequired);
  2963. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2964. function (resource, devices) {
  2965. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2966. });
  2967. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  2968. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  2969. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2970. onDtmfSupportChanged);
  2971. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  2972. SettingsMenu.setStartMuted(audio, video);
  2973. });
  2974. }
  2975. /**
  2976. * Mutes/unmutes the local video.
  2977. *
  2978. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2979. * @param options an object which specifies optional arguments such as the
  2980. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2981. * specifies whether the method was initiated in response to a user command (in
  2982. * contrast to an automatic decision taken by the application logic)
  2983. */
  2984. function setVideoMute(mute, options) {
  2985. APP.RTC.setVideoMute(mute,
  2986. UI.setVideoMuteButtonsState,
  2987. options);
  2988. }
  2989. function onResize()
  2990. {
  2991. Chat.resizeChat();
  2992. VideoLayout.resizeLargeVideoContainer();
  2993. }
  2994. function bindEvents()
  2995. {
  2996. /**
  2997. * Resizes and repositions videos in full screen mode.
  2998. */
  2999. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  3000. onResize);
  3001. $(window).resize(onResize);
  3002. }
  3003. UI.start = function (init) {
  3004. document.title = interfaceConfig.APP_NAME;
  3005. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3006. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3007. {
  3008. $("#videoconference_page").hide();
  3009. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3010. setupWelcomePage();
  3011. return;
  3012. }
  3013. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  3014. var leftWatermarkDiv
  3015. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  3016. leftWatermarkDiv.css({display: 'block'});
  3017. leftWatermarkDiv.parent().get(0).href
  3018. = interfaceConfig.JITSI_WATERMARK_LINK;
  3019. }
  3020. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  3021. var rightWatermarkDiv
  3022. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  3023. rightWatermarkDiv.css({display: 'block'});
  3024. rightWatermarkDiv.parent().get(0).href
  3025. = interfaceConfig.BRAND_WATERMARK_LINK;
  3026. rightWatermarkDiv.get(0).style.backgroundImage
  3027. = "url(images/rightwatermark.png)";
  3028. }
  3029. if (interfaceConfig.SHOW_POWERED_BY) {
  3030. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  3031. }
  3032. $("#welcome_page").hide();
  3033. $("#videospace").mousemove(function () {
  3034. return ToolbarToggler.showToolbar();
  3035. });
  3036. // Set the defaults for prompt dialogs.
  3037. jQuery.prompt.setDefaults({persistent: false});
  3038. VideoLayout.init(eventEmitter);
  3039. AudioLevels.init();
  3040. NicknameHandler.init(eventEmitter);
  3041. registerListeners();
  3042. bindEvents();
  3043. setupPrezi();
  3044. setupToolbars();
  3045. setupChat();
  3046. document.title = interfaceConfig.APP_NAME;
  3047. $("#downloadlog").click(function (event) {
  3048. dump(event.target);
  3049. });
  3050. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3051. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3052. {
  3053. $("#videoconference_page").hide();
  3054. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3055. setupWelcomePage();
  3056. return;
  3057. }
  3058. $("#welcome_page").hide();
  3059. // Display notice message at the top of the toolbar
  3060. if (config.noticeMessage) {
  3061. $('#noticeText').text(config.noticeMessage);
  3062. $('#notice').css({display: 'block'});
  3063. }
  3064. if (!RTCBrowserType.isIExplorer()) {
  3065. document.getElementById('largeVideo').volume = 0;
  3066. }
  3067. if(config.requireDisplayName) {
  3068. var currentSettings = Settings.getSettings();
  3069. if (!currentSettings.displayName) {
  3070. promptDisplayName();
  3071. }
  3072. }
  3073. init();
  3074. toastr.options = {
  3075. "closeButton": true,
  3076. "debug": false,
  3077. "positionClass": "notification-bottom-right",
  3078. "onclick": null,
  3079. "showDuration": "300",
  3080. "hideDuration": "1000",
  3081. "timeOut": "2000",
  3082. "extendedTimeOut": "1000",
  3083. "showEasing": "swing",
  3084. "hideEasing": "linear",
  3085. "showMethod": "fadeIn",
  3086. "hideMethod": "fadeOut",
  3087. "reposition": function() {
  3088. if(PanelToggler.isVisible()) {
  3089. $("#toast-container").addClass("notification-bottom-right-center");
  3090. } else {
  3091. $("#toast-container").removeClass("notification-bottom-right-center");
  3092. }
  3093. },
  3094. "newestOnTop": false
  3095. };
  3096. SettingsMenu.init();
  3097. };
  3098. function chatAddError(errorMessage, originalText)
  3099. {
  3100. return Chat.chatAddError(errorMessage, originalText);
  3101. };
  3102. function chatSetSubject(text)
  3103. {
  3104. return Chat.chatSetSubject(text);
  3105. };
  3106. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3107. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3108. }
  3109. function onMucJoined(jid, info) {
  3110. Toolbar.updateRoomUrl(window.location.href);
  3111. var meHTML = APP.translation.generateTranslationHTML("me");
  3112. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3113. var settings = Settings.getSettings();
  3114. // Make sure we configure our avatar id, before creating avatar for us
  3115. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3116. // Add myself to the contact list.
  3117. ContactList.addContact(jid);
  3118. // Once we've joined the muc show the toolbar
  3119. ToolbarToggler.showToolbar();
  3120. var displayName = !config.displayJids
  3121. ? info.displayName : Strophe.getResourceFromJid(jid);
  3122. if (displayName)
  3123. onDisplayNameChanged('localVideoContainer', displayName);
  3124. VideoLayout.mucJoined();
  3125. }
  3126. function initEtherpad(name) {
  3127. Etherpad.init(name);
  3128. }
  3129. function onMucMemberLeft(jid) {
  3130. console.log('left.muc', jid);
  3131. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3132. '>.displayname').html();
  3133. messageHandler.notify(displayName,'notify.somebody',
  3134. 'disconnected',
  3135. 'notify.disconnected');
  3136. if(!config.startAudioMuted ||
  3137. config.startAudioMuted > APP.members.size())
  3138. UIUtil.playSoundNotification('userLeft');
  3139. // Need to call this with a slight delay, otherwise the element couldn't be
  3140. // found for some reason.
  3141. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  3142. window.setTimeout(function () {
  3143. var container = document.getElementById(
  3144. 'participant_' + Strophe.getResourceFromJid(jid));
  3145. if (container) {
  3146. ContactList.removeContact(jid);
  3147. VideoLayout.removeConnectionIndicator(jid);
  3148. // hide here, wait for video to close before removing
  3149. $(container).hide();
  3150. VideoLayout.resizeThumbnails();
  3151. }
  3152. }, 10);
  3153. VideoLayout.participantLeft(jid);
  3154. };
  3155. function onLocalRoleChanged(jid, info, pres, isModerator)
  3156. {
  3157. console.info("My role changed, new role: " + info.role);
  3158. onModeratorStatusChanged(isModerator);
  3159. VideoLayout.showModeratorIndicator();
  3160. SettingsMenu.onRoleChanged();
  3161. if (isModerator) {
  3162. Authentication.closeAuthenticationWindow();
  3163. messageHandler.notify(null, "notify.me",
  3164. 'connected', "notify.moderator");
  3165. }
  3166. }
  3167. function onModeratorStatusChanged(isModerator) {
  3168. Toolbar.showSipCallButton(isModerator);
  3169. Toolbar.showRecordingButton(
  3170. isModerator); //&&
  3171. // FIXME:
  3172. // Recording visible if
  3173. // there are at least 2(+ 1 focus) participants
  3174. //Object.keys(connection.emuc.members).length >= 3);
  3175. }
  3176. function onPasswordRequired(callback) {
  3177. // password is required
  3178. Toolbar.lockLockButton();
  3179. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3180. message += APP.translation.translateString(
  3181. "dialog.passwordRequired");
  3182. message += '</h2>' +
  3183. '<input name="lockKey" type="text" data-i18n=' +
  3184. '"[placeholder]dialog.password" placeholder="' +
  3185. APP.translation.translateString("dialog.password") +
  3186. '" autofocus>';
  3187. messageHandler.openTwoButtonDialog(null, null, null, message,
  3188. true,
  3189. "dialog.Ok",
  3190. function (e, v, m, f) {},
  3191. null,
  3192. function (e, v, m, f) {
  3193. if (v) {
  3194. var lockKey = f.lockKey;
  3195. if (lockKey) {
  3196. Toolbar.setSharedKey(lockKey);
  3197. callback(lockKey);
  3198. }
  3199. }
  3200. },
  3201. ':input:first'
  3202. );
  3203. }
  3204. /**
  3205. * The dialpad button is shown iff there is at least one member that supports
  3206. * DTMF (e.g. jigasi).
  3207. */
  3208. function onDtmfSupportChanged(dtmfSupport) {
  3209. //TODO: enable when the UI is ready
  3210. //Toolbar.showDialPadButton(dtmfSupport);
  3211. }
  3212. function onMucMemberJoined(jid, id, displayName) {
  3213. messageHandler.notify(displayName,'notify.somebody',
  3214. 'connected',
  3215. 'notify.connected');
  3216. if(!config.startAudioMuted ||
  3217. config.startAudioMuted > APP.members.size())
  3218. UIUtil.playSoundNotification('userJoined');
  3219. // Configure avatar
  3220. Avatar.setUserAvatar(jid, id);
  3221. // Add Peer's container
  3222. VideoLayout.ensurePeerContainerExists(jid);
  3223. }
  3224. function onMucPresenceStatus(jid, info) {
  3225. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3226. }
  3227. function onMucRoleChanged(role, displayName) {
  3228. VideoLayout.showModeratorIndicator();
  3229. if (role === 'moderator') {
  3230. var messageKey, messageOptions = {};
  3231. if (!displayName) {
  3232. messageKey = "notify.grantedToUnknown";
  3233. }
  3234. else
  3235. {
  3236. messageKey = "notify.grantedTo";
  3237. messageOptions = {to: displayName};
  3238. }
  3239. messageHandler.notify(
  3240. displayName,'notify.somebody',
  3241. 'connected', messageKey,
  3242. messageOptions);
  3243. }
  3244. }
  3245. function onAuthenticationRequired(intervalCallback) {
  3246. Authentication.openAuthenticationDialog(
  3247. roomName, intervalCallback, function () {
  3248. Toolbar.authenticateClicked();
  3249. });
  3250. };
  3251. function onLastNChanged(oldValue, newValue) {
  3252. if (config.muteLocalVideoIfNotInLastN) {
  3253. setVideoMute(!newValue, { 'byUser': false });
  3254. }
  3255. }
  3256. UI.toggleSmileys = function () {
  3257. Chat.toggleSmileys();
  3258. };
  3259. UI.getSettings = function () {
  3260. return Settings.getSettings();
  3261. };
  3262. UI.toggleFilmStrip = function () {
  3263. return BottomToolbar.toggleFilmStrip();
  3264. };
  3265. UI.toggleChat = function () {
  3266. return BottomToolbar.toggleChat();
  3267. };
  3268. UI.toggleContactList = function () {
  3269. return BottomToolbar.toggleContactList();
  3270. };
  3271. UI.inputDisplayNameHandler = function (value) {
  3272. VideoLayout.inputDisplayNameHandler(value);
  3273. };
  3274. UI.getLargeVideoJid = function()
  3275. {
  3276. return VideoLayout.getLargeVideoJid();
  3277. };
  3278. UI.generateRoomName = function() {
  3279. if(roomName)
  3280. return roomName;
  3281. var roomnode = null;
  3282. var path = window.location.pathname;
  3283. // determinde the room node from the url
  3284. // TODO: just the roomnode or the whole bare jid?
  3285. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3286. // custom function might be responsible for doing the pushstate
  3287. roomnode = config.getroomnode(path);
  3288. } else {
  3289. /* fall back to default strategy
  3290. * this is making assumptions about how the URL->room mapping happens.
  3291. * It currently assumes deployment at root, with a rewrite like the
  3292. * following one (for nginx):
  3293. location ~ ^/([a-zA-Z0-9]+)$ {
  3294. rewrite ^/(.*)$ / break;
  3295. }
  3296. */
  3297. if (path.length > 1) {
  3298. roomnode = path.substr(1).toLowerCase();
  3299. } else {
  3300. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3301. roomnode = word.toLowerCase();
  3302. window.history.pushState('VideoChat',
  3303. 'Room: ' + word, window.location.pathname + word);
  3304. }
  3305. }
  3306. roomName = roomnode + '@' + config.hosts.muc;
  3307. return roomName;
  3308. };
  3309. UI.connectionIndicatorShowMore = function(jid)
  3310. {
  3311. return VideoLayout.showMore(jid);
  3312. };
  3313. UI.showLoginPopup = function(callback)
  3314. {
  3315. console.log('password is required');
  3316. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3317. message += APP.translation.translateString(
  3318. "dialog.passwordRequired");
  3319. message += '</h2>' +
  3320. '<input name="username" type="text" ' +
  3321. 'placeholder="user@domain.net" autofocus>' +
  3322. '<input name="password" ' +
  3323. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3324. ' placeholder="user password">';
  3325. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3326. true,
  3327. "dialog.Ok",
  3328. function (e, v, m, f) {
  3329. if (v) {
  3330. if (f.username !== null && f.password != null) {
  3331. callback(f.username, f.password);
  3332. }
  3333. }
  3334. },
  3335. null, null, ':input:first'
  3336. );
  3337. }
  3338. UI.checkForNicknameAndJoin = function () {
  3339. Authentication.closeAuthenticationDialog();
  3340. Authentication.stopInterval();
  3341. var nick = null;
  3342. if (config.useNicks) {
  3343. nick = window.prompt('Your nickname (optional)');
  3344. }
  3345. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3346. };
  3347. function dump(elem, filename) {
  3348. elem = elem.parentNode;
  3349. elem.download = filename || 'meetlog.json';
  3350. elem.href = 'data:application/json;charset=utf-8,\n';
  3351. var data = APP.xmpp.populateData();
  3352. var metadata = {};
  3353. metadata.time = new Date();
  3354. metadata.url = window.location.href;
  3355. metadata.ua = navigator.userAgent;
  3356. var log = APP.xmpp.getLogger();
  3357. if (log) {
  3358. metadata.xmpp = log;
  3359. }
  3360. data.metadata = metadata;
  3361. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3362. return false;
  3363. }
  3364. UI.getRoomName = function () {
  3365. return roomName;
  3366. };
  3367. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3368. if(muteAudio || muteVideo) notifyForInitialMute();
  3369. if(muteAudio) UI.setAudioMuted(true);
  3370. if(muteVideo) UI.setVideoMute(true);
  3371. }
  3372. /**
  3373. * Mutes/unmutes the local video.
  3374. */
  3375. UI.toggleVideo = function () {
  3376. setVideoMute(!APP.RTC.localVideo.isMuted());
  3377. };
  3378. /**
  3379. * Mutes / unmutes audio for the local participant.
  3380. */
  3381. UI.toggleAudio = function() {
  3382. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3383. };
  3384. /**
  3385. * Sets muted audio state for the local participant.
  3386. */
  3387. UI.setAudioMuted = function (mute, earlyMute) {
  3388. var audioMute = null;
  3389. if(earlyMute)
  3390. audioMute = function (mute, cb) {
  3391. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3392. };
  3393. else
  3394. audioMute = function (mute, cb) {
  3395. return APP.xmpp.setAudioMute(mute, cb);
  3396. }
  3397. if(!audioMute(mute, function () {
  3398. VideoLayout.showLocalAudioIndicator(mute);
  3399. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3400. }))
  3401. {
  3402. // We still click the button.
  3403. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3404. return;
  3405. }
  3406. }
  3407. UI.addListener = function (type, listener) {
  3408. eventEmitter.on(type, listener);
  3409. }
  3410. UI.clickOnVideo = function (videoNumber) {
  3411. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3412. if (remoteVideos.length > videoNumber) {
  3413. remoteVideos[videoNumber].click();
  3414. }
  3415. }
  3416. //Used by torture
  3417. UI.showToolbar = function () {
  3418. return ToolbarToggler.showToolbar();
  3419. }
  3420. //Used by torture
  3421. UI.dockToolbar = function (isDock) {
  3422. return ToolbarToggler.dockToolbar(isDock);
  3423. }
  3424. UI.setVideoMuteButtonsState = function (mute) {
  3425. var video = $('#video');
  3426. var communicativeClass = "icon-camera";
  3427. var muteClass = "icon-camera icon-camera-disabled";
  3428. if (mute) {
  3429. video.removeClass(communicativeClass);
  3430. video.addClass(muteClass);
  3431. } else {
  3432. video.removeClass(muteClass);
  3433. video.addClass(communicativeClass);
  3434. }
  3435. }
  3436. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3437. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3438. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3439. if(resourceJid === APP.xmpp.myResource())
  3440. SettingsMenu.changeAvatar(thumbUrl);
  3441. }
  3442. UI.setVideoMute = setVideoMute;
  3443. module.exports = UI;
  3444. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes":101,"../../service/connectionquality/CQEvents":104,"../../service/desktopsharing/DesktopSharingEventTypes":105,"../../service/members/Events":106,"../../service/xmpp/XMPPEvents":108,"../RTC/RTCBrowserType":8,"./../settings/Settings":47,"./audio_levels/AudioLevels.js":12,"./authentication/Authentication":14,"./avatar/Avatar":16,"./etherpad/Etherpad.js":17,"./prezi/Prezi.js":18,"./side_pannels/SidePanelToggler":20,"./side_pannels/chat/Chat.js":21,"./side_pannels/contactlist/ContactList":25,"./side_pannels/settings/SettingsMenu":26,"./toolbars/BottomToolbar":27,"./toolbars/Toolbar":28,"./toolbars/ToolbarToggler":29,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":109}],12:[function(require,module,exports){
  3445. var CanvasUtil = require("./CanvasUtils");
  3446. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3447. function initActiveSpeakerAudioLevels() {
  3448. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3449. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3450. // Draw a circle.
  3451. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3452. // Add a shadow around the circle
  3453. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3454. ASDrawContext.shadowOffsetX = 0;
  3455. ASDrawContext.shadowOffsetY = 0;
  3456. }
  3457. /**
  3458. * The audio Levels plugin.
  3459. */
  3460. var AudioLevels = (function(my) {
  3461. var audioLevelCanvasCache = {};
  3462. my.LOCAL_LEVEL = 'local';
  3463. my.init = function () {
  3464. initActiveSpeakerAudioLevels();
  3465. }
  3466. /**
  3467. * Updates the audio level canvas for the given peerJid. If the canvas
  3468. * didn't exist we create it.
  3469. */
  3470. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3471. var resourceJid = null;
  3472. var videoSpanId = null;
  3473. if (!peerJid)
  3474. videoSpanId = 'localVideoContainer';
  3475. else {
  3476. resourceJid = Strophe.getResourceFromJid(peerJid);
  3477. videoSpanId = 'participant_' + resourceJid;
  3478. }
  3479. var videoSpan = document.getElementById(videoSpanId);
  3480. if (!videoSpan) {
  3481. if (resourceJid)
  3482. console.error("No video element for jid", resourceJid);
  3483. else
  3484. console.error("No video element for local video.");
  3485. return;
  3486. }
  3487. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3488. var videoSpaceWidth = $('#remoteVideos').width();
  3489. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3490. var thumbnailWidth = thumbnailSize[0];
  3491. var thumbnailHeight = thumbnailSize[1];
  3492. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3493. audioLevelCanvas = document.createElement('canvas');
  3494. audioLevelCanvas.className = "audiolevel";
  3495. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3496. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3497. resizeAudioLevelCanvas( audioLevelCanvas,
  3498. thumbnailWidth,
  3499. thumbnailHeight);
  3500. videoSpan.appendChild(audioLevelCanvas);
  3501. } else {
  3502. audioLevelCanvas = audioLevelCanvas.get(0);
  3503. resizeAudioLevelCanvas( audioLevelCanvas,
  3504. thumbnailWidth,
  3505. thumbnailHeight);
  3506. }
  3507. };
  3508. /**
  3509. * Updates the audio level UI for the given resourceJid.
  3510. *
  3511. * @param resourceJid the resource jid indicating the video element for
  3512. * which we draw the audio level
  3513. * @param audioLevel the newAudio level to render
  3514. */
  3515. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3516. drawAudioLevelCanvas(resourceJid, audioLevel);
  3517. var videoSpanId = getVideoSpanId(resourceJid);
  3518. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3519. if (!audioLevelCanvas)
  3520. return;
  3521. var drawContext = audioLevelCanvas.getContext('2d');
  3522. var canvasCache = audioLevelCanvasCache[resourceJid];
  3523. drawContext.clearRect (0, 0,
  3524. audioLevelCanvas.width, audioLevelCanvas.height);
  3525. drawContext.drawImage(canvasCache, 0, 0);
  3526. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3527. if(!APP.xmpp.myJid()) {
  3528. return;
  3529. }
  3530. resourceJid = APP.xmpp.myResource();
  3531. }
  3532. if(resourceJid === largeVideoResourceJid) {
  3533. window.requestAnimationFrame(function () {
  3534. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3535. });
  3536. }
  3537. };
  3538. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3539. if($("#activeSpeaker").css("visibility") == "hidden")
  3540. return;
  3541. ASDrawContext.clearRect(0, 0, 300, 300);
  3542. if(audioLevel == 0)
  3543. return;
  3544. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3545. // Fill the shape.
  3546. ASDrawContext.fill();
  3547. };
  3548. /**
  3549. * Resizes the given audio level canvas to match the given thumbnail size.
  3550. */
  3551. function resizeAudioLevelCanvas(audioLevelCanvas,
  3552. thumbnailWidth,
  3553. thumbnailHeight) {
  3554. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3555. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3556. }
  3557. /**
  3558. * Draws the audio level canvas into the cached canvas object.
  3559. *
  3560. * @param resourceJid the resource jid indicating the video element for
  3561. * which we draw the audio level
  3562. * @param audioLevel the newAudio level to render
  3563. */
  3564. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3565. if (!audioLevelCanvasCache[resourceJid]) {
  3566. var videoSpanId = getVideoSpanId(resourceJid);
  3567. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3568. /*
  3569. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3570. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3571. * error. Since audio levels are frequently updated, the errors have
  3572. * been observed to pile into the console, strain the CPU.
  3573. */
  3574. if (audioLevelCanvasOrig)
  3575. {
  3576. audioLevelCanvasCache[resourceJid]
  3577. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3578. }
  3579. }
  3580. var canvas = audioLevelCanvasCache[resourceJid];
  3581. if (!canvas)
  3582. return;
  3583. var drawContext = canvas.getContext('2d');
  3584. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3585. var shadowLevel = getShadowLevel(audioLevel);
  3586. if (shadowLevel > 0)
  3587. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3588. CanvasUtil.drawRoundRectGlow( drawContext,
  3589. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  3590. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3591. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3592. interfaceConfig.CANVAS_RADIUS,
  3593. interfaceConfig.SHADOW_COLOR,
  3594. shadowLevel);
  3595. }
  3596. /**
  3597. * Returns the shadow/glow level for the given audio level.
  3598. *
  3599. * @param audioLevel the audio level from which we determine the shadow
  3600. * level
  3601. */
  3602. function getShadowLevel (audioLevel) {
  3603. var shadowLevel = 0;
  3604. if (audioLevel <= 0.3) {
  3605. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3606. }
  3607. else if (audioLevel <= 0.6) {
  3608. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3609. }
  3610. else {
  3611. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3612. }
  3613. return shadowLevel;
  3614. }
  3615. /**
  3616. * Returns the video span id corresponding to the given resourceJid or local
  3617. * user.
  3618. */
  3619. function getVideoSpanId(resourceJid) {
  3620. var videoSpanId = null;
  3621. if (resourceJid === AudioLevels.LOCAL_LEVEL
  3622. || (APP.xmpp.myResource() && resourceJid
  3623. === APP.xmpp.myResource()))
  3624. videoSpanId = 'localVideoContainer';
  3625. else
  3626. videoSpanId = 'participant_' + resourceJid;
  3627. return videoSpanId;
  3628. }
  3629. /**
  3630. * Indicates that the remote video has been resized.
  3631. */
  3632. $(document).bind('remotevideo.resized', function (event, width, height) {
  3633. var resized = false;
  3634. $('#remoteVideos>span>canvas').each(function() {
  3635. var canvas = $(this).get(0);
  3636. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3637. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3638. resized = true;
  3639. }
  3640. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3641. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3642. resized = true;
  3643. }
  3644. });
  3645. if (resized)
  3646. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3647. audioLevelCanvasCache[resourceJid].width
  3648. = width + interfaceConfig.CANVAS_EXTRA;
  3649. audioLevelCanvasCache[resourceJid].height
  3650. = height + interfaceConfig.CANVAS_EXTRA;
  3651. });
  3652. });
  3653. return my;
  3654. })(AudioLevels || {});
  3655. module.exports = AudioLevels;
  3656. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3657. /**
  3658. * Utility class for drawing canvas shapes.
  3659. */
  3660. var CanvasUtil = (function(my) {
  3661. /**
  3662. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3663. * of the glow.
  3664. *
  3665. * @param drawContext the context of the canvas to draw to
  3666. * @param x the x coordinate of the round rectangle
  3667. * @param y the y coordinate of the round rectangle
  3668. * @param w the width of the round rectangle
  3669. * @param h the height of the round rectangle
  3670. * @param glowColor the color of the glow
  3671. * @param glowWidth the width of the glow
  3672. */
  3673. my.drawRoundRectGlow
  3674. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3675. // Save the previous state of the context.
  3676. drawContext.save();
  3677. if (w < 2 * r) r = w / 2;
  3678. if (h < 2 * r) r = h / 2;
  3679. // Draw a round rectangle.
  3680. drawContext.beginPath();
  3681. drawContext.moveTo(x+r, y);
  3682. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3683. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3684. drawContext.arcTo(x, y+h, x, y, r);
  3685. drawContext.arcTo(x, y, x+w, y, r);
  3686. drawContext.closePath();
  3687. // Add a shadow around the rectangle
  3688. drawContext.shadowColor = glowColor;
  3689. drawContext.shadowBlur = glowWidth;
  3690. drawContext.shadowOffsetX = 0;
  3691. drawContext.shadowOffsetY = 0;
  3692. // Fill the shape.
  3693. drawContext.fill();
  3694. drawContext.save();
  3695. drawContext.restore();
  3696. // 1) Uncomment this line to use Composite Operation, which is doing the
  3697. // same as the clip function below and is also antialiasing the round
  3698. // border, but is said to be less fast performance wise.
  3699. // drawContext.globalCompositeOperation='destination-out';
  3700. drawContext.beginPath();
  3701. drawContext.moveTo(x+r, y);
  3702. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3703. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3704. drawContext.arcTo(x, y+h, x, y, r);
  3705. drawContext.arcTo(x, y, x+w, y, r);
  3706. drawContext.closePath();
  3707. // 2) Uncomment this line to use Composite Operation, which is doing the
  3708. // same as the clip function below and is also antialiasing the round
  3709. // border, but is said to be less fast performance wise.
  3710. // drawContext.fill();
  3711. // Comment these two lines if choosing to do the same with composite
  3712. // operation above 1 and 2.
  3713. drawContext.clip();
  3714. drawContext.clearRect(0, 0, 277, 200);
  3715. // Restore the previous context state.
  3716. drawContext.restore();
  3717. };
  3718. /**
  3719. * Clones the given canvas.
  3720. *
  3721. * @return the new cloned canvas.
  3722. */
  3723. my.cloneCanvas = function (oldCanvas) {
  3724. /*
  3725. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3726. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3727. * levels are frequently updated, the errors have been observed to pile
  3728. * into the console, strain the CPU.
  3729. */
  3730. if (!oldCanvas)
  3731. return oldCanvas;
  3732. //create a new canvas
  3733. var newCanvas = document.createElement('canvas');
  3734. var context = newCanvas.getContext('2d');
  3735. //set dimensions
  3736. newCanvas.width = oldCanvas.width;
  3737. newCanvas.height = oldCanvas.height;
  3738. //apply the old canvas to the new one
  3739. context.drawImage(oldCanvas, 0, 0);
  3740. //return the new canvas
  3741. return newCanvas;
  3742. };
  3743. return my;
  3744. })(CanvasUtil || {});
  3745. module.exports = CanvasUtil;
  3746. },{}],14:[function(require,module,exports){
  3747. /* global $, APP*/
  3748. var LoginDialog = require('./LoginDialog');
  3749. var Moderator = require('../../xmpp/moderator');
  3750. /* Initial "authentication required" dialog */
  3751. var authDialog = null;
  3752. /* Loop retry ID that wits for other user to create the room */
  3753. var authRetryId = null;
  3754. var authenticationWindow = null;
  3755. var Authentication = {
  3756. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3757. // This is the loop that will wait for the room to be created by
  3758. // someone else. 'auth_required.moderator' will bring us back here.
  3759. authRetryId = window.setTimeout(intervalCallback, 5000);
  3760. // Show prompt only if it's not open
  3761. if (authDialog !== null) {
  3762. return;
  3763. }
  3764. // extract room name from 'room@muc.server.net'
  3765. var room = roomName.substr(0, roomName.indexOf('@'));
  3766. var title
  3767. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3768. var msg
  3769. = APP.translation.generateTranslationHTML(
  3770. "dialog.WaitForHostMsg", {room: room});
  3771. var buttonTxt
  3772. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3773. var buttons = [];
  3774. buttons.push({title: buttonTxt, value: "authNow"});
  3775. authDialog = APP.UI.messageHandler.openDialog(
  3776. title,
  3777. msg,
  3778. true,
  3779. buttons,
  3780. function (onSubmitEvent, submitValue) {
  3781. // Do not close the dialog yet
  3782. onSubmitEvent.preventDefault();
  3783. // Open login popup
  3784. if (submitValue === 'authNow') {
  3785. callback();
  3786. }
  3787. }
  3788. );
  3789. },
  3790. closeAuthenticationWindow: function () {
  3791. if (authenticationWindow) {
  3792. authenticationWindow.close();
  3793. authenticationWindow = null;
  3794. }
  3795. },
  3796. xmppAuthenticate: function () {
  3797. var loginDialog = LoginDialog.show(
  3798. function (connection, state) {
  3799. if (!state) {
  3800. // User cancelled
  3801. loginDialog.close();
  3802. return;
  3803. } else if (state == APP.xmpp.Status.CONNECTED) {
  3804. loginDialog.close();
  3805. Authentication.stopInterval();
  3806. Authentication.closeAuthenticationDialog();
  3807. // Close the connection as anonymous one will be used
  3808. // to create the conference. Session-id will authorize
  3809. // the request.
  3810. connection.disconnect();
  3811. var roomName = APP.UI.generateRoomName();
  3812. Moderator.allocateConferenceFocus(roomName, function () {
  3813. // If it's not "on the fly" authentication now join
  3814. // the conference room
  3815. if (!APP.xmpp.getMUCJoined()) {
  3816. APP.UI.checkForNicknameAndJoin();
  3817. }
  3818. });
  3819. }
  3820. }, true);
  3821. },
  3822. focusAuthenticationWindow: function () {
  3823. // If auth window exists just bring it to the front
  3824. if (authenticationWindow) {
  3825. authenticationWindow.focus();
  3826. return;
  3827. }
  3828. },
  3829. closeAuthenticationDialog: function () {
  3830. // Close authentication dialog if opened
  3831. if (authDialog) {
  3832. authDialog.close();
  3833. authDialog = null;
  3834. }
  3835. },
  3836. createAuthenticationWindow: function (callback, url) {
  3837. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3838. url, 910, 660,
  3839. // On closed
  3840. function () {
  3841. // Close authentication dialog if opened
  3842. Authentication.closeAuthenticationDialog();
  3843. callback();
  3844. authenticationWindow = null;
  3845. });
  3846. return authenticationWindow;
  3847. },
  3848. stopInterval: function () {
  3849. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3850. if (authRetryId) {
  3851. window.clearTimeout(authRetryId);
  3852. authRetryId = null;
  3853. }
  3854. }
  3855. };
  3856. module.exports = Authentication;
  3857. },{"../../xmpp/moderator":58,"./LoginDialog":15}],15:[function(require,module,exports){
  3858. /* global $, APP, config*/
  3859. var XMPP = require('../../xmpp/xmpp');
  3860. var Moderator = require('../../xmpp/moderator');
  3861. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3862. // anonymous domain is not enabled
  3863. /**
  3864. * Creates new <tt>Dialog</tt> instance.
  3865. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3866. * when we either fail to connect or succeed(check Strophe.Status).
  3867. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3868. * in order to create session-id after the connection is established.
  3869. * @constructor
  3870. */
  3871. function Dialog(callback, obtainSession) {
  3872. var self = this;
  3873. var stop = false;
  3874. var connection = APP.xmpp.createConnection();
  3875. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3876. message += APP.translation.translateString("dialog.passwordRequired");
  3877. message += '</h2>' +
  3878. '<input name="username" type="text" ' +
  3879. 'placeholder="user@domain.net" autofocus>' +
  3880. '<input name="password" ' +
  3881. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3882. ' placeholder="user password">';
  3883. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3884. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3885. var states = {
  3886. login: {
  3887. html: message,
  3888. buttons: [
  3889. { title: okButton, value: true},
  3890. { title: cancelButton, value: false}
  3891. ],
  3892. focus: ':input:first',
  3893. submit: function (e, v, m, f) {
  3894. e.preventDefault();
  3895. if (v) {
  3896. var jid = f.username;
  3897. var password = f.password;
  3898. if (jid && password) {
  3899. stop = false;
  3900. connection.reset();
  3901. connDialog.goToState('connecting');
  3902. connection.connect(jid, password, stateHandler);
  3903. }
  3904. } else {
  3905. // User cancelled
  3906. stop = true;
  3907. callback();
  3908. }
  3909. }
  3910. },
  3911. connecting: {
  3912. title: APP.translation.translateString('dialog.connecting'),
  3913. html: '<div id="connectionStatus"></div>',
  3914. buttons: [],
  3915. defaultButton: 0
  3916. },
  3917. finished: {
  3918. title: APP.translation.translateString('dialog.error'),
  3919. html: '<div id="errorMessage"></div>',
  3920. buttons: [
  3921. {
  3922. title: APP.translation.translateString('dialog.retry'),
  3923. value: 'retry'
  3924. },
  3925. {
  3926. title: APP.translation.translateString('dialog.Cancel'),
  3927. value: 'cancel'
  3928. },
  3929. ],
  3930. defaultButton: 0,
  3931. submit: function (e, v, m, f) {
  3932. e.preventDefault();
  3933. if (v === 'retry')
  3934. connDialog.goToState('login');
  3935. else
  3936. callback();
  3937. }
  3938. }
  3939. };
  3940. var connDialog
  3941. = APP.UI.messageHandler.openDialogWithStates(states,
  3942. { persistent: true, closeText: '' }, null);
  3943. var stateHandler = function (status, message) {
  3944. if (stop) {
  3945. return;
  3946. }
  3947. var translateKey = "connection." + XMPP.getStatusString(status);
  3948. var statusStr = APP.translation.translateString(translateKey);
  3949. // Display current state
  3950. var connectionStatus =
  3951. connDialog.getState('connecting').find('#connectionStatus');
  3952. connectionStatus.text(statusStr);
  3953. switch (status) {
  3954. case XMPP.Status.CONNECTED:
  3955. stop = true;
  3956. if (!obtainSession) {
  3957. callback(connection, status);
  3958. return;
  3959. }
  3960. // Obtaining session-id status
  3961. connectionStatus.text(
  3962. APP.translation.translateString(
  3963. 'connection.FETCH_SESSION_ID'));
  3964. // Authenticate with Jicofo and obtain session-id
  3965. var roomName = APP.UI.generateRoomName();
  3966. // Jicofo will return new session-id when connected
  3967. // from authenticated domain
  3968. connection.sendIQ(
  3969. Moderator.createConferenceIq(roomName),
  3970. function (result) {
  3971. connectionStatus.text(
  3972. APP.translation.translateString(
  3973. 'connection.GOT_SESSION_ID'));
  3974. stop = true;
  3975. // Parse session-id
  3976. Moderator.parseSessionId(result);
  3977. callback(connection, status);
  3978. },
  3979. function (error) {
  3980. console.error("Auth on the fly failed", error);
  3981. stop = true;
  3982. var errorMsg =
  3983. APP.translation.translateString(
  3984. 'connection.GET_SESSION_ID_ERROR') +
  3985. $(error).find('>error').attr('code');
  3986. self.displayError(errorMsg);
  3987. connection.disconnect();
  3988. });
  3989. break;
  3990. case XMPP.Status.AUTHFAIL:
  3991. case XMPP.Status.CONNFAIL:
  3992. case XMPP.Status.DISCONNECTED:
  3993. stop = true;
  3994. callback(connection, status);
  3995. var errorMessage = statusStr;
  3996. if (message)
  3997. {
  3998. errorMessage += ': ' + message;
  3999. }
  4000. self.displayError(errorMessage);
  4001. break;
  4002. default:
  4003. break;
  4004. }
  4005. };
  4006. /**
  4007. * Displays error message in 'finished' state which allows either to cancel
  4008. * or retry.
  4009. * @param message the final message to be displayed.
  4010. */
  4011. this.displayError = function (message) {
  4012. var finishedState = connDialog.getState('finished');
  4013. var errorMessageElem = finishedState.find('#errorMessage');
  4014. errorMessageElem.text(message);
  4015. connDialog.goToState('finished');
  4016. };
  4017. /**
  4018. * Closes LoginDialog.
  4019. */
  4020. this.close = function () {
  4021. stop = true;
  4022. connDialog.close();
  4023. };
  4024. }
  4025. var LoginDialog = {
  4026. /**
  4027. * Displays login prompt used to establish new XMPP connection. Given
  4028. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4029. * called when we connect successfully(status === CONNECTED) or when we fail
  4030. * to do so. On connection failure program can call Dialog.close() method in
  4031. * order to cancel or do nothing to let the user retry.
  4032. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4033. * called when we either fail to connect or succeed(check
  4034. * Strophe.Status).
  4035. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4036. * Jicofo in order to create session-id after the connection is
  4037. * established.
  4038. * @returns {Dialog}
  4039. */
  4040. show: function (callback, obtainSession) {
  4041. return new Dialog(callback, obtainSession);
  4042. }
  4043. };
  4044. module.exports = LoginDialog;
  4045. },{"../../xmpp/moderator":58,"../../xmpp/xmpp":66}],16:[function(require,module,exports){
  4046. var Settings = require("../../settings/Settings");
  4047. var users = {};
  4048. var Avatar = {
  4049. /**
  4050. * Sets the user's avatar in the settings menu(if local user), contact list
  4051. * and thumbnail
  4052. * @param jid jid of the user
  4053. * @param id email or userID to be used as a hash
  4054. */
  4055. setUserAvatar: function (jid, id) {
  4056. if (id) {
  4057. if (users[jid] === id) {
  4058. return;
  4059. }
  4060. users[jid] = id;
  4061. }
  4062. var thumbUrl = this.getThumbUrl(jid);
  4063. var contactListUrl = this.getContactListUrl(jid);
  4064. var resourceJid = Strophe.getResourceFromJid(jid);
  4065. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4066. },
  4067. /**
  4068. * Returns image URL for the avatar to be displayed on large video area
  4069. * where current active speaker is presented.
  4070. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4071. */
  4072. getActiveSpeakerUrl: function (jid) {
  4073. return this.getGravatarUrl(jid, 100);
  4074. },
  4075. /**
  4076. * Returns image URL for the avatar to be displayed on small video thumbnail
  4077. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4078. */
  4079. getThumbUrl: function (jid) {
  4080. return this.getGravatarUrl(jid, 100);
  4081. },
  4082. /**
  4083. * Returns the URL for the avatar to be displayed as contactlist item
  4084. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4085. */
  4086. getContactListUrl: function (jid) {
  4087. return this.getGravatarUrl(jid, 30);
  4088. },
  4089. getGravatarUrl: function (jid, size) {
  4090. if (!jid) {
  4091. console.error("Get gravatar - jid is undefined");
  4092. return null;
  4093. }
  4094. var id = users[jid];
  4095. if (!id) {
  4096. console.warn("No avatar stored yet for " + jid);
  4097. return null;
  4098. }
  4099. return 'https://www.gravatar.com/avatar/' +
  4100. MD5.hexdigest(id.trim().toLowerCase()) +
  4101. "?d=wavatar&size=" + (size || "30");
  4102. }
  4103. };
  4104. module.exports = Avatar;
  4105. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4106. /* global $, config,
  4107. setLargeVideoVisible, Util */
  4108. var VideoLayout = require("../videolayout/VideoLayout");
  4109. var Prezi = require("../prezi/Prezi");
  4110. var UIUtil = require("../util/UIUtil");
  4111. var etherpadName = null;
  4112. var etherpadIFrame = null;
  4113. var domain = null;
  4114. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4115. /**
  4116. * Resizes the etherpad.
  4117. */
  4118. function resize() {
  4119. if ($('#etherpad>iframe').length) {
  4120. var remoteVideos = $('#remoteVideos');
  4121. var availableHeight
  4122. = window.innerHeight - remoteVideos.outerHeight();
  4123. var availableWidth = UIUtil.getAvailableVideoWidth();
  4124. $('#etherpad>iframe').width(availableWidth);
  4125. $('#etherpad>iframe').height(availableHeight);
  4126. }
  4127. }
  4128. /**
  4129. * Creates the Etherpad button and adds it to the toolbar.
  4130. */
  4131. function enableEtherpadButton() {
  4132. if (!$('#etherpadButton').is(":visible"))
  4133. $('#etherpadButton').css({display: 'inline-block'});
  4134. }
  4135. /**
  4136. * Creates the IFrame for the etherpad.
  4137. */
  4138. function createIFrame() {
  4139. etherpadIFrame = document.createElement('iframe');
  4140. etherpadIFrame.src = domain + etherpadName + options;
  4141. etherpadIFrame.frameBorder = 0;
  4142. etherpadIFrame.scrolling = "no";
  4143. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  4144. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  4145. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  4146. document.getElementById('etherpad').appendChild(etherpadIFrame);
  4147. etherpadIFrame.onload = function() {
  4148. document.domain = document.domain;
  4149. bubbleIframeMouseMove(etherpadIFrame);
  4150. setTimeout(function() {
  4151. // the iframes inside of the etherpad are
  4152. // not yet loaded when the etherpad iframe is loaded
  4153. var outer = etherpadIFrame.
  4154. contentDocument.getElementsByName("ace_outer")[0];
  4155. bubbleIframeMouseMove(outer);
  4156. var inner = outer.
  4157. contentDocument.getElementsByName("ace_inner")[0];
  4158. bubbleIframeMouseMove(inner);
  4159. }, 2000);
  4160. };
  4161. }
  4162. function bubbleIframeMouseMove(iframe){
  4163. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4164. iframe.contentWindow.onmousemove = function(e){
  4165. if(existingOnMouseMove) existingOnMouseMove(e);
  4166. var evt = document.createEvent("MouseEvents");
  4167. var boundingClientRect = iframe.getBoundingClientRect();
  4168. evt.initMouseEvent(
  4169. "mousemove",
  4170. true, // bubbles
  4171. false, // not cancelable
  4172. window,
  4173. e.detail,
  4174. e.screenX,
  4175. e.screenY,
  4176. e.clientX + boundingClientRect.left,
  4177. e.clientY + boundingClientRect.top,
  4178. e.ctrlKey,
  4179. e.altKey,
  4180. e.shiftKey,
  4181. e.metaKey,
  4182. e.button,
  4183. null // no related element
  4184. );
  4185. iframe.dispatchEvent(evt);
  4186. };
  4187. }
  4188. /**
  4189. * On video selected event.
  4190. */
  4191. $(document).bind('video.selected', function (event, isPresentation) {
  4192. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  4193. Etherpad.toggleEtherpad(isPresentation);
  4194. });
  4195. var Etherpad = {
  4196. /**
  4197. * Initializes the etherpad.
  4198. */
  4199. init: function (name) {
  4200. if (config.etherpad_base && !etherpadName && name) {
  4201. domain = config.etherpad_base;
  4202. etherpadName = name;
  4203. enableEtherpadButton();
  4204. /**
  4205. * Resizes the etherpad, when the window is resized.
  4206. */
  4207. $(window).resize(function () {
  4208. resize();
  4209. });
  4210. }
  4211. },
  4212. /**
  4213. * Opens/hides the Etherpad.
  4214. */
  4215. toggleEtherpad: function (isPresentation) {
  4216. if (!etherpadIFrame)
  4217. createIFrame();
  4218. var largeVideo = null;
  4219. if (Prezi.isPresentationVisible())
  4220. largeVideo = $('#presentation>iframe');
  4221. else
  4222. largeVideo = $('#largeVideo');
  4223. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  4224. $('#activeSpeaker').css('visibility', 'hidden');
  4225. largeVideo.fadeOut(300, function () {
  4226. if (Prezi.isPresentationVisible()) {
  4227. largeVideo.css({opacity: '0'});
  4228. } else {
  4229. VideoLayout.setLargeVideoVisible(false);
  4230. }
  4231. });
  4232. $('#etherpad>iframe').fadeIn(300, function () {
  4233. document.body.style.background = '#eeeeee';
  4234. $('#etherpad>iframe').css({visibility: 'visible'});
  4235. $('#etherpad').css({zIndex: 2});
  4236. });
  4237. }
  4238. else if ($('#etherpad>iframe')) {
  4239. $('#etherpad>iframe').fadeOut(300, function () {
  4240. $('#etherpad>iframe').css({visibility: 'hidden'});
  4241. $('#etherpad').css({zIndex: 0});
  4242. document.body.style.background = 'black';
  4243. });
  4244. if (!isPresentation) {
  4245. $('#largeVideo').fadeIn(300, function () {
  4246. VideoLayout.setLargeVideoVisible(true);
  4247. });
  4248. }
  4249. }
  4250. resize();
  4251. },
  4252. isVisible: function() {
  4253. var etherpadIframe = $('#etherpad>iframe');
  4254. return etherpadIframe && etherpadIframe.is(':visible');
  4255. }
  4256. };
  4257. module.exports = Etherpad;
  4258. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4259. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4260. var UIUtil = require("../util/UIUtil");
  4261. var VideoLayout = require("../videolayout/VideoLayout");
  4262. var messageHandler = require("../util/MessageHandler");
  4263. var PreziPlayer = require("./PreziPlayer");
  4264. var preziPlayer = null;
  4265. var Prezi = {
  4266. /**
  4267. * Reloads the current presentation.
  4268. */
  4269. reloadPresentation: function() {
  4270. var iframe = document.getElementById(preziPlayer.options.preziId);
  4271. iframe.src = iframe.src;
  4272. },
  4273. /**
  4274. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4275. * otherwise.
  4276. */
  4277. isPresentationVisible: function () {
  4278. return ($('#presentation>iframe') != null
  4279. && $('#presentation>iframe').css('opacity') == 1);
  4280. },
  4281. /**
  4282. * Opens the Prezi dialog, from which the user could choose a presentation
  4283. * to load.
  4284. */
  4285. openPreziDialog: function() {
  4286. var myprezi = APP.xmpp.getPrezi();
  4287. if (myprezi) {
  4288. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4289. null,
  4290. "dialog.removePreziMsg",
  4291. null,
  4292. false,
  4293. "dialog.Remove",
  4294. function(e,v,m,f) {
  4295. if(v) {
  4296. APP.xmpp.removePreziFromPresence();
  4297. }
  4298. }
  4299. );
  4300. }
  4301. else if (preziPlayer != null) {
  4302. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4303. null, "dialog.sharePreziMsg",
  4304. null,
  4305. false,
  4306. "dialog.Ok",
  4307. function(e,v,m,f) {
  4308. $.prompt.close();
  4309. }
  4310. );
  4311. }
  4312. else {
  4313. var html = APP.translation.generateTranslationHTML(
  4314. "dialog.sharePreziTitle");
  4315. var cancelButton = APP.translation.generateTranslationHTML(
  4316. "dialog.Cancel");
  4317. var shareButton = APP.translation.generateTranslationHTML(
  4318. "dialog.Share");
  4319. var backButton = APP.translation.generateTranslationHTML(
  4320. "dialog.Back");
  4321. var buttons = [];
  4322. var buttons1 = [];
  4323. // Cancel button to both states
  4324. buttons.push({title: cancelButton, value: false});
  4325. buttons1.push({title: cancelButton, value: false});
  4326. // Share button
  4327. buttons.push({title: shareButton, value: true});
  4328. // Back button
  4329. buttons1.push({title: backButton, value: true});
  4330. var linkError = APP.translation.generateTranslationHTML(
  4331. "dialog.preziLinkError");
  4332. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4333. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4334. var openPreziState = {
  4335. state0: {
  4336. html: '<h2>' + html + '</h2>' +
  4337. '<input name="preziUrl" type="text" ' +
  4338. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4339. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4340. '\' placeholder="' + defaultUrl + '" autofocus>',
  4341. persistent: false,
  4342. buttons: buttons,
  4343. focus: ':input:first',
  4344. defaultButton: 0,
  4345. submit: function (e, v, m, f) {
  4346. e.preventDefault();
  4347. if(v)
  4348. {
  4349. var preziUrl = f.preziUrl;
  4350. if (preziUrl)
  4351. {
  4352. var urlValue
  4353. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4354. if (urlValue.indexOf('http://prezi.com/') != 0
  4355. && urlValue.indexOf('https://prezi.com/') != 0)
  4356. {
  4357. $.prompt.goToState('state1');
  4358. return false;
  4359. }
  4360. else {
  4361. var presIdTmp = urlValue.substring(
  4362. urlValue.indexOf("prezi.com/") + 10);
  4363. if (!isAlphanumeric(presIdTmp)
  4364. || presIdTmp.indexOf('/') < 2) {
  4365. $.prompt.goToState('state1');
  4366. return false;
  4367. }
  4368. else {
  4369. APP.xmpp.addToPresence("prezi", urlValue);
  4370. $.prompt.close();
  4371. }
  4372. }
  4373. }
  4374. }
  4375. else
  4376. $.prompt.close();
  4377. }
  4378. },
  4379. state1: {
  4380. html: '<h2>' + html + '</h2>' +
  4381. linkError,
  4382. persistent: false,
  4383. buttons: buttons1,
  4384. focus: ':input:first',
  4385. defaultButton: 1,
  4386. submit: function (e, v, m, f) {
  4387. e.preventDefault();
  4388. if (v === 0)
  4389. $.prompt.close();
  4390. else
  4391. $.prompt.goToState('state0');
  4392. }
  4393. }
  4394. };
  4395. messageHandler.openDialogWithStates(openPreziState);
  4396. }
  4397. }
  4398. };
  4399. /**
  4400. * A new presentation has been added.
  4401. *
  4402. * @param event the event indicating the add of a presentation
  4403. * @param jid the jid from which the presentation was added
  4404. * @param presUrl url of the presentation
  4405. * @param currentSlide the current slide to which we should move
  4406. */
  4407. function presentationAdded(event, jid, presUrl, currentSlide) {
  4408. console.log("presentation added", presUrl);
  4409. var presId = getPresentationId(presUrl);
  4410. var elementId = 'participant_'
  4411. + Strophe.getResourceFromJid(jid)
  4412. + '_' + presId;
  4413. VideoLayout.addPreziContainer(elementId);
  4414. VideoLayout.resizeThumbnails();
  4415. var controlsEnabled = false;
  4416. if (jid === APP.xmpp.myJid())
  4417. controlsEnabled = true;
  4418. setPresentationVisible(true);
  4419. $('#largeVideoContainer').hover(
  4420. function (event) {
  4421. if (Prezi.isPresentationVisible()) {
  4422. var reloadButtonRight = window.innerWidth
  4423. - $('#presentation>iframe').offset().left
  4424. - $('#presentation>iframe').width();
  4425. $('#reloadPresentation').css({ right: reloadButtonRight,
  4426. display:'inline-block'});
  4427. }
  4428. },
  4429. function (event) {
  4430. if (!Prezi.isPresentationVisible())
  4431. $('#reloadPresentation').css({display:'none'});
  4432. else {
  4433. var e = event.toElement || event.relatedTarget;
  4434. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4435. $('#reloadPresentation').css({display:'none'});
  4436. }
  4437. });
  4438. preziPlayer = new PreziPlayer(
  4439. 'presentation',
  4440. {preziId: presId,
  4441. width: getPresentationWidth(),
  4442. height: getPresentationHeihgt(),
  4443. controls: controlsEnabled,
  4444. debug: true
  4445. });
  4446. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4447. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4448. console.log("prezi status", event.value);
  4449. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4450. if (jid != APP.xmpp.myJid())
  4451. preziPlayer.flyToStep(currentSlide);
  4452. }
  4453. });
  4454. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4455. console.log("event value", event.value);
  4456. APP.xmpp.addToPresence("preziSlide", event.value);
  4457. });
  4458. $("#" + elementId).css( 'background-image',
  4459. 'url(../images/avatarprezi.png)');
  4460. $("#" + elementId).click(
  4461. function () {
  4462. setPresentationVisible(true);
  4463. }
  4464. );
  4465. };
  4466. /**
  4467. * A presentation has been removed.
  4468. *
  4469. * @param event the event indicating the remove of a presentation
  4470. * @param jid the jid for which the presentation was removed
  4471. * @param the url of the presentation
  4472. */
  4473. function presentationRemoved(event, jid, presUrl) {
  4474. console.log('presentation removed', presUrl);
  4475. var presId = getPresentationId(presUrl);
  4476. setPresentationVisible(false);
  4477. $('#participant_'
  4478. + Strophe.getResourceFromJid(jid)
  4479. + '_' + presId).remove();
  4480. $('#presentation>iframe').remove();
  4481. if (preziPlayer != null) {
  4482. preziPlayer.destroy();
  4483. preziPlayer = null;
  4484. }
  4485. };
  4486. /**
  4487. * Indicates if the given string is an alphanumeric string.
  4488. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4489. * purpose of checking URIs.
  4490. */
  4491. function isAlphanumeric(unsafeText) {
  4492. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4493. return regex.test(unsafeText);
  4494. }
  4495. /**
  4496. * Returns the presentation id from the given url.
  4497. */
  4498. function getPresentationId (presUrl) {
  4499. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4500. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4501. }
  4502. /**
  4503. * Returns the presentation width.
  4504. */
  4505. function getPresentationWidth() {
  4506. var availableWidth = UIUtil.getAvailableVideoWidth();
  4507. var availableHeight = getPresentationHeihgt();
  4508. var aspectRatio = 16.0 / 9.0;
  4509. if (availableHeight < availableWidth / aspectRatio) {
  4510. availableWidth = Math.floor(availableHeight * aspectRatio);
  4511. }
  4512. return availableWidth;
  4513. }
  4514. /**
  4515. * Returns the presentation height.
  4516. */
  4517. function getPresentationHeihgt() {
  4518. var remoteVideos = $('#remoteVideos');
  4519. return window.innerHeight - remoteVideos.outerHeight();
  4520. }
  4521. /**
  4522. * Resizes the presentation iframe.
  4523. */
  4524. function resize() {
  4525. if ($('#presentation>iframe')) {
  4526. $('#presentation>iframe').width(getPresentationWidth());
  4527. $('#presentation>iframe').height(getPresentationHeihgt());
  4528. }
  4529. }
  4530. /**
  4531. * Shows/hides a presentation.
  4532. */
  4533. function setPresentationVisible(visible) {
  4534. var prezi = $('#presentation>iframe');
  4535. if (visible) {
  4536. // Trigger the video.selected event to indicate a change in the
  4537. // large video.
  4538. $(document).trigger("video.selected", [true]);
  4539. $('#largeVideo').fadeOut(300);
  4540. prezi.fadeIn(300, function() {
  4541. prezi.css({opacity:'1'});
  4542. ToolbarToggler.dockToolbar(true);
  4543. VideoLayout.setLargeVideoVisible(false);
  4544. });
  4545. $('#activeSpeaker').css('visibility', 'hidden');
  4546. }
  4547. else {
  4548. if (prezi.css('opacity') == '1') {
  4549. prezi.fadeOut(300, function () {
  4550. prezi.css({opacity:'0'});
  4551. $('#reloadPresentation').css({display:'none'});
  4552. $('#largeVideo').fadeIn(300, function() {
  4553. VideoLayout.setLargeVideoVisible(true);
  4554. ToolbarToggler.dockToolbar(false);
  4555. });
  4556. });
  4557. }
  4558. }
  4559. }
  4560. /**
  4561. * Presentation has been removed.
  4562. */
  4563. $(document).bind('presentationremoved.muc', presentationRemoved);
  4564. /**
  4565. * Presentation has been added.
  4566. */
  4567. $(document).bind('presentationadded.muc', presentationAdded);
  4568. /*
  4569. * Indicates presentation slide change.
  4570. */
  4571. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4572. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4573. preziPlayer.flyToStep(current);
  4574. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4575. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4576. preziPlayer.flyToStep(current, i);
  4577. }
  4578. }
  4579. });
  4580. /**
  4581. * On video selected event.
  4582. */
  4583. $(document).bind('video.selected', function (event, isPresentation) {
  4584. if (!isPresentation && $('#presentation>iframe')) {
  4585. setPresentationVisible(false);
  4586. }
  4587. });
  4588. $(window).resize(function () {
  4589. resize();
  4590. });
  4591. module.exports = Prezi;
  4592. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4593. (function() {
  4594. "use strict";
  4595. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4596. window.PreziPlayer = (function() {
  4597. PreziPlayer.API_VERSION = 1;
  4598. PreziPlayer.CURRENT_STEP = 'currentStep';
  4599. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4600. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4601. PreziPlayer.STATUS_LOADING = 'loading';
  4602. PreziPlayer.STATUS_READY = 'ready';
  4603. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4604. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4605. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4606. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4607. PreziPlayer.EVENT_STATUS = "statusChange";
  4608. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4609. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4610. PreziPlayer.domain = "https://prezi.com";
  4611. PreziPlayer.path = "/player/";
  4612. PreziPlayer.players = {};
  4613. PreziPlayer.binded_methods = ['changesHandler'];
  4614. PreziPlayer.createMultiplePlayers = function(optionArray){
  4615. for(var i=0; i<optionArray.length; i++) {
  4616. var optionSet = optionArray[i];
  4617. new PreziPlayer(optionSet.id, optionSet);
  4618. };
  4619. };
  4620. PreziPlayer.messageReceived = function(event){
  4621. var message, item, player;
  4622. try {
  4623. message = JSON.parse(event.data);
  4624. if (message.id && (player = PreziPlayer.players[message.id])) {
  4625. if (player.options.debug === true) {
  4626. if (console && console.log)
  4627. console.log('received', message);
  4628. }
  4629. if (message.type === "changes") {
  4630. player.changesHandler(message);
  4631. }
  4632. for (var i = 0; i < player.callbacks.length; i++) {
  4633. item = player.callbacks[i];
  4634. if (item && message.type === item.event) {
  4635. item.callback(message);
  4636. }
  4637. }
  4638. }
  4639. } catch (e) { }
  4640. };
  4641. function PreziPlayer(id, options) {
  4642. var params, paramString = "", _this = this;
  4643. if (PreziPlayer.players[id]){
  4644. PreziPlayer.players[id].destroy();
  4645. }
  4646. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4647. var method_name = PreziPlayer.binded_methods[i];
  4648. _this[method_name] = __bind(_this[method_name], _this);
  4649. };
  4650. options = options || {};
  4651. this.options = options;
  4652. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4653. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4654. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4655. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4656. this.callbacks = [];
  4657. this.id = id;
  4658. this.embedTo = document.getElementById(id);
  4659. if (!this.embedTo) {
  4660. throw "The element id is not available.";
  4661. }
  4662. this.iframe = document.createElement('iframe');
  4663. params = [
  4664. { name: 'oid', value: options.preziId },
  4665. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4666. { name: 'controls', value: options.controls ? 1 : 0 }
  4667. ];
  4668. for(var i=0; i<params.length; i++) {
  4669. var param = params[i];
  4670. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4671. };
  4672. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4673. this.iframe.frameBorder = 0;
  4674. this.iframe.scrolling = "no";
  4675. this.iframe.width = options.width || 640;
  4676. this.iframe.height = options.height || 480;
  4677. this.embedTo.innerHTML = '';
  4678. // JITSI: IN CASE SOMETHING GOES WRONG.
  4679. try {
  4680. this.embedTo.appendChild(this.iframe);
  4681. }
  4682. catch (err) {
  4683. console.log("CATCH ERROR");
  4684. }
  4685. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4686. // crashes for us.
  4687. this.initPollInterval = setInterval(function(){
  4688. _this.sendMessage({'action': 'init'});
  4689. }, 500);
  4690. PreziPlayer.players[id] = this;
  4691. }
  4692. PreziPlayer.prototype.changesHandler = function(message) {
  4693. var key, value, j, item;
  4694. if (this.initPollInterval) {
  4695. clearInterval(this.initPollInterval);
  4696. this.initPollInterval = false;
  4697. }
  4698. for (key in message.data) {
  4699. if (message.data.hasOwnProperty(key)){
  4700. value = message.data[key];
  4701. this.values[key] = value;
  4702. for (j=0; j<this.callbacks.length; j++) {
  4703. item = this.callbacks[j];
  4704. if (item && item.event === key + "Change"){
  4705. item.callback({type: item.event, value: value});
  4706. }
  4707. }
  4708. }
  4709. }
  4710. };
  4711. PreziPlayer.prototype.destroy = function() {
  4712. if (this.initPollInterval) {
  4713. clearInterval(this.initPollInterval);
  4714. this.initPollInterval = false;
  4715. }
  4716. this.embedTo.innerHTML = '';
  4717. };
  4718. PreziPlayer.prototype.sendMessage = function(message) {
  4719. if (this.options.debug === true) {
  4720. if (console && console.log) console.log('sent', message);
  4721. }
  4722. message.version = PreziPlayer.API_VERSION;
  4723. message.id = this.id;
  4724. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4725. };
  4726. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4727. PreziPlayer.prototype.flyToNextStep = function() {
  4728. return this.sendMessage({
  4729. 'action': 'present',
  4730. 'data': ['moveToNextStep']
  4731. });
  4732. };
  4733. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4734. PreziPlayer.prototype.flyToPreviousStep = function() {
  4735. return this.sendMessage({
  4736. 'action': 'present',
  4737. 'data': ['moveToPrevStep']
  4738. });
  4739. };
  4740. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4741. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4742. var obj = this;
  4743. // check animation_step
  4744. if (animation_step > 0 &&
  4745. obj.values.animationCountOnSteps &&
  4746. obj.values.animationCountOnSteps[step] <= animation_step) {
  4747. animation_step = obj.values.animationCountOnSteps[step];
  4748. }
  4749. // jump to animation steps by calling flyToNextStep()
  4750. function doAnimationSteps() {
  4751. if (obj.values.isMoving == true) {
  4752. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4753. return;
  4754. }
  4755. while (animation_step-- > 0) {
  4756. obj.flyToNextStep(); // do the animation steps
  4757. }
  4758. }
  4759. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4760. // jump to the step
  4761. return this.sendMessage({
  4762. 'action': 'present',
  4763. 'data': ['moveToStep', step]
  4764. });
  4765. };
  4766. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4767. PreziPlayer.prototype.flyToObject = function(objectId) {
  4768. return this.sendMessage({
  4769. 'action': 'present',
  4770. 'data': ['moveToObject', objectId]
  4771. });
  4772. };
  4773. PreziPlayer.prototype.play = function(defaultDelay) {
  4774. return this.sendMessage({
  4775. 'action': 'present',
  4776. 'data': ['startAutoPlay', defaultDelay]
  4777. });
  4778. };
  4779. PreziPlayer.prototype.stop = function() {
  4780. return this.sendMessage({
  4781. 'action': 'present',
  4782. 'data': ['stopAutoPlay']
  4783. });
  4784. };
  4785. PreziPlayer.prototype.pause = function(defaultDelay) {
  4786. return this.sendMessage({
  4787. 'action': 'present',
  4788. 'data': ['pauseAutoPlay', defaultDelay]
  4789. });
  4790. };
  4791. PreziPlayer.prototype.getCurrentStep = function() {
  4792. return this.values.currentStep;
  4793. };
  4794. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4795. return this.values.currentAnimationStep;
  4796. };
  4797. PreziPlayer.prototype.getCurrentObject = function() {
  4798. return this.values.currentObject;
  4799. };
  4800. PreziPlayer.prototype.getStatus = function() {
  4801. return this.values.status;
  4802. };
  4803. PreziPlayer.prototype.isPlaying = function() {
  4804. return this.values.isAutoPlaying;
  4805. };
  4806. PreziPlayer.prototype.getStepCount = function() {
  4807. return this.values.stepCount;
  4808. };
  4809. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4810. return this.values.animationCountOnSteps;
  4811. };
  4812. PreziPlayer.prototype.getTitle = function() {
  4813. return this.values.title;
  4814. };
  4815. PreziPlayer.prototype.setDimensions = function(dims) {
  4816. for (var parameter in dims) {
  4817. this.iframe[parameter] = dims[parameter];
  4818. }
  4819. }
  4820. PreziPlayer.prototype.getDimensions = function() {
  4821. return {
  4822. width: parseInt(this.iframe.width, 10),
  4823. height: parseInt(this.iframe.height, 10)
  4824. }
  4825. }
  4826. PreziPlayer.prototype.on = function(event, callback) {
  4827. this.callbacks.push({
  4828. event: event,
  4829. callback: callback
  4830. });
  4831. };
  4832. PreziPlayer.prototype.off = function(event, callback) {
  4833. var j, item;
  4834. if (event === undefined) {
  4835. this.callbacks = [];
  4836. }
  4837. j = this.callbacks.length;
  4838. while (j--) {
  4839. item = this.callbacks[j];
  4840. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4841. this.callbacks.splice(j, 1);
  4842. }
  4843. }
  4844. };
  4845. if (window.addEventListener) {
  4846. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4847. } else {
  4848. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4849. }
  4850. return PreziPlayer;
  4851. })();
  4852. })();
  4853. module.exports = PreziPlayer;
  4854. },{}],20:[function(require,module,exports){
  4855. var Chat = require("./chat/Chat");
  4856. var ContactList = require("./contactlist/ContactList");
  4857. var Settings = require("./../../settings/Settings");
  4858. var SettingsMenu = require("./settings/SettingsMenu");
  4859. var VideoLayout = require("../videolayout/VideoLayout");
  4860. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4861. var UIUtil = require("../util/UIUtil");
  4862. var LargeVideo = require("../videolayout/LargeVideo");
  4863. /**
  4864. * Toggler for the chat, contact list, settings menu, etc..
  4865. */
  4866. var PanelToggler = (function(my) {
  4867. var currentlyOpen = null;
  4868. var buttons = {
  4869. '#chatspace': '#chatBottomButton',
  4870. '#contactlist': '#contactListButton',
  4871. '#settingsmenu': '#settingsButton'
  4872. };
  4873. /**
  4874. * Toggles the windows in the side panel
  4875. * @param object the window that should be shown
  4876. * @param selector the selector for the element containing the panel
  4877. * @param onOpenComplete function to be called when the panel is opened
  4878. * @param onOpen function to be called if the window is going to be opened
  4879. * @param onClose function to be called if the window is going to be closed
  4880. */
  4881. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4882. UIUtil.buttonClick(buttons[selector], "active");
  4883. if (object.isVisible()) {
  4884. $("#toast-container").animate({
  4885. right: '5px'
  4886. },
  4887. {
  4888. queue: false,
  4889. duration: 500
  4890. });
  4891. $(selector).hide("slide", {
  4892. direction: "right",
  4893. queue: false,
  4894. duration: 500
  4895. });
  4896. if(typeof onClose === "function") {
  4897. onClose();
  4898. }
  4899. currentlyOpen = null;
  4900. }
  4901. else {
  4902. // Undock the toolbar when the chat is shown and if we're in a
  4903. // video mode.
  4904. if (LargeVideo.isLargeVideoVisible()) {
  4905. ToolbarToggler.dockToolbar(false);
  4906. }
  4907. if(currentlyOpen) {
  4908. var current = $(currentlyOpen);
  4909. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4910. current.css('z-index', 4);
  4911. setTimeout(function () {
  4912. current.css('display', 'none');
  4913. current.css('z-index', 5);
  4914. }, 500);
  4915. }
  4916. $("#toast-container").animate({
  4917. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4918. },
  4919. {
  4920. queue: false,
  4921. duration: 500
  4922. });
  4923. $(selector).show("slide", {
  4924. direction: "right",
  4925. queue: false,
  4926. duration: 500,
  4927. complete: onOpenComplete
  4928. });
  4929. if(typeof onOpen === "function") {
  4930. onOpen();
  4931. }
  4932. currentlyOpen = selector;
  4933. }
  4934. };
  4935. /**
  4936. * Opens / closes the chat area.
  4937. */
  4938. my.toggleChat = function() {
  4939. var chatCompleteFunction = Chat.isVisible() ?
  4940. function() {} : function () {
  4941. Chat.scrollChatToBottom();
  4942. $('#chatspace').trigger('shown');
  4943. };
  4944. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4945. toggle(Chat,
  4946. '#chatspace',
  4947. function () {
  4948. // Request the focus in the nickname field or the chat input field.
  4949. if ($('#nickname').css('visibility') === 'visible') {
  4950. $('#nickinput').focus();
  4951. } else {
  4952. $('#usermsg').focus();
  4953. }
  4954. },
  4955. null,
  4956. Chat.resizeChat,
  4957. null);
  4958. };
  4959. /**
  4960. * Opens / closes the contact list area.
  4961. */
  4962. my.toggleContactList = function () {
  4963. var completeFunction = ContactList.isVisible() ?
  4964. function() {} : function () { $('#contactlist').trigger('shown');};
  4965. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4966. toggle(ContactList,
  4967. '#contactlist',
  4968. null,
  4969. function() {
  4970. ContactList.setVisualNotification(false);
  4971. },
  4972. null);
  4973. };
  4974. /**
  4975. * Opens / closes the settings menu
  4976. */
  4977. my.toggleSettingsMenu = function() {
  4978. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4979. toggle(SettingsMenu,
  4980. '#settingsmenu',
  4981. null,
  4982. function() {
  4983. var settings = Settings.getSettings();
  4984. $('#setDisplayName').get(0).value = settings.displayName;
  4985. $('#setEmail').get(0).value = settings.email;
  4986. },
  4987. null);
  4988. };
  4989. /**
  4990. * Returns the size of the side panel.
  4991. */
  4992. my.getPanelSize = function () {
  4993. var availableHeight = window.innerHeight;
  4994. var availableWidth = window.innerWidth;
  4995. var panelWidth = 200;
  4996. if (availableWidth * 0.2 < 200) {
  4997. panelWidth = availableWidth * 0.2;
  4998. }
  4999. return [panelWidth, availableHeight];
  5000. };
  5001. my.isVisible = function() {
  5002. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  5003. };
  5004. return my;
  5005. }(PanelToggler || {}));
  5006. module.exports = PanelToggler;
  5007. },{"../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){
  5008. /* global $, Util, nickname:true */
  5009. var Replacement = require("./Replacement");
  5010. var CommandsProcessor = require("./Commands");
  5011. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  5012. var smileys = require("./smileys.json").smileys;
  5013. var NicknameHandler = require("../../util/NicknameHandler");
  5014. var UIUtil = require("../../util/UIUtil");
  5015. var UIEvents = require("../../../../service/UI/UIEvents");
  5016. var notificationInterval = false;
  5017. var unreadMessages = 0;
  5018. /**
  5019. * Shows/hides a visual notification, indicating that a message has arrived.
  5020. */
  5021. function setVisualNotification(show) {
  5022. var unreadMsgElement = document.getElementById('unreadMessages');
  5023. var unreadMsgBottomElement
  5024. = document.getElementById('bottomUnreadMessages');
  5025. var glower = $('#chatButton');
  5026. var bottomGlower = $('#chatBottomButton');
  5027. if (unreadMessages) {
  5028. unreadMsgElement.innerHTML = unreadMessages.toString();
  5029. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  5030. ToolbarToggler.dockToolbar(true);
  5031. var chatButtonElement
  5032. = document.getElementById('chatButton').parentNode;
  5033. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  5034. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  5035. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  5036. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  5037. unreadMsgElement.setAttribute(
  5038. 'style',
  5039. 'top:' + topIndent +
  5040. '; left:' + leftIndent + ';');
  5041. var chatBottomButtonElement
  5042. = document.getElementById('chatBottomButton').parentNode;
  5043. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  5044. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  5045. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  5046. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5047. unreadMsgBottomElement.setAttribute(
  5048. 'style',
  5049. 'top:' + bottomTopIndent +
  5050. '; left:' + bottomLeftIndent + ';');
  5051. if (!glower.hasClass('icon-chat-simple')) {
  5052. glower.removeClass('icon-chat');
  5053. glower.addClass('icon-chat-simple');
  5054. }
  5055. }
  5056. else {
  5057. unreadMsgElement.innerHTML = '';
  5058. unreadMsgBottomElement.innerHTML = '';
  5059. glower.removeClass('icon-chat-simple');
  5060. glower.addClass('icon-chat');
  5061. }
  5062. if (show && !notificationInterval) {
  5063. notificationInterval = window.setInterval(function () {
  5064. glower.toggleClass('active');
  5065. bottomGlower.toggleClass('active glowing');
  5066. }, 800);
  5067. }
  5068. else if (!show && notificationInterval) {
  5069. window.clearInterval(notificationInterval);
  5070. notificationInterval = false;
  5071. glower.removeClass('active');
  5072. bottomGlower.removeClass('glowing');
  5073. bottomGlower.addClass('active');
  5074. }
  5075. }
  5076. /**
  5077. * Returns the current time in the format it is shown to the user
  5078. * @returns {string}
  5079. */
  5080. function getCurrentTime(stamp) {
  5081. var now = (stamp? new Date(stamp): new Date());
  5082. var hour = now.getHours();
  5083. var minute = now.getMinutes();
  5084. var second = now.getSeconds();
  5085. if(hour.toString().length === 1) {
  5086. hour = '0'+hour;
  5087. }
  5088. if(minute.toString().length === 1) {
  5089. minute = '0'+minute;
  5090. }
  5091. if(second.toString().length === 1) {
  5092. second = '0'+second;
  5093. }
  5094. return hour+':'+minute+':'+second;
  5095. }
  5096. function toggleSmileys()
  5097. {
  5098. var smileys = $('#smileysContainer');
  5099. if(!smileys.is(':visible')) {
  5100. smileys.show("slide", { direction: "down", duration: 300});
  5101. } else {
  5102. smileys.hide("slide", { direction: "down", duration: 300});
  5103. }
  5104. $('#usermsg').focus();
  5105. }
  5106. function addClickFunction(smiley, number) {
  5107. smiley.onclick = function addSmileyToMessage() {
  5108. var usermsg = $('#usermsg');
  5109. var message = usermsg.val();
  5110. message += smileys['smiley' + number];
  5111. usermsg.val(message);
  5112. usermsg.get(0).setSelectionRange(message.length, message.length);
  5113. toggleSmileys();
  5114. usermsg.focus();
  5115. };
  5116. }
  5117. /**
  5118. * Adds the smileys container to the chat
  5119. */
  5120. function addSmileys() {
  5121. var smileysContainer = document.createElement('div');
  5122. smileysContainer.id = 'smileysContainer';
  5123. for(var i = 1; i <= 21; i++) {
  5124. var smileyContainer = document.createElement('div');
  5125. smileyContainer.id = 'smiley' + i;
  5126. smileyContainer.className = 'smileyContainer';
  5127. var smiley = document.createElement('img');
  5128. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5129. smiley.className = 'smiley';
  5130. addClickFunction(smiley, i);
  5131. smileyContainer.appendChild(smiley);
  5132. smileysContainer.appendChild(smileyContainer);
  5133. }
  5134. $("#chatspace").append(smileysContainer);
  5135. }
  5136. /**
  5137. * Resizes the chat conversation.
  5138. */
  5139. function resizeChatConversation() {
  5140. var msgareaHeight = $('#usermsg').outerHeight();
  5141. var chatspace = $('#chatspace');
  5142. var width = chatspace.width();
  5143. var chat = $('#chatconversation');
  5144. var smileys = $('#smileysarea');
  5145. smileys.height(msgareaHeight);
  5146. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5147. $('#smileysContainer').css('bottom', msgareaHeight);
  5148. chat.width(width - 10);
  5149. chat.height(window.innerHeight - 15 - msgareaHeight);
  5150. }
  5151. /**
  5152. * Chat related user interface.
  5153. */
  5154. var Chat = (function (my) {
  5155. /**
  5156. * Initializes chat related interface.
  5157. */
  5158. my.init = function () {
  5159. if(NicknameHandler.getNickname())
  5160. Chat.setChatConversationMode(true);
  5161. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5162. function (nickname) {
  5163. Chat.setChatConversationMode(true);
  5164. });
  5165. $('#nickinput').keydown(function (event) {
  5166. if (event.keyCode === 13) {
  5167. event.preventDefault();
  5168. var val = UIUtil.escapeHtml(this.value);
  5169. this.value = '';
  5170. if (!NicknameHandler.getNickname()) {
  5171. NicknameHandler.setNickname(val);
  5172. return;
  5173. }
  5174. }
  5175. });
  5176. $('#usermsg').keydown(function (event) {
  5177. if (event.keyCode === 13) {
  5178. event.preventDefault();
  5179. var value = this.value;
  5180. $('#usermsg').val('').trigger('autosize.resize');
  5181. this.focus();
  5182. var command = new CommandsProcessor(value);
  5183. if(command.isCommand())
  5184. {
  5185. command.processCommand();
  5186. }
  5187. else
  5188. {
  5189. var message = UIUtil.escapeHtml(value);
  5190. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5191. }
  5192. }
  5193. });
  5194. var onTextAreaResize = function () {
  5195. resizeChatConversation();
  5196. Chat.scrollChatToBottom();
  5197. };
  5198. $('#usermsg').autosize({callback: onTextAreaResize});
  5199. $("#chatspace").bind("shown",
  5200. function () {
  5201. unreadMessages = 0;
  5202. setVisualNotification(false);
  5203. });
  5204. addSmileys();
  5205. };
  5206. /**
  5207. * Appends the given message to the chat conversation.
  5208. */
  5209. my.updateChatConversation = function (from, displayName, message, myjid, stamp) {
  5210. var divClassName = '';
  5211. if (APP.xmpp.myJid() === from) {
  5212. divClassName = "localuser";
  5213. }
  5214. else {
  5215. divClassName = "remoteuser";
  5216. if (!Chat.isVisible()) {
  5217. unreadMessages++;
  5218. UIUtil.playSoundNotification('chatNotification');
  5219. setVisualNotification(true);
  5220. }
  5221. }
  5222. // replace links and smileys
  5223. // Strophe already escapes special symbols on sending,
  5224. // so we escape here only tags to avoid double &amp;
  5225. var escMessage = message.replace(/</g, '&lt;').
  5226. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5227. var escDisplayName = UIUtil.escapeHtml(displayName);
  5228. message = Replacement.processReplacements(escMessage);
  5229. var messageContainer =
  5230. '<div class="chatmessage">'+
  5231. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5232. '<div class="username ' + divClassName +'">' + escDisplayName +
  5233. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5234. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5235. '</div>';
  5236. $('#chatconversation').append(messageContainer);
  5237. $('#chatconversation').animate(
  5238. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5239. };
  5240. /**
  5241. * Appends error message to the conversation
  5242. * @param errorMessage the received error message.
  5243. * @param originalText the original message.
  5244. */
  5245. my.chatAddError = function(errorMessage, originalText)
  5246. {
  5247. errorMessage = UIUtil.escapeHtml(errorMessage);
  5248. originalText = UIUtil.escapeHtml(originalText);
  5249. $('#chatconversation').append(
  5250. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5251. (originalText? (' \"'+ originalText + '\"') : "") +
  5252. ' was not sent.' +
  5253. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5254. $('#chatconversation').animate(
  5255. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5256. };
  5257. /**
  5258. * Sets the subject to the UI
  5259. * @param subject the subject
  5260. */
  5261. my.chatSetSubject = function(subject)
  5262. {
  5263. if(subject)
  5264. subject = subject.trim();
  5265. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5266. if(subject === "")
  5267. {
  5268. $("#subject").css({display: "none"});
  5269. }
  5270. else
  5271. {
  5272. $("#subject").css({display: "block"});
  5273. }
  5274. };
  5275. /**
  5276. * Sets the chat conversation mode.
  5277. */
  5278. my.setChatConversationMode = function (isConversationMode) {
  5279. if (isConversationMode) {
  5280. $('#nickname').css({visibility: 'hidden'});
  5281. $('#chatconversation').css({visibility: 'visible'});
  5282. $('#usermsg').css({visibility: 'visible'});
  5283. $('#smileysarea').css({visibility: 'visible'});
  5284. $('#usermsg').focus();
  5285. }
  5286. };
  5287. /**
  5288. * Resizes the chat area.
  5289. */
  5290. my.resizeChat = function () {
  5291. var chatSize = require("../SidePanelToggler").getPanelSize();
  5292. $('#chatspace').width(chatSize[0]);
  5293. $('#chatspace').height(chatSize[1]);
  5294. resizeChatConversation();
  5295. };
  5296. /**
  5297. * Indicates if the chat is currently visible.
  5298. */
  5299. my.isVisible = function () {
  5300. return $('#chatspace').is(":visible");
  5301. };
  5302. /**
  5303. * Shows and hides the window with the smileys
  5304. */
  5305. my.toggleSmileys = toggleSmileys;
  5306. /**
  5307. * Scrolls chat to the bottom.
  5308. */
  5309. my.scrollChatToBottom = function() {
  5310. setTimeout(function () {
  5311. $('#chatconversation').scrollTop(
  5312. $('#chatconversation')[0].scrollHeight);
  5313. }, 5);
  5314. };
  5315. return my;
  5316. }(Chat || {}));
  5317. module.exports = Chat;
  5318. },{"../../../../service/UI/UIEvents":102,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5319. var UIUtil = require("../../util/UIUtil");
  5320. /**
  5321. * List with supported commands. The keys are the names of the commands and
  5322. * the value is the function that processes the message.
  5323. * @type {{String: function}}
  5324. */
  5325. var commands = {
  5326. "topic" : processTopic
  5327. };
  5328. /**
  5329. * Extracts the command from the message.
  5330. * @param message the received message
  5331. * @returns {string} the command
  5332. */
  5333. function getCommand(message)
  5334. {
  5335. if(message)
  5336. {
  5337. for(var command in commands)
  5338. {
  5339. if(message.indexOf("/" + command) == 0)
  5340. return command;
  5341. }
  5342. }
  5343. return "";
  5344. };
  5345. /**
  5346. * Processes the data for topic command.
  5347. * @param commandArguments the arguments of the topic command.
  5348. */
  5349. function processTopic(commandArguments)
  5350. {
  5351. var topic = UIUtil.escapeHtml(commandArguments);
  5352. APP.xmpp.setSubject(topic);
  5353. }
  5354. /**
  5355. * Constructs new CommandProccessor instance from a message that
  5356. * handles commands received via chat messages.
  5357. * @param message the message
  5358. * @constructor
  5359. */
  5360. function CommandsProcessor(message)
  5361. {
  5362. var command = getCommand(message);
  5363. /**
  5364. * Returns the name of the command.
  5365. * @returns {String} the command
  5366. */
  5367. this.getCommand = function()
  5368. {
  5369. return command;
  5370. };
  5371. var messageArgument = message.substr(command.length + 2);
  5372. /**
  5373. * Returns the arguments of the command.
  5374. * @returns {string}
  5375. */
  5376. this.getArgument = function()
  5377. {
  5378. return messageArgument;
  5379. };
  5380. }
  5381. /**
  5382. * Checks whether this instance is valid command or not.
  5383. * @returns {boolean}
  5384. */
  5385. CommandsProcessor.prototype.isCommand = function()
  5386. {
  5387. if(this.getCommand())
  5388. return true;
  5389. return false;
  5390. };
  5391. /**
  5392. * Processes the command.
  5393. */
  5394. CommandsProcessor.prototype.processCommand = function()
  5395. {
  5396. if(!this.isCommand())
  5397. return;
  5398. commands[this.getCommand()](this.getArgument());
  5399. };
  5400. module.exports = CommandsProcessor;
  5401. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5402. var Smileys = require("./smileys.json");
  5403. /**
  5404. * Processes links and smileys in "body"
  5405. */
  5406. function processReplacements(body)
  5407. {
  5408. //make links clickable
  5409. body = linkify(body);
  5410. //add smileys
  5411. body = smilify(body);
  5412. return body;
  5413. }
  5414. /**
  5415. * Finds and replaces all links in the links in "body"
  5416. * with their <a href=""></a>
  5417. */
  5418. function linkify(inputText)
  5419. {
  5420. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5421. //URLs starting with http://, https://, or ftp://
  5422. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5423. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5424. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5425. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5426. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5427. //Change email addresses to mailto:: links.
  5428. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5429. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5430. return replacedText;
  5431. }
  5432. /**
  5433. * Replaces common smiley strings with images
  5434. */
  5435. function smilify(body)
  5436. {
  5437. if(!body) {
  5438. return body;
  5439. }
  5440. var regexs = Smileys["regexs"];
  5441. for(var smiley in regexs) {
  5442. if(regexs.hasOwnProperty(smiley)) {
  5443. body = body.replace(regexs[smiley],
  5444. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5445. }
  5446. }
  5447. return body;
  5448. }
  5449. module.exports = {
  5450. processReplacements: processReplacements,
  5451. linkify: linkify
  5452. };
  5453. },{"./smileys.json":24}],24:[function(require,module,exports){
  5454. module.exports={
  5455. "smileys": {
  5456. "smiley1": ":)",
  5457. "smiley2": ":(",
  5458. "smiley3": ":D",
  5459. "smiley4": "(y)",
  5460. "smiley5": " :P",
  5461. "smiley6": "(wave)",
  5462. "smiley7": "(blush)",
  5463. "smiley8": "(chuckle)",
  5464. "smiley9": "(shocked)",
  5465. "smiley10": ":*",
  5466. "smiley11": "(n)",
  5467. "smiley12": "(search)",
  5468. "smiley13": " <3",
  5469. "smiley14": "(oops)",
  5470. "smiley15": "(angry)",
  5471. "smiley16": "(angel)",
  5472. "smiley17": "(sick)",
  5473. "smiley18": ";(",
  5474. "smiley19": "(bomb)",
  5475. "smiley20": "(clap)",
  5476. "smiley21": " ;)"
  5477. },
  5478. "regexs": {
  5479. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5480. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5481. "smiley1": /(:-\)|:\))/gi,
  5482. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5483. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5484. "smiley6": /(\(wave\))/gi,
  5485. "smiley7": /(\(blush\))/gi,
  5486. "smiley8": /(\(chuckle\))/gi,
  5487. "smiley9": /(:-0|\(shocked\))/gi,
  5488. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5489. "smiley11": /(\(n\))/gi,
  5490. "smiley12": /(\(search\))/g,
  5491. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5492. "smiley14": /(\(oops\))/gi,
  5493. "smiley15": /(\(angry\))/gi,
  5494. "smiley16": /(\(angel\))/gi,
  5495. "smiley17": /(\(sick\))/gi,
  5496. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5497. "smiley19": /(\(bomb\))/gi,
  5498. "smiley20": /(\(clap\))/gi,
  5499. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5500. }
  5501. }
  5502. },{}],25:[function(require,module,exports){
  5503. var Avatar = require('../../avatar/Avatar');
  5504. var numberOfContacts = 0;
  5505. var notificationInterval;
  5506. /**
  5507. * Updates the number of participants in the contact list button and sets
  5508. * the glow
  5509. * @param delta indicates whether a new user has joined (1) or someone has
  5510. * left(-1)
  5511. */
  5512. function updateNumberOfParticipants(delta) {
  5513. numberOfContacts += delta;
  5514. if (numberOfContacts === 1) {
  5515. // when the user is alone we don't show the number of participants
  5516. $("#numberOfParticipants").text('');
  5517. ContactList.setVisualNotification(false);
  5518. } else if (numberOfContacts > 1) {
  5519. ContactList.setVisualNotification(!ContactList.isVisible());
  5520. $("#numberOfParticipants").text(numberOfContacts);
  5521. } else {
  5522. console.error("Invalid number of participants: " + numberOfContacts);
  5523. }
  5524. }
  5525. /**
  5526. * Creates the avatar element.
  5527. *
  5528. * @return the newly created avatar element
  5529. */
  5530. function createAvatar(jid) {
  5531. var avatar = document.createElement('img');
  5532. avatar.className = "icon-avatar avatar";
  5533. avatar.src = Avatar.getContactListUrl(jid);
  5534. return avatar;
  5535. }
  5536. /**
  5537. * Creates the display name paragraph.
  5538. *
  5539. * @param displayName the display name to set
  5540. */
  5541. function createDisplayNameParagraph(key, displayName) {
  5542. var p = document.createElement('p');
  5543. if(displayName)
  5544. p.innerText = displayName;
  5545. else if(key)
  5546. {
  5547. p.setAttribute("data-i18n",key);
  5548. p.innerText = APP.translation.translateString(key);
  5549. }
  5550. return p;
  5551. }
  5552. function stopGlowing(glower) {
  5553. window.clearInterval(notificationInterval);
  5554. notificationInterval = false;
  5555. glower.removeClass('glowing');
  5556. if (!ContactList.isVisible()) {
  5557. glower.removeClass('active');
  5558. }
  5559. }
  5560. /**
  5561. * Contact list.
  5562. */
  5563. var ContactList = {
  5564. /**
  5565. * Indicates if the chat is currently visible.
  5566. *
  5567. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5568. * otherwise
  5569. */
  5570. isVisible: function () {
  5571. return $('#contactlist').is(":visible");
  5572. },
  5573. /**
  5574. * Adds a contact for the given peerJid if such doesn't yet exist.
  5575. *
  5576. * @param peerJid the peerJid corresponding to the contact
  5577. */
  5578. ensureAddContact: function (peerJid) {
  5579. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5580. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5581. if (!contact || contact.length <= 0)
  5582. ContactList.addContact(peerJid);
  5583. },
  5584. /**
  5585. * Adds a contact for the given peer jid.
  5586. *
  5587. * @param peerJid the jid of the contact to add
  5588. */
  5589. addContact: function (peerJid) {
  5590. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5591. var contactlist = $('#contacts');
  5592. var newContact = document.createElement('li');
  5593. newContact.id = resourceJid;
  5594. newContact.className = "clickable";
  5595. newContact.onclick = function (event) {
  5596. if (event.currentTarget.className === "clickable") {
  5597. $(ContactList).trigger('contactclicked', [peerJid]);
  5598. }
  5599. };
  5600. newContact.appendChild(createAvatar(peerJid));
  5601. newContact.appendChild(createDisplayNameParagraph("participant"));
  5602. if (resourceJid === APP.xmpp.myResource()) {
  5603. contactlist.prepend(newContact);
  5604. }
  5605. else {
  5606. contactlist.append(newContact);
  5607. }
  5608. updateNumberOfParticipants(1);
  5609. },
  5610. /**
  5611. * Removes a contact for the given peer jid.
  5612. *
  5613. * @param peerJid the peerJid corresponding to the contact to remove
  5614. */
  5615. removeContact: function (peerJid) {
  5616. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5617. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5618. if (contact && contact.length > 0) {
  5619. var contactlist = $('#contactlist>ul');
  5620. contactlist.get(0).removeChild(contact.get(0));
  5621. updateNumberOfParticipants(-1);
  5622. }
  5623. },
  5624. setVisualNotification: function (show, stopGlowingIn) {
  5625. var glower = $('#contactListButton');
  5626. if (show && !notificationInterval) {
  5627. notificationInterval = window.setInterval(function () {
  5628. glower.toggleClass('active glowing');
  5629. }, 800);
  5630. }
  5631. else if (!show && notificationInterval) {
  5632. stopGlowing(glower);
  5633. }
  5634. if (stopGlowingIn) {
  5635. setTimeout(function () {
  5636. stopGlowing(glower);
  5637. }, stopGlowingIn);
  5638. }
  5639. },
  5640. setClickable: function (resourceJid, isClickable) {
  5641. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5642. if (isClickable) {
  5643. contact.addClass('clickable');
  5644. } else {
  5645. contact.removeClass('clickable');
  5646. }
  5647. },
  5648. onDisplayNameChange: function (peerJid, displayName) {
  5649. if (peerJid === 'localVideoContainer')
  5650. peerJid = APP.xmpp.myJid();
  5651. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5652. var contactName = $('#contacts #' + resourceJid + '>p');
  5653. if (contactName && displayName && displayName.length > 0)
  5654. contactName.html(displayName);
  5655. },
  5656. userAvatarChanged: function (resourceJid, contactListUrl) {
  5657. // set the avatar in the contact list
  5658. var contact = $('#' + resourceJid + '>img');
  5659. if (contact && contact.length > 0) {
  5660. contact.get(0).src = contactListUrl;
  5661. }
  5662. }
  5663. };
  5664. module.exports = ContactList;
  5665. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5666. var Avatar = require("../../avatar/Avatar");
  5667. var Settings = require("./../../../settings/Settings");
  5668. var UIUtil = require("../../util/UIUtil");
  5669. var languages = require("../../../../service/translation/languages");
  5670. function generateLanguagesSelectBox()
  5671. {
  5672. var currentLang = APP.translation.getCurrentLanguage();
  5673. var html = "<select id=\"languages_selectbox\">";
  5674. var langArray = languages.getLanguages();
  5675. for(var i = 0; i < langArray.length; i++)
  5676. {
  5677. var lang = langArray[i];
  5678. html += "<option ";
  5679. if(lang === currentLang)
  5680. html += "selected ";
  5681. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5682. html += "</option>";
  5683. }
  5684. return html + "</select>";
  5685. }
  5686. var SettingsMenu = {
  5687. init: function () {
  5688. $("#startMutedOptions").before(generateLanguagesSelectBox());
  5689. APP.translation.translateElement($("#languages_selectbox"));
  5690. $('#settingsmenu>input').keyup(function(event){
  5691. if(event.keyCode === 13) {//enter
  5692. SettingsMenu.update();
  5693. }
  5694. });
  5695. if(APP.xmpp.isModerator())
  5696. {
  5697. $("#startMutedOptions").css("display", "block");
  5698. }
  5699. else
  5700. {
  5701. $("#startMutedOptions").css("display", "none");
  5702. }
  5703. $("#updateSettings").click(function () {
  5704. SettingsMenu.update();
  5705. });
  5706. },
  5707. onRoleChanged: function () {
  5708. if(APP.xmpp.isModerator())
  5709. {
  5710. $("#startMutedOptions").css("display", "block");
  5711. }
  5712. else
  5713. {
  5714. $("#startMutedOptions").css("display", "none");
  5715. }
  5716. },
  5717. setStartMuted: function (audio, video) {
  5718. $("#startAudioMuted").attr("checked", audio);
  5719. $("#startVideoMuted").attr("checked", video);
  5720. },
  5721. update: function() {
  5722. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5723. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5724. if(newDisplayName) {
  5725. var displayName = Settings.setDisplayName(newDisplayName);
  5726. APP.xmpp.addToPresence("displayName", displayName, true);
  5727. }
  5728. var language = $("#languages_selectbox").val();
  5729. APP.translation.setLanguage(language);
  5730. Settings.setLanguage(language);
  5731. APP.xmpp.addToPresence("email", newEmail);
  5732. var email = Settings.setEmail(newEmail);
  5733. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5734. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5735. APP.xmpp.addToPresence("startMuted",
  5736. [startAudioMuted, startVideoMuted]);
  5737. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5738. },
  5739. isVisible: function() {
  5740. return $('#settingsmenu').is(':visible');
  5741. },
  5742. setDisplayName: function(newDisplayName) {
  5743. var displayName = Settings.setDisplayName(newDisplayName);
  5744. $('#setDisplayName').get(0).value = displayName;
  5745. },
  5746. onDisplayNameChange: function(peerJid, newDisplayName) {
  5747. if(peerJid === 'localVideoContainer' ||
  5748. peerJid === APP.xmpp.myJid()) {
  5749. this.setDisplayName(newDisplayName);
  5750. }
  5751. },
  5752. changeAvatar: function (thumbUrl) {
  5753. $('#avatar').get(0).src = thumbUrl;
  5754. }
  5755. };
  5756. module.exports = SettingsMenu;
  5757. },{"../../../../service/translation/languages":107,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5758. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5759. var buttonHandlers = {
  5760. "bottom_toolbar_contact_list": function () {
  5761. BottomToolbar.toggleContactList();
  5762. },
  5763. "bottom_toolbar_film_strip": function () {
  5764. BottomToolbar.toggleFilmStrip();
  5765. },
  5766. "bottom_toolbar_chat": function () {
  5767. BottomToolbar.toggleChat();
  5768. }
  5769. };
  5770. var BottomToolbar = (function (my) {
  5771. my.init = function () {
  5772. for(var k in buttonHandlers)
  5773. $("#" + k).click(buttonHandlers[k]);
  5774. };
  5775. my.toggleChat = function() {
  5776. PanelToggler.toggleChat();
  5777. };
  5778. my.toggleContactList = function() {
  5779. PanelToggler.toggleContactList();
  5780. };
  5781. my.toggleFilmStrip = function() {
  5782. var filmstrip = $("#remoteVideos");
  5783. filmstrip.toggleClass("hidden");
  5784. };
  5785. $(document).bind("remotevideo.resized", function (event, width, height) {
  5786. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5787. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5788. });
  5789. return my;
  5790. }(BottomToolbar || {}));
  5791. module.exports = BottomToolbar;
  5792. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5793. /* global APP,$, buttonClick, config, lockRoom,
  5794. setSharedKey, Util */
  5795. var messageHandler = require("../util/MessageHandler");
  5796. var BottomToolbar = require("./BottomToolbar");
  5797. var Prezi = require("../prezi/Prezi");
  5798. var Etherpad = require("../etherpad/Etherpad");
  5799. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5800. var Authentication = require("../authentication/Authentication");
  5801. var UIUtil = require("../util/UIUtil");
  5802. var AuthenticationEvents
  5803. = require("../../../service/authentication/AuthenticationEvents");
  5804. var roomUrl = null;
  5805. var sharedKey = '';
  5806. var UI = null;
  5807. var buttonHandlers =
  5808. {
  5809. "toolbar_button_mute": function () {
  5810. return APP.UI.toggleAudio();
  5811. },
  5812. "toolbar_button_camera": function () {
  5813. return APP.UI.toggleVideo();
  5814. },
  5815. /*"toolbar_button_authentication": function () {
  5816. return Toolbar.authenticateClicked();
  5817. },*/
  5818. "toolbar_button_record": function () {
  5819. return toggleRecording();
  5820. },
  5821. "toolbar_button_security": function () {
  5822. return Toolbar.openLockDialog();
  5823. },
  5824. "toolbar_button_link": function () {
  5825. return Toolbar.openLinkDialog();
  5826. },
  5827. "toolbar_button_chat": function () {
  5828. return BottomToolbar.toggleChat();
  5829. },
  5830. "toolbar_button_prezi": function () {
  5831. return Prezi.openPreziDialog();
  5832. },
  5833. "toolbar_button_etherpad": function () {
  5834. return Etherpad.toggleEtherpad(0);
  5835. },
  5836. "toolbar_button_desktopsharing": function () {
  5837. return APP.desktopsharing.toggleScreenSharing();
  5838. },
  5839. "toolbar_button_fullScreen": function()
  5840. {
  5841. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  5842. return Toolbar.toggleFullScreen();
  5843. },
  5844. "toolbar_button_sip": function () {
  5845. return callSipButtonClicked();
  5846. },
  5847. "toolbar_button_dialpad": function () {
  5848. return dialpadButtonClicked();
  5849. },
  5850. "toolbar_button_settings": function () {
  5851. PanelToggler.toggleSettingsMenu();
  5852. },
  5853. "toolbar_button_hangup": function () {
  5854. return hangup();
  5855. },
  5856. "toolbar_button_login": function () {
  5857. Toolbar.authenticateClicked();
  5858. },
  5859. "toolbar_button_logout": function () {
  5860. // Ask for confirmation
  5861. messageHandler.openTwoButtonDialog(
  5862. "dialog.logoutTitle",
  5863. null,
  5864. "dialog.logoutQuestion",
  5865. null,
  5866. false,
  5867. "dialog.Yes",
  5868. function (evt, yes) {
  5869. if (yes) {
  5870. APP.xmpp.logout(function (url) {
  5871. if (url) {
  5872. window.location.href = url;
  5873. } else {
  5874. hangup();
  5875. }
  5876. });
  5877. }
  5878. });
  5879. }
  5880. };
  5881. function hangup() {
  5882. APP.xmpp.disposeConference();
  5883. if(config.enableWelcomePage)
  5884. {
  5885. setTimeout(function()
  5886. {
  5887. window.localStorage.welcomePageDisabled = false;
  5888. window.location.pathname = "/";
  5889. }, 10000);
  5890. }
  5891. var title = APP.translation.generateTranslationHTML(
  5892. "dialog.sessTerminated");
  5893. var msg = APP.translation.generateTranslationHTML(
  5894. "dialog.hungUp");
  5895. var button = APP.translation.generateTranslationHTML(
  5896. "dialog.joinAgain");
  5897. var buttons = [];
  5898. buttons.push({title: button, value: true});
  5899. UI.messageHandler.openDialog(
  5900. title,
  5901. msg,
  5902. true,
  5903. buttons,
  5904. function(event, value, message, formVals)
  5905. {
  5906. window.location.reload();
  5907. return false;
  5908. }
  5909. );
  5910. }
  5911. /**
  5912. * Starts or stops the recording for the conference.
  5913. */
  5914. function toggleRecording() {
  5915. APP.xmpp.toggleRecording(function (callback) {
  5916. var msg = APP.translation.generateTranslationHTML(
  5917. "dialog.recordingToken");
  5918. var token = APP.translation.translateString("dialog.token");
  5919. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5920. '<h2>' + msg + '</h2>' +
  5921. '<input name="recordingToken" type="text" ' +
  5922. ' data-i18n="[placeholder]dialog.token" ' +
  5923. 'placeholder="' + token + '" autofocus>',
  5924. false,
  5925. "dialog.Save",
  5926. function (e, v, m, f) {
  5927. if (v) {
  5928. var token = f.recordingToken;
  5929. if (token) {
  5930. callback(UIUtil.escapeHtml(token));
  5931. }
  5932. }
  5933. },
  5934. null,
  5935. function () { },
  5936. ':input:first'
  5937. );
  5938. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  5939. }
  5940. /**
  5941. * Locks / unlocks the room.
  5942. */
  5943. function lockRoom(lock) {
  5944. var currentSharedKey = '';
  5945. if (lock)
  5946. currentSharedKey = sharedKey;
  5947. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5948. // password is required
  5949. if (sharedKey)
  5950. {
  5951. console.log('set room password');
  5952. Toolbar.lockLockButton();
  5953. }
  5954. else
  5955. {
  5956. console.log('removed room password');
  5957. Toolbar.unlockLockButton();
  5958. }
  5959. }, function (err) {
  5960. console.warn('setting password failed', err);
  5961. messageHandler.showError("dialog.lockTitle",
  5962. "dialog.lockMessage");
  5963. Toolbar.setSharedKey('');
  5964. }, function () {
  5965. console.warn('room passwords not supported');
  5966. messageHandler.showError("dialog.warning",
  5967. "dialog.passwordNotSupported");
  5968. Toolbar.setSharedKey('');
  5969. });
  5970. };
  5971. /**
  5972. * Invite participants to conference.
  5973. */
  5974. function inviteParticipants() {
  5975. if (roomUrl === null)
  5976. return;
  5977. var sharedKeyText = "";
  5978. if (sharedKey && sharedKey.length > 0) {
  5979. sharedKeyText =
  5980. APP.translation.translateString("email.sharedKey",
  5981. {sharedKey: sharedKey});
  5982. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5983. }
  5984. var supportedBrowsers = "Chromium, Google Chrome " +
  5985. APP.translation.translateString("email.and") + " Opera";
  5986. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5987. var subject = APP.translation.translateString("email.subject",
  5988. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5989. var body = APP.translation.translateString("email.body",
  5990. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5991. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5992. body = body.replace(/\n/g, "%0D%0A");
  5993. if (window.localStorage.displayname) {
  5994. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5995. }
  5996. if (interfaceConfig.INVITATION_POWERED_BY) {
  5997. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5998. }
  5999. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  6000. }
  6001. function dialpadButtonClicked()
  6002. {
  6003. //TODO show the dialpad window
  6004. }
  6005. function callSipButtonClicked()
  6006. {
  6007. var defaultNumber
  6008. = config.defaultSipNumber ? config.defaultSipNumber : '';
  6009. var sipMsg = APP.translation.generateTranslationHTML(
  6010. "dialog.sipMsg");
  6011. messageHandler.openTwoButtonDialog(null, null, null,
  6012. '<h2>' + sipMsg + '</h2>' +
  6013. '<input name="sipNumber" type="text"' +
  6014. ' value="' + defaultNumber + '" autofocus>',
  6015. false,
  6016. "dialog.Dial",
  6017. function (e, v, m, f) {
  6018. if (v) {
  6019. var numberInput = f.sipNumber;
  6020. if (numberInput) {
  6021. APP.xmpp.dial(
  6022. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  6023. }
  6024. }
  6025. },
  6026. null, null, ':input:first'
  6027. );
  6028. }
  6029. var Toolbar = (function (my) {
  6030. my.init = function (ui) {
  6031. for(var k in buttonHandlers)
  6032. $("#" + k).click(buttonHandlers[k]);
  6033. UI = ui;
  6034. // Update login info
  6035. APP.xmpp.addListener(
  6036. AuthenticationEvents.IDENTITY_UPDATED,
  6037. function (authenticationEnabled, userIdentity) {
  6038. var loggedIn = false;
  6039. if (userIdentity) {
  6040. loggedIn = true;
  6041. }
  6042. Toolbar.showAuthenticateButton(authenticationEnabled);
  6043. if (authenticationEnabled) {
  6044. Toolbar.setAuthenticatedIdentity(userIdentity);
  6045. Toolbar.showLoginButton(!loggedIn);
  6046. Toolbar.showLogoutButton(loggedIn);
  6047. }
  6048. }
  6049. );
  6050. },
  6051. /**
  6052. * Sets shared key
  6053. * @param sKey the shared key
  6054. */
  6055. my.setSharedKey = function (sKey) {
  6056. sharedKey = sKey;
  6057. };
  6058. my.authenticateClicked = function () {
  6059. Authentication.focusAuthenticationWindow();
  6060. if (!APP.xmpp.isExternalAuthEnabled()) {
  6061. Authentication.xmppAuthenticate();
  6062. return;
  6063. }
  6064. // Get authentication URL
  6065. if (!APP.xmpp.getMUCJoined()) {
  6066. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6067. // If conference has not been started yet - redirect to login page
  6068. window.location.href = url;
  6069. });
  6070. } else {
  6071. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6072. // Otherwise - open popup with authentication URL
  6073. var authenticationWindow = Authentication.createAuthenticationWindow(
  6074. function () {
  6075. // On popup closed - retry room allocation
  6076. APP.xmpp.allocateConferenceFocus(
  6077. APP.UI.getRoomName(),
  6078. function () { console.info("AUTH DONE"); }
  6079. );
  6080. }, url);
  6081. if (!authenticationWindow) {
  6082. messageHandler.openMessageDialog(
  6083. null, "dialog.popupError");
  6084. }
  6085. });
  6086. }
  6087. };
  6088. /**
  6089. * Updates the room invite url.
  6090. */
  6091. my.updateRoomUrl = function (newRoomUrl) {
  6092. roomUrl = newRoomUrl;
  6093. // If the invite dialog has been already opened we update the information.
  6094. var inviteLink = document.getElementById('inviteLinkRef');
  6095. if (inviteLink) {
  6096. inviteLink.value = roomUrl;
  6097. inviteLink.select();
  6098. $('#inviteLinkRef').parent()
  6099. .find('button[value=true]').prop('disabled', false);
  6100. }
  6101. };
  6102. /**
  6103. * Disables and enables some of the buttons.
  6104. */
  6105. my.setupButtonsFromConfig = function () {
  6106. if (config.disablePrezi)
  6107. {
  6108. $("#prezi_button").css({display: "none"});
  6109. }
  6110. };
  6111. /**
  6112. * Opens the lock room dialog.
  6113. */
  6114. my.openLockDialog = function () {
  6115. // Only the focus is able to set a shared key.
  6116. if (!APP.xmpp.isModerator()) {
  6117. if (sharedKey) {
  6118. messageHandler.openMessageDialog(null,
  6119. "dialog.passwordError");
  6120. } else {
  6121. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6122. }
  6123. } else {
  6124. if (sharedKey) {
  6125. messageHandler.openTwoButtonDialog(null, null,
  6126. "dialog.passwordCheck",
  6127. null,
  6128. false,
  6129. "dialog.Remove",
  6130. function (e, v) {
  6131. if (v) {
  6132. Toolbar.setSharedKey('');
  6133. lockRoom(false);
  6134. }
  6135. });
  6136. } else {
  6137. var msg = APP.translation.generateTranslationHTML(
  6138. "dialog.passwordMsg");
  6139. var yourPassword = APP.translation.translateString(
  6140. "dialog.yourPassword");
  6141. messageHandler.openTwoButtonDialog(null, null, null,
  6142. '<h2>' + msg + '</h2>' +
  6143. '<input name="lockKey" type="text"' +
  6144. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6145. 'placeholder="' + yourPassword + '" autofocus>',
  6146. false,
  6147. "dialog.Save",
  6148. function (e, v, m, f) {
  6149. if (v) {
  6150. var lockKey = f.lockKey;
  6151. if (lockKey) {
  6152. Toolbar.setSharedKey(
  6153. UIUtil.escapeHtml(lockKey));
  6154. lockRoom(true);
  6155. }
  6156. }
  6157. },
  6158. null, null, 'input:first'
  6159. );
  6160. }
  6161. }
  6162. };
  6163. /**
  6164. * Opens the invite link dialog.
  6165. */
  6166. my.openLinkDialog = function () {
  6167. var inviteAttreibutes;
  6168. if (roomUrl === null) {
  6169. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6170. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6171. } else {
  6172. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6173. }
  6174. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6175. null, null,
  6176. '<input id="inviteLinkRef" type="text" ' +
  6177. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6178. false,
  6179. "dialog.Invite",
  6180. function (e, v) {
  6181. if (v) {
  6182. if (roomUrl) {
  6183. inviteParticipants();
  6184. }
  6185. }
  6186. },
  6187. function (event) {
  6188. if (roomUrl) {
  6189. document.getElementById('inviteLinkRef').select();
  6190. } else {
  6191. if (event && event.target)
  6192. $(event.target)
  6193. .find('button[value=true]').prop('disabled', true);
  6194. }
  6195. }
  6196. );
  6197. };
  6198. /**
  6199. * Opens the settings dialog.
  6200. * FIXME: not used ?
  6201. */
  6202. my.openSettingsDialog = function () {
  6203. var settings1 = APP.translation.generateTranslationHTML(
  6204. "dialog.settings1");
  6205. var settings2 = APP.translation.generateTranslationHTML(
  6206. "dialog.settings2");
  6207. var settings3 = APP.translation.generateTranslationHTML(
  6208. "dialog.settings3");
  6209. var yourPassword = APP.translation.translateString(
  6210. "dialog.yourPassword");
  6211. messageHandler.openTwoButtonDialog(null,
  6212. '<h2>' + settings1 + '</h2>' +
  6213. '<input type="checkbox" id="initMuted">' +
  6214. settings2 + '<br/>' +
  6215. '<input type="checkbox" id="requireNicknames">' +
  6216. settings3 +
  6217. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6218. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6219. null,
  6220. null,
  6221. false,
  6222. "dialog.Save",
  6223. function () {
  6224. document.getElementById('lockKey').focus();
  6225. },
  6226. function (e, v) {
  6227. if (v) {
  6228. if ($('#initMuted').is(":checked")) {
  6229. // it is checked
  6230. }
  6231. if ($('#requireNicknames').is(":checked")) {
  6232. // it is checked
  6233. }
  6234. /*
  6235. var lockKey = document.getElementById('lockKey');
  6236. if (lockKey.value) {
  6237. setSharedKey(lockKey.value);
  6238. lockRoom(true);
  6239. }
  6240. */
  6241. }
  6242. }
  6243. );
  6244. };
  6245. /**
  6246. * Toggles the application in and out of full screen mode
  6247. * (a.k.a. presentation mode in Chrome).
  6248. */
  6249. my.toggleFullScreen = function () {
  6250. var fsElement = document.documentElement;
  6251. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6252. //Enter Full Screen
  6253. if (fsElement.mozRequestFullScreen) {
  6254. fsElement.mozRequestFullScreen();
  6255. }
  6256. else {
  6257. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6258. }
  6259. } else {
  6260. //Exit Full Screen
  6261. if (document.mozCancelFullScreen) {
  6262. document.mozCancelFullScreen();
  6263. } else {
  6264. document.webkitCancelFullScreen();
  6265. }
  6266. }
  6267. };
  6268. /**
  6269. * Unlocks the lock button state.
  6270. */
  6271. my.unlockLockButton = function () {
  6272. if ($("#lockIcon").hasClass("icon-security-locked"))
  6273. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6274. };
  6275. /**
  6276. * Updates the lock button state to locked.
  6277. */
  6278. my.lockLockButton = function () {
  6279. if ($("#lockIcon").hasClass("icon-security"))
  6280. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6281. };
  6282. /**
  6283. * Shows or hides authentication button
  6284. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6285. */
  6286. my.showAuthenticateButton = function (show) {
  6287. if (show) {
  6288. $('#authentication').css({display: "inline"});
  6289. }
  6290. else {
  6291. $('#authentication').css({display: "none"});
  6292. }
  6293. };
  6294. // Shows or hides the 'recording' button.
  6295. my.showRecordingButton = function (show) {
  6296. if (!config.enableRecording) {
  6297. return;
  6298. }
  6299. if (show) {
  6300. $('#recording').css({display: "inline"});
  6301. }
  6302. else {
  6303. $('#recording').css({display: "none"});
  6304. }
  6305. };
  6306. // Sets the state of the recording button
  6307. my.setRecordingButtonState = function (isRecording) {
  6308. var selector = $('#recordButton');
  6309. if (isRecording) {
  6310. selector.removeClass("icon-recEnable");
  6311. selector.addClass("icon-recEnable active");
  6312. } else {
  6313. selector.removeClass("icon-recEnable active");
  6314. selector.addClass("icon-recEnable");
  6315. }
  6316. };
  6317. // Shows or hides SIP calls button
  6318. my.showSipCallButton = function (show) {
  6319. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6320. $('#sipCallButton').css({display: "inline-block"});
  6321. } else {
  6322. $('#sipCallButton').css({display: "none"});
  6323. }
  6324. };
  6325. // Shows or hides the dialpad button
  6326. my.showDialPadButton = function (show) {
  6327. if (show) {
  6328. $('#dialPadButton').css({display: "inline-block"});
  6329. } else {
  6330. $('#dialPadButton').css({display: "none"});
  6331. }
  6332. };
  6333. /**
  6334. * Displays user authenticated identity name(login).
  6335. * @param authIdentity identity name to be displayed.
  6336. */
  6337. my.setAuthenticatedIdentity = function (authIdentity) {
  6338. if (authIdentity) {
  6339. var selector = $('#toolbar_auth_identity');
  6340. selector.css({display: "list-item"});
  6341. selector.text(authIdentity);
  6342. } else {
  6343. $('#toolbar_auth_identity').css({display: "none"});
  6344. }
  6345. };
  6346. /**
  6347. * Shows/hides login button.
  6348. * @param show <tt>true</tt> to show
  6349. */
  6350. my.showLoginButton = function (show) {
  6351. if (show) {
  6352. $('#toolbar_button_login').css({display: "list-item"});
  6353. } else {
  6354. $('#toolbar_button_login').css({display: "none"});
  6355. }
  6356. };
  6357. /**
  6358. * Shows/hides logout button.
  6359. * @param show <tt>true</tt> to show
  6360. */
  6361. my.showLogoutButton = function (show) {
  6362. if (show) {
  6363. $('#toolbar_button_logout').css({display: "list-item"});
  6364. } else {
  6365. $('#toolbar_button_logout').css({display: "none"});
  6366. }
  6367. };
  6368. /**
  6369. * Sets the state of the button. The button has blue glow if desktop
  6370. * streaming is active.
  6371. * @param active the state of the desktop streaming.
  6372. */
  6373. my.changeDesktopSharingButtonState = function (active) {
  6374. var button = $("#desktopsharing > a");
  6375. if (active)
  6376. {
  6377. button.addClass("glow");
  6378. }
  6379. else
  6380. {
  6381. button.removeClass("glow");
  6382. }
  6383. };
  6384. return my;
  6385. }(Toolbar || {}));
  6386. module.exports = Toolbar;
  6387. },{"../../../service/authentication/AuthenticationEvents":103,"../authentication/Authentication":14,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../side_pannels/SidePanelToggler":20,"../util/MessageHandler":31,"../util/UIUtil":33,"./BottomToolbar":27}],29:[function(require,module,exports){
  6388. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  6389. var toolbarTimeoutObject,
  6390. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6391. function showDesktopSharingButton() {
  6392. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6393. $('#desktopsharing').css({display: "inline"});
  6394. } else {
  6395. $('#desktopsharing').css({display: "none"});
  6396. }
  6397. }
  6398. /**
  6399. * Hides the toolbar.
  6400. */
  6401. function hideToolbar() {
  6402. if(config.alwaysVisibleToolbar)
  6403. return;
  6404. var header = $("#header"),
  6405. bottomToolbar = $("#bottomToolbar");
  6406. var isToolbarHover = false;
  6407. header.find('*').each(function () {
  6408. var id = $(this).attr('id');
  6409. if ($("#" + id + ":hover").length > 0) {
  6410. isToolbarHover = true;
  6411. }
  6412. });
  6413. if ($("#bottomToolbar:hover").length > 0) {
  6414. isToolbarHover = true;
  6415. }
  6416. clearTimeout(toolbarTimeoutObject);
  6417. toolbarTimeoutObject = null;
  6418. if (!isToolbarHover) {
  6419. header.hide("slide", { direction: "up", duration: 300});
  6420. $('#subject').animate({top: "-=40"}, 300);
  6421. if ($("#remoteVideos").hasClass("hidden")) {
  6422. bottomToolbar.hide(
  6423. "slide", {direction: "right", duration: 300});
  6424. }
  6425. }
  6426. else {
  6427. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6428. }
  6429. }
  6430. var ToolbarToggler = {
  6431. /**
  6432. * Shows the main toolbar.
  6433. */
  6434. showToolbar: function () {
  6435. var header = $("#header"),
  6436. bottomToolbar = $("#bottomToolbar");
  6437. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6438. header.show("slide", { direction: "up", duration: 300});
  6439. $('#subject').animate({top: "+=40"}, 300);
  6440. if (!bottomToolbar.is(":visible")) {
  6441. bottomToolbar.show(
  6442. "slide", {direction: "right", duration: 300});
  6443. }
  6444. if (toolbarTimeoutObject) {
  6445. clearTimeout(toolbarTimeoutObject);
  6446. toolbarTimeoutObject = null;
  6447. }
  6448. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6449. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6450. }
  6451. if (APP.xmpp.isModerator())
  6452. {
  6453. // TODO: Enable settings functionality.
  6454. // Need to uncomment the settings button in index.html.
  6455. // $('#settingsButton').css({visibility:"visible"});
  6456. }
  6457. // Show/hide desktop sharing button
  6458. showDesktopSharingButton();
  6459. },
  6460. /**
  6461. * Docks/undocks the toolbar.
  6462. *
  6463. * @param isDock indicates what operation to perform
  6464. */
  6465. dockToolbar: function (isDock) {
  6466. if (isDock) {
  6467. // First make sure the toolbar is shown.
  6468. if (!$('#header').is(':visible')) {
  6469. this.showToolbar();
  6470. }
  6471. // Then clear the time out, to dock the toolbar.
  6472. if (toolbarTimeoutObject) {
  6473. clearTimeout(toolbarTimeoutObject);
  6474. toolbarTimeoutObject = null;
  6475. }
  6476. }
  6477. else {
  6478. if (!$('#header').is(':visible')) {
  6479. this.showToolbar();
  6480. }
  6481. else {
  6482. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6483. }
  6484. }
  6485. },
  6486. showDesktopSharingButton: showDesktopSharingButton
  6487. };
  6488. module.exports = ToolbarToggler;
  6489. },{}],30:[function(require,module,exports){
  6490. var JitsiPopover = (function () {
  6491. /**
  6492. * Constructs new JitsiPopover and attaches it to the element
  6493. * @param element jquery selector
  6494. * @param options the options for the popover.
  6495. * @constructor
  6496. */
  6497. function JitsiPopover(element, options)
  6498. {
  6499. this.options = {
  6500. skin: "white",
  6501. content: ""
  6502. };
  6503. if(options)
  6504. {
  6505. if(options.skin)
  6506. this.options.skin = options.skin;
  6507. if(options.content)
  6508. this.options.content = options.content;
  6509. }
  6510. this.elementIsHovered = false;
  6511. this.popoverIsHovered = false;
  6512. this.popoverShown = false;
  6513. element.data("jitsi_popover", this);
  6514. this.element = element;
  6515. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6516. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6517. '<div class="jitsiPopupmenuPadding"></div></div>';
  6518. var self = this;
  6519. this.element.on("mouseenter", function () {
  6520. self.elementIsHovered = true;
  6521. self.show();
  6522. }).on("mouseleave", function () {
  6523. self.elementIsHovered = false;
  6524. setTimeout(function () {
  6525. self.hide();
  6526. }, 10);
  6527. });
  6528. }
  6529. /**
  6530. * Shows the popover
  6531. */
  6532. JitsiPopover.prototype.show = function () {
  6533. this.createPopover();
  6534. this.popoverShown = true;
  6535. };
  6536. /**
  6537. * Hides the popover
  6538. */
  6539. JitsiPopover.prototype.hide = function () {
  6540. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  6541. {
  6542. this.forceHide();
  6543. }
  6544. };
  6545. /**
  6546. * Hides the popover
  6547. */
  6548. JitsiPopover.prototype.forceHide = function () {
  6549. $(".jitsipopover").remove();
  6550. this.popoverShown = false;
  6551. };
  6552. /**
  6553. * Creates the popover html
  6554. */
  6555. JitsiPopover.prototype.createPopover = function () {
  6556. $("body").append(this.template);
  6557. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6558. var self = this;
  6559. $(".jitsipopover").on("mouseenter", function () {
  6560. self.popoverIsHovered = true;
  6561. }).on("mouseleave", function () {
  6562. self.popoverIsHovered = false;
  6563. self.hide();
  6564. });
  6565. this.refreshPosition();
  6566. };
  6567. /**
  6568. * Refreshes the position of the popover
  6569. */
  6570. JitsiPopover.prototype.refreshPosition = function () {
  6571. $(".jitsipopover").position({
  6572. my: "bottom",
  6573. at: "top",
  6574. collision: "fit",
  6575. of: this.element,
  6576. using: function (position, elements) {
  6577. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  6578. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  6579. $(".jitsipopover > .arrow").css({left: calcLeft});
  6580. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  6581. }
  6582. });
  6583. };
  6584. /**
  6585. * Updates the content of popover.
  6586. * @param content new content
  6587. */
  6588. JitsiPopover.prototype.updateContent = function (content) {
  6589. this.options.content = content;
  6590. if(!this.popoverShown)
  6591. return;
  6592. $(".jitsipopover").remove();
  6593. this.createPopover();
  6594. };
  6595. return JitsiPopover;
  6596. })();
  6597. module.exports = JitsiPopover;
  6598. },{}],31:[function(require,module,exports){
  6599. /* global $, APP, jQuery, toastr */
  6600. var messageHandler = (function(my) {
  6601. /**
  6602. * Shows a message to the user.
  6603. *
  6604. * @param titleString the title of the message
  6605. * @param messageString the text of the message
  6606. */
  6607. my.openMessageDialog = function(titleKey, messageKey) {
  6608. var title = null;
  6609. if(titleKey)
  6610. {
  6611. title = APP.translation.generateTranslationHTML(titleKey);
  6612. }
  6613. var message = APP.translation.generateTranslationHTML(messageKey);
  6614. $.prompt(message,
  6615. {
  6616. title: title,
  6617. persistent: false
  6618. }
  6619. );
  6620. };
  6621. /**
  6622. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6623. *
  6624. * @param titleString the title of the message
  6625. * @param msgString the text of the message
  6626. * @param persistent boolean value which determines whether the message is persistent or not
  6627. * @param leftButton the fist button's text
  6628. * @param submitFunction function to be called on submit
  6629. * @param loadedFunction function to be called after the prompt is fully loaded
  6630. * @param closeFunction function to be called after the prompt is closed
  6631. * @param focus optional focus selector or button index to be focused after
  6632. * the dialog is opened
  6633. * @param defaultButton index of default button which will be activated when
  6634. * the user press 'enter'. Indexed from 0.
  6635. */
  6636. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6637. persistent, leftButtonKey, submitFunction, loadedFunction,
  6638. closeFunction, focus, defaultButton)
  6639. {
  6640. var buttons = [];
  6641. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6642. buttons.push({ title: leftButton, value: true});
  6643. var cancelButton
  6644. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6645. buttons.push({title: cancelButton, value: false});
  6646. var message = msgString, title = titleString;
  6647. if (titleKey)
  6648. {
  6649. title = APP.translation.generateTranslationHTML(titleKey);
  6650. }
  6651. if (msgKey) {
  6652. message = APP.translation.generateTranslationHTML(msgKey);
  6653. }
  6654. $.prompt(message, {
  6655. title: title,
  6656. persistent: false,
  6657. buttons: buttons,
  6658. defaultButton: defaultButton,
  6659. focus: focus,
  6660. loaded: loadedFunction,
  6661. submit: submitFunction,
  6662. close: closeFunction
  6663. });
  6664. };
  6665. /**
  6666. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6667. *
  6668. * @param titleString the title of the message
  6669. * @param msgString the text of the message
  6670. * @param persistent boolean value which determines whether the message is persistent or not
  6671. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  6672. * that will be passed to submitFunction
  6673. * @param submitFunction function to be called on submit
  6674. * @param loadedFunction function to be called after the prompt is fully loaded
  6675. */
  6676. my.openDialog = function (titleString, msgString, persistent, buttons,
  6677. submitFunction, loadedFunction) {
  6678. var args = {
  6679. title: titleString,
  6680. persistent: persistent,
  6681. buttons: buttons,
  6682. defaultButton: 1,
  6683. loaded: loadedFunction,
  6684. submit: submitFunction
  6685. };
  6686. if (persistent) {
  6687. args.closeText = '';
  6688. }
  6689. return new Impromptu(msgString, args);
  6690. };
  6691. /**
  6692. * Closes currently opened dialog.
  6693. */
  6694. my.closeDialog = function () {
  6695. $.prompt.close();
  6696. };
  6697. /**
  6698. * Shows a dialog with different states to the user.
  6699. *
  6700. * @param statesObject object containing all the states of the dialog
  6701. */
  6702. my.openDialogWithStates = function (statesObject, options) {
  6703. return new Impromptu(statesObject, options);
  6704. };
  6705. /**
  6706. * Opens new popup window for given <tt>url</tt> centered over current
  6707. * window.
  6708. *
  6709. * @param url the URL to be displayed in the popup window
  6710. * @param w the width of the popup window
  6711. * @param h the height of the popup window
  6712. * @param onPopupClosed optional callback function called when popup window
  6713. * has been closed.
  6714. *
  6715. * @returns popup window object if opened successfully or undefined
  6716. * in case we failed to open it(popup blocked)
  6717. */
  6718. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6719. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6720. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6721. var popup = window.open(
  6722. url, '_blank',
  6723. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6724. if (popup && onPopupClosed) {
  6725. var pollTimer = window.setInterval(function () {
  6726. if (popup.closed !== false) {
  6727. window.clearInterval(pollTimer);
  6728. onPopupClosed();
  6729. }
  6730. }, 200);
  6731. }
  6732. return popup;
  6733. };
  6734. /**
  6735. * Shows a dialog prompting the user to send an error report.
  6736. *
  6737. * @param titleString the title of the message
  6738. * @param msgString the text of the message
  6739. * @param error the error that is being reported
  6740. */
  6741. my.openReportDialog = function(titleKey, msgKey, error) {
  6742. my.openMessageDialog(titleKey, msgKey);
  6743. console.log(error);
  6744. //FIXME send the error to the server
  6745. };
  6746. /**
  6747. * Shows an error dialog to the user.
  6748. * @param title the title of the message
  6749. * @param message the text of the messafe
  6750. */
  6751. my.showError = function(titleKey, msgKey) {
  6752. if(!titleKey) {
  6753. titleKey = "dialog.oops";
  6754. }
  6755. if(!msgKey)
  6756. {
  6757. msgKey = "dialog.defaultError";
  6758. }
  6759. messageHandler.openMessageDialog(titleKey, msgKey);
  6760. };
  6761. my.notify = function(displayName, displayNameKey,
  6762. cls, messageKey, messageArguments, options) {
  6763. var displayNameSpan = '<span class="nickname" ';
  6764. if(displayName)
  6765. {
  6766. displayNameSpan += ">" + displayName;
  6767. }
  6768. else
  6769. {
  6770. displayNameSpan += "data-i18n='" + displayNameKey +
  6771. "'>" + APP.translation.translateString(displayNameKey);
  6772. }
  6773. displayNameSpan += "</span>";
  6774. toastr.info(
  6775. displayNameSpan + '<br>' +
  6776. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6777. (messageArguments?
  6778. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6779. : "") + ">" +
  6780. APP.translation.translateString(messageKey,
  6781. messageArguments) +
  6782. '</span>', null, options);
  6783. };
  6784. return my;
  6785. }(messageHandler || {}));
  6786. module.exports = messageHandler;
  6787. },{}],32:[function(require,module,exports){
  6788. var UIEvents = require("../../../service/UI/UIEvents");
  6789. var nickname = null;
  6790. var eventEmitter = null;
  6791. var NickanameHandler = {
  6792. init: function (emitter) {
  6793. eventEmitter = emitter;
  6794. var storedDisplayName = window.localStorage.displayname;
  6795. if (storedDisplayName) {
  6796. nickname = storedDisplayName;
  6797. }
  6798. },
  6799. setNickname: function (newNickname) {
  6800. if (!newNickname || nickname === newNickname)
  6801. return;
  6802. nickname = newNickname;
  6803. window.localStorage.displayname = nickname;
  6804. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6805. },
  6806. getNickname: function () {
  6807. return nickname;
  6808. },
  6809. addListener: function (type, listener) {
  6810. eventEmitter.on(type, listener);
  6811. }
  6812. };
  6813. module.exports = NickanameHandler;
  6814. },{"../../../service/UI/UIEvents":102}],33:[function(require,module,exports){
  6815. /**
  6816. * Created by hristo on 12/22/14.
  6817. */
  6818. module.exports = {
  6819. /**
  6820. * Returns the available video width.
  6821. */
  6822. getAvailableVideoWidth: function (isVisible) {
  6823. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6824. if(typeof isVisible === "undefined" || isVisible === null)
  6825. isVisible = PanelToggler.isVisible();
  6826. var rightPanelWidth
  6827. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6828. return window.innerWidth - rightPanelWidth;
  6829. },
  6830. /**
  6831. * Changes the style class of the element given by id.
  6832. */
  6833. buttonClick: function(id, classname) {
  6834. $(id).toggleClass(classname); // add the class to the clicked element
  6835. },
  6836. /**
  6837. * Returns the text width for the given element.
  6838. *
  6839. * @param el the element
  6840. */
  6841. getTextWidth: function (el) {
  6842. return (el.clientWidth + 1);
  6843. },
  6844. /**
  6845. * Returns the text height for the given element.
  6846. *
  6847. * @param el the element
  6848. */
  6849. getTextHeight: function (el) {
  6850. return (el.clientHeight + 1);
  6851. },
  6852. /**
  6853. * Plays the sound given by id.
  6854. *
  6855. * @param id the identifier of the audio element.
  6856. */
  6857. playSoundNotification: function (id) {
  6858. document.getElementById(id).play();
  6859. },
  6860. /**
  6861. * Escapes the given text.
  6862. */
  6863. escapeHtml: function (unsafeText) {
  6864. return $('<div/>').text(unsafeText).html();
  6865. },
  6866. imageToGrayScale: function (canvas) {
  6867. var context = canvas.getContext('2d');
  6868. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6869. var pixels = imgData.data;
  6870. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6871. var grayscale
  6872. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  6873. pixels[i ] = grayscale; // red
  6874. pixels[i+1] = grayscale; // green
  6875. pixels[i+2] = grayscale; // blue
  6876. // pixels[i+3] is alpha
  6877. }
  6878. // redraw the image in black & white
  6879. context.putImageData(imgData, 0, 0);
  6880. },
  6881. setTooltip: function (element, key, position) {
  6882. element.setAttribute("data-i18n", "[data-content]" + key);
  6883. element.setAttribute("data-toggle", "popover");
  6884. element.setAttribute("data-placement", position);
  6885. element.setAttribute("data-html", true);
  6886. element.setAttribute("data-container", "body");
  6887. }
  6888. };
  6889. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6890. var JitsiPopover = require("../util/JitsiPopover");
  6891. /**
  6892. * Constructs new connection indicator.
  6893. * @param videoContainer the video container associated with the indicator.
  6894. * @constructor
  6895. */
  6896. function ConnectionIndicator(videoContainer, jid)
  6897. {
  6898. this.videoContainer = videoContainer;
  6899. this.bandwidth = null;
  6900. this.packetLoss = null;
  6901. this.bitrate = null;
  6902. this.showMoreValue = false;
  6903. this.resolution = null;
  6904. this.transport = [];
  6905. this.popover = null;
  6906. this.jid = jid;
  6907. this.create();
  6908. }
  6909. /**
  6910. * Values for the connection quality
  6911. * @type {{98: string,
  6912. * 81: string,
  6913. * 64: string,
  6914. * 47: string,
  6915. * 30: string,
  6916. * 0: string}}
  6917. */
  6918. ConnectionIndicator.connectionQualityValues = {
  6919. 98: "18px", //full
  6920. 81: "15px",//4 bars
  6921. 64: "11px",//3 bars
  6922. 47: "7px",//2 bars
  6923. 30: "3px",//1 bar
  6924. 0: "0px"//empty
  6925. };
  6926. ConnectionIndicator.getIP = function(value)
  6927. {
  6928. return value.substring(0, value.lastIndexOf(":"));
  6929. };
  6930. ConnectionIndicator.getPort = function(value)
  6931. {
  6932. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6933. };
  6934. ConnectionIndicator.getStringFromArray = function (array) {
  6935. var res = "";
  6936. for(var i = 0; i < array.length; i++)
  6937. {
  6938. res += (i === 0? "" : ", ") + array[i];
  6939. }
  6940. return res;
  6941. };
  6942. /**
  6943. * Generates the html content.
  6944. * @returns {string} the html content.
  6945. */
  6946. ConnectionIndicator.prototype.generateText = function () {
  6947. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6948. var translate = APP.translation.translateString;
  6949. if(this.bitrate === null)
  6950. {
  6951. downloadBitrate = "N/A";
  6952. uploadBitrate = "N/A";
  6953. }
  6954. else
  6955. {
  6956. downloadBitrate =
  6957. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6958. uploadBitrate =
  6959. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6960. }
  6961. if(this.packetLoss === null)
  6962. {
  6963. packetLoss = "N/A";
  6964. }
  6965. else
  6966. {
  6967. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6968. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  6969. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6970. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  6971. }
  6972. var resolutionValue = null;
  6973. if(this.resolution && this.jid != null)
  6974. {
  6975. var keys = Object.keys(this.resolution);
  6976. for(var ssrc in this.resolution)
  6977. {
  6978. resolutionValue = this.resolution[ssrc];
  6979. }
  6980. }
  6981. if(this.jid === null)
  6982. {
  6983. resolution = "";
  6984. if(this.resolution === null || !Object.keys(this.resolution) ||
  6985. Object.keys(this.resolution).length === 0)
  6986. {
  6987. resolution = "N/A";
  6988. }
  6989. else
  6990. for(i in this.resolution)
  6991. {
  6992. resolutionValue = this.resolution[i];
  6993. if(resolutionValue)
  6994. {
  6995. if(resolutionValue.height &&
  6996. resolutionValue.width)
  6997. {
  6998. resolution += (resolution === ""? "" : ", ") +
  6999. resolutionValue.width + "x" +
  7000. resolutionValue.height;
  7001. }
  7002. }
  7003. }
  7004. }
  7005. else if(!resolutionValue ||
  7006. !resolutionValue.height ||
  7007. !resolutionValue.width)
  7008. {
  7009. resolution = "N/A";
  7010. }
  7011. else
  7012. {
  7013. resolution = resolutionValue.width + "x" + resolutionValue.height;
  7014. }
  7015. var result = "<table style='width:100%'>" +
  7016. "<tr>" +
  7017. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  7018. translate("connectionindicator.bitrate") + "</span></td>" +
  7019. "<td><span class='jitsipopover_green'>&darr;</span>" +
  7020. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  7021. uploadBitrate + "</td>" +
  7022. "</tr><tr>" +
  7023. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  7024. translate("connectionindicator.packetloss") + "</span></td>" +
  7025. "<td>" + packetLoss + "</td>" +
  7026. "</tr><tr>" +
  7027. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  7028. translate("connectionindicator.resolution") + "</span></td>" +
  7029. "<td>" + resolution + "</td></tr></table>";
  7030. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  7031. result += "<div class=\"jitsipopover_showmore\" " +
  7032. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  7033. // FIXME: we do not know local jid when this text is generated
  7034. //this.jid + "')\" data-i18n='connectionindicator." +
  7035. "local')\" data-i18n='connectionindicator." +
  7036. (this.showMoreValue ? "less" : "more") + "'>" +
  7037. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  7038. "</div><br />";
  7039. }
  7040. if(this.showMoreValue)
  7041. {
  7042. var downloadBandwidth, uploadBandwidth, transport;
  7043. if(this.bandwidth === null)
  7044. {
  7045. downloadBandwidth = "N/A";
  7046. uploadBandwidth = "N/A";
  7047. }
  7048. else
  7049. {
  7050. downloadBandwidth = this.bandwidth.download?
  7051. this.bandwidth.download + " Kbps" :
  7052. "N/A";
  7053. uploadBandwidth = this.bandwidth.upload?
  7054. this.bandwidth.upload + " Kbps" :
  7055. "N/A";
  7056. }
  7057. if(!this.transport || this.transport.length === 0)
  7058. {
  7059. transport = "<tr>" +
  7060. "<td><span class='jitsipopover_blue' " +
  7061. "data-i18n='connectionindicator.address'>" +
  7062. translate("connectionindicator.address") + "</span></td>" +
  7063. "<td> N/A</td></tr>";
  7064. }
  7065. else
  7066. {
  7067. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7068. for(i = 0; i < this.transport.length; i++)
  7069. {
  7070. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7071. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7072. var localIP =
  7073. ConnectionIndicator.getIP(this.transport[i].localip);
  7074. var localPort =
  7075. ConnectionIndicator.getPort(this.transport[i].localip);
  7076. if(data.remoteIP.indexOf(ip) == -1)
  7077. {
  7078. data.remoteIP.push(ip);
  7079. }
  7080. if(data.remotePort.indexOf(port) == -1)
  7081. {
  7082. data.remotePort.push(port);
  7083. }
  7084. if(data.localIP.indexOf(localIP) == -1)
  7085. {
  7086. data.localIP.push(localIP);
  7087. }
  7088. if(data.localPort.indexOf(localPort) == -1)
  7089. {
  7090. data.localPort.push(localPort);
  7091. }
  7092. }
  7093. var local_address_key = "connectionindicator.localaddress";
  7094. var remote_address_key = "connectionindicator.remoteaddress";
  7095. var localTransport =
  7096. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7097. local_address_key +"' data-i18n-options='" +
  7098. JSON.stringify({count: data.localIP.length}) + "'>" +
  7099. translate(local_address_key, {count: data.localIP.length}) +
  7100. "</span></td><td> " +
  7101. ConnectionIndicator.getStringFromArray(data.localIP) +
  7102. "</td></tr>";
  7103. transport =
  7104. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7105. remote_address_key + "' data-i18n-options='" +
  7106. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7107. translate(remote_address_key,
  7108. {count: data.remoteIP.length}) +
  7109. "</span></td><td> " +
  7110. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7111. "</td></tr>";
  7112. var key_remote = "connectionindicator.remoteport",
  7113. key_local = "connectionindicator.localport";
  7114. transport += "<tr>" +
  7115. "<td>" +
  7116. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7117. "' data-i18n-options='" +
  7118. JSON.stringify({count: this.transport.length}) + "'>" +
  7119. translate(key_remote, {count: this.transport.length}) +
  7120. "</span></td><td>";
  7121. localTransport += "<tr>" +
  7122. "<td>" +
  7123. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7124. "' data-i18n-options='" +
  7125. JSON.stringify({count: this.transport.length}) + "'>" +
  7126. translate(key_local, {count: this.transport.length}) +
  7127. "</span></td><td>";
  7128. transport +=
  7129. ConnectionIndicator.getStringFromArray(data.remotePort);
  7130. localTransport +=
  7131. ConnectionIndicator.getStringFromArray(data.localPort);
  7132. transport += "</td></tr>";
  7133. transport += localTransport + "</td></tr>";
  7134. transport +="<tr>" +
  7135. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7136. translate("connectionindicator.transport") + "</span></td>" +
  7137. "<td>" + this.transport[0].type + "</td></tr>";
  7138. }
  7139. result += "<table style='width:100%'>" +
  7140. "<tr>" +
  7141. "<td>" +
  7142. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7143. translate("connectionindicator.bandwidth") + "</span>" +
  7144. "</td><td>" +
  7145. "<span class='jitsipopover_green'>&darr;</span>" +
  7146. downloadBandwidth +
  7147. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7148. uploadBandwidth + "</td></tr>";
  7149. result += transport + "</table>";
  7150. }
  7151. return result;
  7152. };
  7153. /**
  7154. * Shows or hide the additional information.
  7155. */
  7156. ConnectionIndicator.prototype.showMore = function () {
  7157. this.showMoreValue = !this.showMoreValue;
  7158. this.updatePopoverData();
  7159. };
  7160. function createIcon(classes)
  7161. {
  7162. var icon = document.createElement("span");
  7163. for(var i in classes)
  7164. {
  7165. icon.classList.add(classes[i]);
  7166. }
  7167. icon.appendChild(
  7168. document.createElement("i")).classList.add("icon-connection");
  7169. return icon;
  7170. }
  7171. /**
  7172. * Creates the indicator
  7173. */
  7174. ConnectionIndicator.prototype.create = function () {
  7175. this.connectionIndicatorContainer = document.createElement("div");
  7176. this.connectionIndicatorContainer.className = "connectionindicator";
  7177. this.connectionIndicatorContainer.style.display = "none";
  7178. this.videoContainer.container.appendChild(this.connectionIndicatorContainer);
  7179. this.popover = new JitsiPopover(
  7180. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7181. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7182. APP.translation.translateString("connectionindicator.na") + "</div>",
  7183. skin: "black"});
  7184. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7185. createIcon(["connection", "connection_empty"]));
  7186. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7187. createIcon(["connection", "connection_full"]));
  7188. };
  7189. /**
  7190. * Removes the indicator
  7191. */
  7192. ConnectionIndicator.prototype.remove = function()
  7193. {
  7194. if (this.connectionIndicatorContainer.parentNode) {
  7195. this.connectionIndicatorContainer.parentNode.removeChild(
  7196. this.connectionIndicatorContainer);
  7197. }
  7198. this.popover.forceHide();
  7199. };
  7200. /**
  7201. * Updates the data of the indicator
  7202. * @param percent the percent of connection quality
  7203. * @param object the statistics data.
  7204. */
  7205. ConnectionIndicator.prototype.updateConnectionQuality =
  7206. function (percent, object) {
  7207. if(percent === null)
  7208. {
  7209. this.connectionIndicatorContainer.style.display = "none";
  7210. this.popover.forceHide();
  7211. return;
  7212. }
  7213. else
  7214. {
  7215. if(this.connectionIndicatorContainer.style.display == "none") {
  7216. this.connectionIndicatorContainer.style.display = "block";
  7217. this.videoContainer.updateIconPositions();
  7218. }
  7219. }
  7220. this.bandwidth = object.bandwidth;
  7221. this.bitrate = object.bitrate;
  7222. this.packetLoss = object.packetLoss;
  7223. this.transport = object.transport;
  7224. if(object.resolution)
  7225. {
  7226. this.resolution = object.resolution;
  7227. }
  7228. for(var quality in ConnectionIndicator.connectionQualityValues)
  7229. {
  7230. if(percent >= quality)
  7231. {
  7232. this.fullIcon.style.width =
  7233. ConnectionIndicator.connectionQualityValues[quality];
  7234. }
  7235. }
  7236. this.updatePopoverData();
  7237. };
  7238. /**
  7239. * Updates the resolution
  7240. * @param resolution the new resolution
  7241. */
  7242. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7243. this.resolution = resolution;
  7244. this.updatePopoverData();
  7245. };
  7246. /**
  7247. * Updates the content of the popover
  7248. */
  7249. ConnectionIndicator.prototype.updatePopoverData = function () {
  7250. this.popover.updateContent(
  7251. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7252. APP.translation.translateElement($(".connection_info"));
  7253. };
  7254. /**
  7255. * Hides the popover
  7256. */
  7257. ConnectionIndicator.prototype.hide = function () {
  7258. this.popover.forceHide();
  7259. };
  7260. /**
  7261. * Hides the indicator
  7262. */
  7263. ConnectionIndicator.prototype.hideIndicator = function () {
  7264. this.connectionIndicatorContainer.style.display = "none";
  7265. if(this.popover)
  7266. this.popover.forceHide();
  7267. };
  7268. module.exports = ConnectionIndicator;
  7269. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7270. var Avatar = require("../avatar/Avatar");
  7271. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7272. var UIUtil = require("../util/UIUtil");
  7273. var UIEvents = require("../../../service/UI/UIEvents");
  7274. var xmpp = require("../../xmpp/xmpp");
  7275. // FIXME: With Temasys we have to re-select everytime
  7276. //var video = $('#largeVideo');
  7277. var currentVideoWidth = null;
  7278. var currentVideoHeight = null;
  7279. // By default we use camera
  7280. var getVideoSize = getCameraVideoSize;
  7281. var getVideoPosition = getCameraVideoPosition;
  7282. var currentSmallVideo = null;
  7283. var oldSmallVideo = null;
  7284. /**
  7285. * Sets the size and position of the given video element.
  7286. *
  7287. * @param video the video element to position
  7288. * @param width the desired video width
  7289. * @param height the desired video height
  7290. * @param horizontalIndent the left and right indent
  7291. * @param verticalIndent the top and bottom indent
  7292. */
  7293. function positionVideo(video,
  7294. width,
  7295. height,
  7296. horizontalIndent,
  7297. verticalIndent,
  7298. animate) {
  7299. if(animate)
  7300. {
  7301. video.animate({
  7302. width: width,
  7303. height: height,
  7304. top: verticalIndent,
  7305. bottom: verticalIndent,
  7306. left: horizontalIndent,
  7307. right: horizontalIndent
  7308. },
  7309. {
  7310. queue: false,
  7311. duration: 500
  7312. });
  7313. }
  7314. else
  7315. {
  7316. video.width(width);
  7317. video.height(height);
  7318. video.css({ top: verticalIndent + 'px',
  7319. bottom: verticalIndent + 'px',
  7320. left: horizontalIndent + 'px',
  7321. right: horizontalIndent + 'px'});
  7322. }
  7323. }
  7324. /**
  7325. * Returns an array of the video dimensions, so that it keeps it's aspect
  7326. * ratio and fits available area with it's larger dimension. This method
  7327. * ensures that whole video will be visible and can leave empty areas.
  7328. *
  7329. * @return an array with 2 elements, the video width and the video height
  7330. */
  7331. function getDesktopVideoSize(videoWidth,
  7332. videoHeight,
  7333. videoSpaceWidth,
  7334. videoSpaceHeight) {
  7335. if (!videoWidth)
  7336. videoWidth = currentVideoWidth;
  7337. if (!videoHeight)
  7338. videoHeight = currentVideoHeight;
  7339. var aspectRatio = videoWidth / videoHeight;
  7340. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7341. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7342. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7343. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7344. {
  7345. availableHeight = videoSpaceHeight;
  7346. availableWidth = availableHeight * aspectRatio;
  7347. }
  7348. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7349. {
  7350. availableWidth = videoSpaceWidth;
  7351. availableHeight = availableWidth / aspectRatio;
  7352. }
  7353. return [availableWidth, availableHeight];
  7354. }
  7355. /**
  7356. * Returns an array of the video horizontal and vertical indents,
  7357. * so that if fits its parent.
  7358. *
  7359. * @return an array with 2 elements, the horizontal indent and the vertical
  7360. * indent
  7361. */
  7362. function getCameraVideoPosition(videoWidth,
  7363. videoHeight,
  7364. videoSpaceWidth,
  7365. videoSpaceHeight) {
  7366. // Parent height isn't completely calculated when we position the video in
  7367. // full screen mode and this is why we use the screen height in this case.
  7368. // Need to think it further at some point and implement it properly.
  7369. var isFullScreen = document.fullScreen ||
  7370. document.mozFullScreen ||
  7371. document.webkitIsFullScreen;
  7372. if (isFullScreen)
  7373. videoSpaceHeight = window.innerHeight;
  7374. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7375. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7376. return [horizontalIndent, verticalIndent];
  7377. }
  7378. /**
  7379. * Returns an array of the video horizontal and vertical indents.
  7380. * Centers horizontally and top aligns vertically.
  7381. *
  7382. * @return an array with 2 elements, the horizontal indent and the vertical
  7383. * indent
  7384. */
  7385. function getDesktopVideoPosition(videoWidth,
  7386. videoHeight,
  7387. videoSpaceWidth,
  7388. videoSpaceHeight) {
  7389. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7390. var verticalIndent = 0;// Top aligned
  7391. return [horizontalIndent, verticalIndent];
  7392. }
  7393. /**
  7394. * Returns an array of the video dimensions, so that it covers the screen.
  7395. * It leaves no empty areas, but some parts of the video might not be visible.
  7396. *
  7397. * @return an array with 2 elements, the video width and the video height
  7398. */
  7399. function getCameraVideoSize(videoWidth,
  7400. videoHeight,
  7401. videoSpaceWidth,
  7402. videoSpaceHeight) {
  7403. if (!videoWidth)
  7404. videoWidth = currentVideoWidth;
  7405. if (!videoHeight)
  7406. videoHeight = currentVideoHeight;
  7407. var aspectRatio = videoWidth / videoHeight;
  7408. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7409. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7410. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7411. availableHeight = videoSpaceHeight;
  7412. availableWidth = availableHeight * aspectRatio;
  7413. }
  7414. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7415. availableWidth = videoSpaceWidth;
  7416. availableHeight = availableWidth / aspectRatio;
  7417. }
  7418. return [availableWidth, availableHeight];
  7419. }
  7420. /**
  7421. * Updates the src of the active speaker avatar
  7422. * @param jid of the current active speaker
  7423. */
  7424. function updateActiveSpeakerAvatarSrc() {
  7425. var avatar = $("#activeSpeakerAvatar")[0];
  7426. var jid = currentSmallVideo.peerJid;
  7427. var url = Avatar.getActiveSpeakerUrl(jid);
  7428. if (avatar.src === url)
  7429. return;
  7430. var isMuted = null;
  7431. if (!currentSmallVideo.isLocal &&
  7432. !LargeVideo.VideoLayout.isInLastN(currentSmallVideo.getResourceJid())) {
  7433. isMuted = true;
  7434. }
  7435. else
  7436. {
  7437. isMuted = APP.RTC.isVideoMuted(jid);
  7438. }
  7439. if (jid && isMuted !== null) {
  7440. avatar.src = url;
  7441. $("#largeVideo").css("visibility", isMuted ? "hidden" : "visible");
  7442. currentSmallVideo.showAvatar(isMuted);
  7443. }
  7444. }
  7445. function changeVideo(isVisible) {
  7446. updateActiveSpeakerAvatarSrc();
  7447. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7448. var videoTransform = document.getElementById('largeVideo')
  7449. .style.webkitTransform;
  7450. var flipX = currentSmallVideo.flipX;
  7451. if (flipX && videoTransform !== 'scaleX(-1)') {
  7452. document.getElementById('largeVideo').style.webkitTransform
  7453. = "scaleX(-1)";
  7454. }
  7455. else if (!flipX && videoTransform === 'scaleX(-1)') {
  7456. document.getElementById('largeVideo').style.webkitTransform
  7457. = "none";
  7458. }
  7459. var isDesktop = APP.RTC.isVideoSrcDesktop(currentSmallVideo.peerJid);
  7460. // Change the way we'll be measuring and positioning large video
  7461. getVideoSize = isDesktop
  7462. ? getDesktopVideoSize
  7463. : getCameraVideoSize;
  7464. getVideoPosition = isDesktop
  7465. ? getDesktopVideoPosition
  7466. : getCameraVideoPosition;
  7467. // Only if the large video is currently visible.
  7468. // Disable previous dominant speaker video.
  7469. if (oldSmallVideo) {
  7470. oldSmallVideo.enableDominantSpeaker(false);
  7471. }
  7472. // Enable new dominant speaker in the remote videos section.
  7473. if (currentSmallVideo) {
  7474. currentSmallVideo.enableDominantSpeaker(true);
  7475. }
  7476. if (isVisible) {
  7477. $('#largeVideo').fadeIn(300);
  7478. }
  7479. if(oldSmallVideo)
  7480. oldSmallVideo.showAvatar();
  7481. }
  7482. var LargeVideo = {
  7483. init: function (VideoLayout, emitter) {
  7484. this.VideoLayout = VideoLayout;
  7485. this.eventEmitter = emitter;
  7486. var self = this;
  7487. // Listen for large video size updates
  7488. var largeVideo = $('#largeVideo')[0];
  7489. var onplaying = function (arg1, arg2, arg3) {
  7490. // re-select
  7491. if (RTCBrowserType.isTemasysPluginUsed())
  7492. largeVideo = $('#largeVideo')[0];
  7493. currentVideoWidth = largeVideo.videoWidth;
  7494. currentVideoHeight = largeVideo.videoHeight;
  7495. self.position(currentVideoWidth, currentVideoHeight);
  7496. };
  7497. largeVideo.onplaying = onplaying;
  7498. },
  7499. /**
  7500. * Indicates if the large video is currently visible.
  7501. *
  7502. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7503. */
  7504. isLargeVideoVisible: function() {
  7505. return $('#largeVideo').is(':visible');
  7506. },
  7507. /**
  7508. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7509. */
  7510. isCurrentlyOnLarge: function (resourceJid) {
  7511. return currentSmallVideo && resourceJid &&
  7512. currentSmallVideo.getResourceJid() === resourceJid;
  7513. },
  7514. /**
  7515. * Updates the large video with the given new video source.
  7516. */
  7517. updateLargeVideo: function(resourceJid, forceUpdate) {
  7518. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7519. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7520. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7521. $('#activeSpeaker').css('visibility', 'hidden');
  7522. if(currentSmallVideo) {
  7523. oldSmallVideo = currentSmallVideo;
  7524. } else {
  7525. oldSmallVideo = null;
  7526. }
  7527. currentSmallVideo = newSmallVideo;
  7528. var oldJid = null;
  7529. if(oldSmallVideo)
  7530. oldJid = oldSmallVideo.peerJid;
  7531. if (oldJid !== resourceJid) {
  7532. // we want the notification to trigger even if userJid is undefined,
  7533. // or null.
  7534. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  7535. resourceJid);
  7536. }
  7537. $('#largeVideo').fadeOut(300,
  7538. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7539. } else {
  7540. if(currentSmallVideo) {
  7541. currentSmallVideo.showAvatar();
  7542. }
  7543. }
  7544. },
  7545. /**
  7546. * Shows/hides the large video.
  7547. */
  7548. setLargeVideoVisible: function(isVisible) {
  7549. if (isVisible) {
  7550. $('#largeVideo').css({visibility: 'visible'});
  7551. $('.watermark').css({visibility: 'visible'});
  7552. if(currentSmallVideo)
  7553. currentSmallVideo.enableDominantSpeaker(true);
  7554. }
  7555. else {
  7556. $('#largeVideo').css({visibility: 'hidden'});
  7557. $('#activeSpeaker').css('visibility', 'hidden');
  7558. $('.watermark').css({visibility: 'hidden'});
  7559. if(currentSmallVideo)
  7560. currentSmallVideo.enableDominantSpeaker(false);
  7561. }
  7562. },
  7563. onVideoTypeChanged: function (jid) {
  7564. var resourceJid = Strophe.getResourceFromJid(jid);
  7565. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7566. {
  7567. var isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7568. getVideoSize = isDesktop
  7569. ? getDesktopVideoSize
  7570. : getCameraVideoSize;
  7571. getVideoPosition = isDesktop
  7572. ? getDesktopVideoPosition
  7573. : getCameraVideoPosition;
  7574. this.position(null, null);
  7575. }
  7576. },
  7577. /**
  7578. * Positions the large video.
  7579. *
  7580. * @param videoWidth the stream video width
  7581. * @param videoHeight the stream video height
  7582. */
  7583. position: function (videoWidth, videoHeight,
  7584. videoSpaceWidth, videoSpaceHeight, animate) {
  7585. if(!videoSpaceWidth)
  7586. videoSpaceWidth = $('#videospace').width();
  7587. if(!videoSpaceHeight)
  7588. videoSpaceHeight = window.innerHeight;
  7589. var videoSize = getVideoSize(videoWidth,
  7590. videoHeight,
  7591. videoSpaceWidth,
  7592. videoSpaceHeight);
  7593. var largeVideoWidth = videoSize[0];
  7594. var largeVideoHeight = videoSize[1];
  7595. var videoPosition = getVideoPosition(largeVideoWidth,
  7596. largeVideoHeight,
  7597. videoSpaceWidth,
  7598. videoSpaceHeight);
  7599. var horizontalIndent = videoPosition[0];
  7600. var verticalIndent = videoPosition[1];
  7601. positionVideo($('#largeVideo'),
  7602. largeVideoWidth,
  7603. largeVideoHeight,
  7604. horizontalIndent, verticalIndent, animate);
  7605. },
  7606. isLargeVideoOnTop: function () {
  7607. var Etherpad = require("../etherpad/Etherpad");
  7608. var Prezi = require("../prezi/Prezi");
  7609. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  7610. },
  7611. resize: function (animate, isVisible, completeFunction) {
  7612. var availableHeight = window.innerHeight;
  7613. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7614. if (availableWidth < 0 || availableHeight < 0) return;
  7615. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7616. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7617. $('#activeSpeaker').css('top', top);
  7618. if(animate)
  7619. {
  7620. $('#videospace').animate({
  7621. right: window.innerWidth - availableWidth,
  7622. width: availableWidth,
  7623. height: availableHeight
  7624. },
  7625. {
  7626. queue: false,
  7627. duration: 500,
  7628. complete: completeFunction
  7629. });
  7630. $('#largeVideoContainer').animate({
  7631. width: availableWidth,
  7632. height: availableHeight
  7633. },
  7634. {
  7635. queue: false,
  7636. duration: 500
  7637. });
  7638. }
  7639. else
  7640. {
  7641. $('#videospace').width(availableWidth);
  7642. $('#videospace').height(availableHeight);
  7643. $('#largeVideoContainer').width(availableWidth);
  7644. $('#largeVideoContainer').height(availableHeight);
  7645. }
  7646. return [availableWidth, availableHeight];
  7647. },
  7648. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7649. var size = this.resize(true, isVisible, completeFunction);
  7650. this.position(null, null, size[0], size[1], true);
  7651. },
  7652. getResourceJid: function () {
  7653. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7654. },
  7655. updateAvatar: function (resourceJid) {
  7656. if (resourceJid === this.getResourceJid()) {
  7657. updateActiveSpeakerAvatarSrc();
  7658. }
  7659. },
  7660. showAvatar: function (resourceJid, show) {
  7661. if(this.getResourceJid() === resourceJid
  7662. && LargeVideo.isLargeVideoOnTop())
  7663. {
  7664. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7665. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7666. return true;
  7667. }
  7668. return false;
  7669. }
  7670. }
  7671. module.exports = LargeVideo;
  7672. },{"../../../service/UI/UIEvents":102,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":66,"../avatar/Avatar":16,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../util/UIUtil":33}],36:[function(require,module,exports){
  7673. var SmallVideo = require("./SmallVideo");
  7674. var ConnectionIndicator = require("./ConnectionIndicator");
  7675. var NicknameHandler = require("../util/NicknameHandler");
  7676. var UIUtil = require("../util/UIUtil");
  7677. var LargeVideo = require("./LargeVideo");
  7678. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7679. function LocalVideo(VideoLayout)
  7680. {
  7681. this.videoSpanId = "localVideoContainer";
  7682. this.container = $("#localVideoContainer").get(0);
  7683. this.VideoLayout = VideoLayout;
  7684. this.flipX = true;
  7685. this.isLocal = true;
  7686. this.peerJid = null;
  7687. }
  7688. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7689. LocalVideo.prototype.constructor = LocalVideo;
  7690. /**
  7691. * Creates the edit display name button.
  7692. *
  7693. * @returns the edit button
  7694. */
  7695. function createEditDisplayNameButton() {
  7696. var editButton = document.createElement('a');
  7697. editButton.className = 'displayname';
  7698. UIUtil.setTooltip(editButton,
  7699. "videothumbnail.editnickname",
  7700. "top");
  7701. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7702. return editButton;
  7703. }
  7704. /**
  7705. * Sets the display name for the given video span id.
  7706. */
  7707. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7708. if (!this.container) {
  7709. console.warn(
  7710. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  7711. return;
  7712. }
  7713. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7714. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7715. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7716. // If we already have a display name for this video.
  7717. if (nameSpan.length > 0) {
  7718. if (nameSpan.text() !== displayName) {
  7719. if (displayName && displayName.length > 0)
  7720. {
  7721. var meHTML = APP.translation.generateTranslationHTML("me");
  7722. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7723. }
  7724. else
  7725. $('#localDisplayName').html(defaultLocalDisplayName);
  7726. }
  7727. } else {
  7728. var editButton = createEditDisplayNameButton();
  7729. nameSpan = document.createElement('span');
  7730. nameSpan.className = 'displayname';
  7731. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7732. if (displayName && displayName.length > 0) {
  7733. var meHTML = APP.translation.generateTranslationHTML("me");
  7734. nameSpan.innerHTML = displayName + meHTML;
  7735. }
  7736. else {
  7737. nameSpan.innerHTML = defaultLocalDisplayName;
  7738. }
  7739. nameSpan.id = 'localDisplayName';
  7740. this.container.appendChild(editButton);
  7741. //translates popover of edit button
  7742. APP.translation.translateElement($("a.displayname"));
  7743. var editableText = document.createElement('input');
  7744. editableText.className = 'displayname';
  7745. editableText.type = 'text';
  7746. editableText.id = 'editDisplayName';
  7747. if (displayName && displayName.length) {
  7748. editableText.value = displayName;
  7749. }
  7750. var defaultNickname = APP.translation.translateString(
  7751. "defaultNickname", {name: "Jane Pink"});
  7752. editableText.setAttribute('style', 'display:none;');
  7753. editableText.setAttribute('data-18n',
  7754. '[placeholder]defaultNickname');
  7755. editableText.setAttribute("data-i18n-options",
  7756. JSON.stringify({name: "Jane Pink"}));
  7757. editableText.setAttribute("placeholder", defaultNickname);
  7758. this.container.appendChild(editableText);
  7759. var self = this;
  7760. $('#localVideoContainer .displayname')
  7761. .bind("click", function (e) {
  7762. e.preventDefault();
  7763. e.stopPropagation();
  7764. $('#localDisplayName').hide();
  7765. $('#editDisplayName').show();
  7766. $('#editDisplayName').focus();
  7767. $('#editDisplayName').select();
  7768. $('#editDisplayName').one("focusout", function (e) {
  7769. self.VideoLayout.inputDisplayNameHandler(this.value);
  7770. });
  7771. $('#editDisplayName').on('keydown', function (e) {
  7772. if (e.keyCode === 13) {
  7773. e.preventDefault();
  7774. self.VideoLayout.inputDisplayNameHandler(this.value);
  7775. }
  7776. });
  7777. });
  7778. }
  7779. }
  7780. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7781. NicknameHandler.setNickname(name);
  7782. if (!$('#localDisplayName').is(":visible")) {
  7783. if (NicknameHandler.getNickname())
  7784. {
  7785. var meHTML = APP.translation.generateTranslationHTML("me");
  7786. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  7787. }
  7788. else
  7789. {
  7790. var defaultHTML = APP.translation.generateTranslationHTML(
  7791. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7792. $('#localDisplayName')
  7793. .html(defaultHTML);
  7794. }
  7795. $('#localDisplayName').show();
  7796. }
  7797. $('#editDisplayName').hide();
  7798. }
  7799. LocalVideo.prototype.createConnectionIndicator = function()
  7800. {
  7801. if(this.connectionIndicator)
  7802. return;
  7803. this.connectionIndicator
  7804. = new ConnectionIndicator(this, null);
  7805. }
  7806. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7807. var self = this;
  7808. function localVideoClick(event) {
  7809. // FIXME: with Temasys plugin event arg is not an event, but
  7810. // the clicked object itself, so we have to skip this call
  7811. if (event.stopPropagation) {
  7812. event.stopPropagation();
  7813. }
  7814. self.VideoLayout.handleVideoThumbClicked(
  7815. false,
  7816. APP.xmpp.myResource());
  7817. }
  7818. $('#localVideoContainer').off('click');
  7819. $('#localVideoContainer').on('click', localVideoClick);
  7820. // Add hover handler
  7821. $('#localVideoContainer').hover(
  7822. function() {
  7823. self.showDisplayName(true);
  7824. },
  7825. function() {
  7826. if (!LargeVideo.isLargeVideoVisible() ||
  7827. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  7828. self.showDisplayName(false);
  7829. }
  7830. );
  7831. if(isMuted)
  7832. {
  7833. APP.UI.setVideoMute(true);
  7834. return;
  7835. }
  7836. this.flipX = (stream.videoType == "screen")? false : true;
  7837. var localVideo = document.createElement('video');
  7838. localVideo.id = 'localVideo_' +
  7839. APP.RTC.getStreamID(stream.getOriginalStream());
  7840. if (!RTCBrowserType.isIExplorer()) {
  7841. localVideo.autoplay = true;
  7842. localVideo.volume = 0; // is it required if audio is separated ?
  7843. }
  7844. localVideo.oncontextmenu = function () { return false; };
  7845. var localVideoContainer = document.getElementById('localVideoWrapper');
  7846. localVideoContainer.appendChild(localVideo);
  7847. var localVideoSelector = $('#' + localVideo.id);
  7848. // Add click handler to both video and video wrapper elements in case
  7849. // there's no video.
  7850. // onclick has to be used with Temasys plugin
  7851. localVideo.onclick = localVideoClick;
  7852. if (this.flipX) {
  7853. localVideoSelector.addClass("flipVideoX");
  7854. }
  7855. // Attach WebRTC stream
  7856. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7857. // Add stream ended handler
  7858. stream.getOriginalStream().onended = function () {
  7859. // We have to re-select after attach when Temasys plugin is used,
  7860. // because <video> element is replaced with <object>
  7861. localVideo = $('#' + localVideo.id)[0];
  7862. localVideoContainer.removeChild(localVideo);
  7863. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7864. };
  7865. };
  7866. LocalVideo.prototype.joined = function (jid) {
  7867. this.peerJid = jid;
  7868. };
  7869. LocalVideo.prototype.getResourceJid = function () {
  7870. var myResource = APP.xmpp.myResource();
  7871. if (!myResource) {
  7872. console.error("Requested local resource before we're in the MUC");
  7873. }
  7874. return myResource;
  7875. };
  7876. module.exports = LocalVideo;
  7877. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7878. var ConnectionIndicator = require("./ConnectionIndicator");
  7879. var SmallVideo = require("./SmallVideo");
  7880. var AudioLevels = require("../audio_levels/AudioLevels");
  7881. var LargeVideo = require("./LargeVideo");
  7882. var Avatar = require("../avatar/Avatar");
  7883. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7884. function RemoteVideo(peerJid, VideoLayout)
  7885. {
  7886. this.peerJid = peerJid;
  7887. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7888. this.videoSpanId = 'participant_' + this.resourceJid;
  7889. this.VideoLayout = VideoLayout;
  7890. this.addRemoteVideoContainer();
  7891. this.connectionIndicator = new ConnectionIndicator(
  7892. this, this.peerJid);
  7893. this.setDisplayName();
  7894. var nickfield = document.createElement('span');
  7895. nickfield.className = "nick";
  7896. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7897. this.container.appendChild(nickfield);
  7898. this.flipX = false;
  7899. this.isLocal = false;
  7900. }
  7901. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7902. RemoteVideo.prototype.constructor = RemoteVideo;
  7903. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7904. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7905. if (APP.xmpp.isModerator())
  7906. this.addRemoteVideoMenu();
  7907. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7908. return this.container;
  7909. };
  7910. /**
  7911. * Adds the remote video menu element for the given <tt>jid</tt> in the
  7912. * given <tt>parentElement</tt>.
  7913. *
  7914. * @param jid the jid indicating the video for which we're adding a menu.
  7915. * @param parentElement the parent element where this menu will be added
  7916. */
  7917. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  7918. var spanElement = document.createElement('span');
  7919. spanElement.className = 'remotevideomenu';
  7920. this.container.appendChild(spanElement);
  7921. var menuElement = document.createElement('i');
  7922. menuElement.className = 'fa fa-angle-down';
  7923. menuElement.title = 'Remote user controls';
  7924. spanElement.appendChild(menuElement);
  7925. var popupmenuElement = document.createElement('ul');
  7926. popupmenuElement.className = 'popupmenu';
  7927. popupmenuElement.id
  7928. = 'remote_popupmenu_' + this.getResourceJid();
  7929. spanElement.appendChild(popupmenuElement);
  7930. var muteMenuItem = document.createElement('li');
  7931. var muteLinkItem = document.createElement('a');
  7932. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  7933. if (!this.isMuted) {
  7934. muteLinkItem.innerHTML = mutedIndicator +
  7935. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7936. muteLinkItem.className = 'mutelink';
  7937. }
  7938. else {
  7939. muteLinkItem.innerHTML = mutedIndicator +
  7940. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7941. muteLinkItem.className = 'mutelink disabled';
  7942. }
  7943. var self = this;
  7944. muteLinkItem.onclick = function(){
  7945. if ($(this).attr('disabled') != undefined) {
  7946. event.preventDefault();
  7947. }
  7948. var isMute = self.isMuted == true;
  7949. APP.xmpp.setMute(self.peerJid, !isMute);
  7950. popupmenuElement.setAttribute('style', 'display:none;');
  7951. if (isMute) {
  7952. this.innerHTML = mutedIndicator +
  7953. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7954. this.className = 'mutelink disabled';
  7955. }
  7956. else {
  7957. this.innerHTML = mutedIndicator +
  7958. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7959. this.className = 'mutelink';
  7960. }
  7961. };
  7962. muteMenuItem.appendChild(muteLinkItem);
  7963. popupmenuElement.appendChild(muteMenuItem);
  7964. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  7965. var ejectMenuItem = document.createElement('li');
  7966. var ejectLinkItem = document.createElement('a');
  7967. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  7968. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  7969. ejectLinkItem.onclick = function(){
  7970. APP.xmpp.eject(self.peerJid);
  7971. popupmenuElement.setAttribute('style', 'display:none;');
  7972. };
  7973. ejectMenuItem.appendChild(ejectLinkItem);
  7974. popupmenuElement.appendChild(ejectMenuItem);
  7975. var paddingSpan = document.createElement('span');
  7976. paddingSpan.className = 'popupmenuPadding';
  7977. popupmenuElement.appendChild(paddingSpan);
  7978. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  7979. }
  7980. /**
  7981. * Removes the remote stream element corresponding to the given stream and
  7982. * parent container.
  7983. *
  7984. * @param stream the stream
  7985. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  7986. * @param container
  7987. */
  7988. RemoteVideo.prototype.removeRemoteStreamElement = function (stream, isVideo, id) {
  7989. if (!this.container)
  7990. return false;
  7991. var select = null;
  7992. if (isVideo) {
  7993. select = $('#' + id);
  7994. }
  7995. else
  7996. select = $('#' + this.videoSpanId + '>audio');
  7997. // Mark video as removed to cancel waiting loop(if video is removed
  7998. // before has started)
  7999. select.removed = true;
  8000. select.remove();
  8001. var audioCount = $('#' + this.videoSpanId + '>audio').length;
  8002. var videoCount = $('#' + this.videoSpanId + '>' + APP.RTC.getVideoElementName()).length;
  8003. if (!audioCount && !videoCount) {
  8004. console.log("Remove whole user", this.videoSpanId);
  8005. if(this.connectionIndicator)
  8006. this.connectionIndicator.remove();
  8007. // Remove whole container
  8008. if (this.container.parentNode)
  8009. this.container.parentNode.removeChild(this.container);
  8010. this.VideoLayout.resizeThumbnails();
  8011. }
  8012. if (isVideo)
  8013. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8014. };
  8015. RemoteVideo.prototype.waitForPlayback = function (stream) {
  8016. var isVideo = stream.getVideoTracks().length > 0;
  8017. if (!isVideo || stream.id === 'mixedmslabel') {
  8018. return;
  8019. }
  8020. var self = this;
  8021. var resourceJid = this.getResourceJid();
  8022. var sel = this.VideoLayout.getPeerVideoSel(resourceJid);
  8023. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8024. // when video playback starts
  8025. var onPlayingHandler = function () {
  8026. // FIXME: why do i have to do this for FF?
  8027. if (RTCBrowserType.isFirefox()) {
  8028. APP.RTC.attachMediaStream(sel, stream);
  8029. }
  8030. if (RTCBrowserType.isTemasysPluginUsed()) {
  8031. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8032. }
  8033. self.VideoLayout.videoactive(sel, resourceJid);
  8034. sel[0].onplaying = null;
  8035. if (RTCBrowserType.isTemasysPluginUsed()) {
  8036. // 'currentTime' is used to check if the video has started
  8037. // and the value is not set by the plugin, so we do it
  8038. sel[0].currentTime = 1;
  8039. }
  8040. };
  8041. sel[0].onplaying = onPlayingHandler;
  8042. };
  8043. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8044. if (!this.container)
  8045. return;
  8046. var self = this;
  8047. var isVideo = stream.getVideoTracks().length > 0;
  8048. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8049. var newElementId = streamElement.id;
  8050. this.container.appendChild(streamElement);
  8051. var sel = $('#' + newElementId);
  8052. sel.hide();
  8053. // If the container is currently visible we attach the stream.
  8054. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8055. this.waitForPlayback(stream);
  8056. APP.RTC.attachMediaStream(sel, stream);
  8057. }
  8058. stream.onended = function () {
  8059. console.log('stream ended', this);
  8060. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8061. };
  8062. // Name of video element name is different for IE/Safari
  8063. var videoElem = APP.RTC.getVideoElementName();
  8064. // Add click handler.
  8065. var onClickHandler = function (event) {
  8066. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8067. // On IE we need to populate this handler on video <object>
  8068. // and it does not give event instance as an argument,
  8069. // so we check here for methods.
  8070. if (event.stopPropagation && event.preventDefault) {
  8071. event.stopPropagation();
  8072. event.preventDefault();
  8073. }
  8074. return false;
  8075. };
  8076. this.container.onclick = onClickHandler;
  8077. // reselect
  8078. if (RTCBrowserType.isTemasysPluginUsed())
  8079. sel = $('#' + newElementId);
  8080. sel[0].onclick = onClickHandler;
  8081. //FIXME
  8082. // Add hover handler
  8083. $(this.container).hover(
  8084. function() {
  8085. self.showDisplayName(true);
  8086. },
  8087. function() {
  8088. // If the video has been "pinned" by the user we want to
  8089. // keep the display name on place.
  8090. if (!LargeVideo.isLargeVideoVisible() ||
  8091. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8092. self.showDisplayName(false);
  8093. }
  8094. );
  8095. },
  8096. /**
  8097. * Show/hide peer container for the given resourceJid.
  8098. */
  8099. RemoteVideo.prototype.showPeerContainer = function (state) {
  8100. if (!this.container)
  8101. return;
  8102. var isHide = state === 'hide';
  8103. var resizeThumbnails = false;
  8104. if (!isHide) {
  8105. if (!$(this.container).is(':visible')) {
  8106. resizeThumbnails = true;
  8107. $(this.container).show();
  8108. }
  8109. this.showAvatar(state !== 'show');
  8110. }
  8111. else if ($(this.container).is(':visible') && isHide)
  8112. {
  8113. resizeThumbnails = true;
  8114. $(this.container).hide();
  8115. if(this.connectionIndicator)
  8116. this.connectionIndicator.hide();
  8117. }
  8118. if (resizeThumbnails) {
  8119. this.VideoLayout.resizeThumbnails();
  8120. }
  8121. // We want to be able to pin a participant from the contact list, even
  8122. // if he's not in the lastN set!
  8123. // ContactList.setClickable(resourceJid, !isHide);
  8124. };
  8125. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8126. if(this.connectionIndicator)
  8127. this.connectionIndicator.remove();
  8128. }
  8129. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8130. if(this.connectionIndicator)
  8131. this.connectionIndicator.hide();
  8132. }
  8133. /**
  8134. * Updates the remote video menu.
  8135. *
  8136. * @param jid the jid indicating the video for which we're adding a menu.
  8137. * @param isMuted indicates the current mute state
  8138. */
  8139. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8140. var muteMenuItem
  8141. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8142. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8143. if (muteMenuItem.length) {
  8144. var muteLink = muteMenuItem.get(0);
  8145. if (isMuted === 'true') {
  8146. muteLink.innerHTML = mutedIndicator + ' Muted';
  8147. muteLink.className = 'mutelink disabled';
  8148. }
  8149. else {
  8150. muteLink.innerHTML = mutedIndicator + ' Mute';
  8151. muteLink.className = 'mutelink';
  8152. }
  8153. }
  8154. };
  8155. /**
  8156. * Sets the display name for the given video span id.
  8157. */
  8158. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8159. if (!this.container) {
  8160. console.warn(
  8161. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  8162. return;
  8163. }
  8164. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8165. // If we already have a display name for this video.
  8166. if (nameSpan.length > 0) {
  8167. if (displayName && displayName.length > 0)
  8168. {
  8169. $('#' + this.videoSpanId + '_name').html(displayName);
  8170. }
  8171. else if (key && key.length > 0)
  8172. {
  8173. var nameHtml = APP.translation.generateTranslationHTML(key);
  8174. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8175. }
  8176. else
  8177. $('#' + this.videoSpanId + '_name').text(
  8178. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8179. } else {
  8180. nameSpan = document.createElement('span');
  8181. nameSpan.className = 'displayname';
  8182. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8183. if (displayName && displayName.length > 0) {
  8184. nameSpan.innerText = displayName;
  8185. }
  8186. else
  8187. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8188. nameSpan.id = this.videoSpanId + '_name';
  8189. }
  8190. }
  8191. /**
  8192. * Removes remote video menu element from video element identified by
  8193. * given <tt>videoElementId</tt>.
  8194. *
  8195. * @param videoElementId the id of local or remote video element.
  8196. */
  8197. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8198. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8199. if (menuSpan.length) {
  8200. menuSpan.remove();
  8201. }
  8202. };
  8203. RemoteVideo.prototype.getResourceJid = function () {
  8204. if (!this.resourceJid) {
  8205. console.error("Undefined resource jid");
  8206. }
  8207. return this.resourceJid;
  8208. };
  8209. RemoteVideo.createContainer = function (spanId) {
  8210. var container = document.createElement('span');
  8211. container.id = spanId;
  8212. container.className = 'videocontainer';
  8213. var remotes = document.getElementById('remoteVideos');
  8214. return remotes.appendChild(container);
  8215. };
  8216. module.exports = RemoteVideo;
  8217. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8218. var Avatar = require("../avatar/Avatar");
  8219. var UIUtil = require("../util/UIUtil");
  8220. var LargeVideo = require("./LargeVideo");
  8221. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8222. function SmallVideo(){
  8223. this.isMuted = false;
  8224. this.hasAvatar = false;
  8225. }
  8226. function setVisibility(selector, show) {
  8227. if (selector && selector.length > 0) {
  8228. selector.css("visibility", show ? "visible" : "hidden");
  8229. }
  8230. }
  8231. SmallVideo.prototype.showDisplayName = function(isShow) {
  8232. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8233. if (isShow) {
  8234. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8235. nameSpan.setAttribute("style", "display:inline-block;");
  8236. }
  8237. else {
  8238. if (nameSpan)
  8239. nameSpan.setAttribute("style", "display:none;");
  8240. }
  8241. };
  8242. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8243. if(!this.container)
  8244. return;
  8245. $("#" + this.videoSpanId + " > .noMic").remove();
  8246. $("#" + this.videoSpanId + " > .noVideo").remove();
  8247. if(!devices.audio)
  8248. {
  8249. this.container.appendChild(
  8250. document.createElement("div")).setAttribute("class","noMic");
  8251. }
  8252. if(!devices.video)
  8253. {
  8254. this.container.appendChild(
  8255. document.createElement("div")).setAttribute("class","noVideo");
  8256. }
  8257. if(!devices.audio && !devices.video)
  8258. {
  8259. $("#" + this.videoSpanId + " > .noMic").css("background-position", "75%");
  8260. $("#" + this.videoSpanId + " > .noVideo").css("background-position", "25%");
  8261. $("#" + this.videoSpanId + " > .noVideo").css("background-color", "transparent");
  8262. }
  8263. }
  8264. /**
  8265. * Shows the presence status message for the given video.
  8266. */
  8267. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8268. if (!this.container) {
  8269. // No container
  8270. return;
  8271. }
  8272. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8273. if (!statusSpan.length) {
  8274. //Add status span
  8275. statusSpan = document.createElement('span');
  8276. statusSpan.className = 'status';
  8277. statusSpan.id = this.videoSpanId + '_status';
  8278. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8279. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8280. }
  8281. // Display status
  8282. if (statusMsg && statusMsg.length) {
  8283. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8284. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8285. }
  8286. else {
  8287. // Hide
  8288. statusSpan.get(0).setAttribute("style", "display:none;");
  8289. }
  8290. };
  8291. /**
  8292. * Creates an audio or video stream element.
  8293. */
  8294. SmallVideo.createStreamElement = function (sid, stream) {
  8295. var isVideo = stream.getVideoTracks().length > 0;
  8296. var element = isVideo
  8297. ? document.createElement('video')
  8298. : document.createElement('audio');
  8299. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  8300. + sid + '_' + APP.RTC.getStreamID(stream);
  8301. element.id = id;
  8302. if (!RTCBrowserType.isIExplorer()) {
  8303. element.autoplay = true;
  8304. }
  8305. element.oncontextmenu = function () { return false; };
  8306. return element;
  8307. };
  8308. /**
  8309. * Updates the data for the indicator
  8310. * @param id the id of the indicator
  8311. * @param percent the percent for connection quality
  8312. * @param object the data
  8313. */
  8314. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8315. if(this.connectionIndicator)
  8316. this.connectionIndicator.updateConnectionQuality(percent, object);
  8317. }
  8318. SmallVideo.prototype.hideIndicator = function () {
  8319. if(this.connectionIndicator)
  8320. this.connectionIndicator.hideIndicator();
  8321. }
  8322. /**
  8323. * Shows audio muted indicator over small videos.
  8324. * @param {string} isMuted
  8325. */
  8326. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8327. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8328. if (!isMuted) {
  8329. if (audioMutedSpan.length > 0) {
  8330. audioMutedSpan.popover('hide');
  8331. audioMutedSpan.remove();
  8332. }
  8333. }
  8334. else {
  8335. if(audioMutedSpan.length == 0 ) {
  8336. audioMutedSpan = document.createElement('span');
  8337. audioMutedSpan.className = 'audioMuted';
  8338. UIUtil.setTooltip(audioMutedSpan,
  8339. "videothumbnail.mute",
  8340. "top");
  8341. this.container.appendChild(audioMutedSpan);
  8342. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8343. var mutedIndicator = document.createElement('i');
  8344. mutedIndicator.className = 'icon-mic-disabled';
  8345. audioMutedSpan.appendChild(mutedIndicator);
  8346. }
  8347. this.updateIconPositions();
  8348. }
  8349. this.isMuted = isMuted;
  8350. };
  8351. /**
  8352. * Shows video muted indicator over small videos.
  8353. */
  8354. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8355. this.showAvatar(isMuted);
  8356. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8357. if (isMuted === false) {
  8358. if (videoMutedSpan.length > 0) {
  8359. videoMutedSpan.remove();
  8360. }
  8361. }
  8362. else {
  8363. if(videoMutedSpan.length == 0) {
  8364. videoMutedSpan = document.createElement('span');
  8365. videoMutedSpan.className = 'videoMuted';
  8366. this.container.appendChild(videoMutedSpan);
  8367. var mutedIndicator = document.createElement('i');
  8368. mutedIndicator.className = 'icon-camera-disabled';
  8369. UIUtil.setTooltip(mutedIndicator,
  8370. "videothumbnail.videomute",
  8371. "top");
  8372. videoMutedSpan.appendChild(mutedIndicator);
  8373. //translate texts for muted indicator
  8374. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8375. }
  8376. this.updateIconPositions();
  8377. }
  8378. };
  8379. SmallVideo.prototype.enableDominantSpeaker = function (isEnable)
  8380. {
  8381. var resourceJid = this.getResourceJid();
  8382. var displayName = resourceJid;
  8383. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8384. if (nameSpan.length > 0)
  8385. displayName = nameSpan.html();
  8386. console.log("UI enable dominant speaker",
  8387. displayName,
  8388. resourceJid,
  8389. isEnable);
  8390. if (!this.container) {
  8391. return;
  8392. }
  8393. if (isEnable) {
  8394. this.showDisplayName(LargeVideo.isLargeVideoOnTop());
  8395. if (!this.container.classList.contains("dominantspeaker"))
  8396. this.container.classList.add("dominantspeaker");
  8397. }
  8398. else {
  8399. this.showDisplayName(false);
  8400. if (this.container.classList.contains("dominantspeaker"))
  8401. this.container.classList.remove("dominantspeaker");
  8402. }
  8403. this.showAvatar();
  8404. };
  8405. SmallVideo.prototype.updateIconPositions = function () {
  8406. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8407. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8408. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8409. if(connectionIndicator.length > 0
  8410. && connectionIndicator[0].style.display != "none") {
  8411. audioMutedSpan.css({right: "23px"});
  8412. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8413. }
  8414. else
  8415. {
  8416. audioMutedSpan.css({right: "0px"});
  8417. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8418. }
  8419. }
  8420. /**
  8421. * Creates the element indicating the moderator(owner) of the conference.
  8422. *
  8423. * @param parentElement the parent element where the owner indicator will
  8424. * be added
  8425. */
  8426. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8427. // Show moderator indicator
  8428. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8429. if (!indicatorSpan || indicatorSpan.length === 0) {
  8430. indicatorSpan = document.createElement('span');
  8431. indicatorSpan.className = 'focusindicator';
  8432. this.container.appendChild(indicatorSpan);
  8433. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8434. }
  8435. if (indicatorSpan.children().length !== 0)
  8436. return;
  8437. var moderatorIndicator = document.createElement('i');
  8438. moderatorIndicator.className = 'fa fa-star';
  8439. indicatorSpan[0].appendChild(moderatorIndicator);
  8440. UIUtil.setTooltip(indicatorSpan[0],
  8441. "videothumbnail.moderator",
  8442. "top");
  8443. //translates text in focus indicators
  8444. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8445. }
  8446. SmallVideo.prototype.getSrc = function () {
  8447. var videoElement = APP.RTC.getVideoElementName();
  8448. return APP.RTC.getVideoSrc(
  8449. $('#' + this.videoSpanId).find(videoElement).get(0));
  8450. },
  8451. SmallVideo.prototype.focus = function(isFocused)
  8452. {
  8453. if(!isFocused) {
  8454. this.container.classList.remove("videoContainerFocused");
  8455. }
  8456. else
  8457. {
  8458. this.container.classList.add("videoContainerFocused");
  8459. }
  8460. }
  8461. SmallVideo.prototype.hasVideo = function () {
  8462. return $("#" + this.videoSpanId).find(
  8463. APP.RTC.getVideoElementName()).length !== 0;
  8464. }
  8465. /**
  8466. * Hides or shows the user's avatar
  8467. * @param show whether we should show the avatar or not
  8468. * video because there is no dominant speaker and no focused speaker
  8469. */
  8470. SmallVideo.prototype.showAvatar = function (show) {
  8471. if (!this.hasAvatar) {
  8472. if (this.peerJid) {
  8473. // Init avatar
  8474. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8475. } else {
  8476. console.error("Unable to init avatar - no peerjid", this);
  8477. return;
  8478. }
  8479. }
  8480. var resourceJid = this.getResourceJid();
  8481. var videoElem = APP.RTC.getVideoElementName();
  8482. var video = $('#' + this.videoSpanId).find(videoElem);
  8483. var avatar = $('#avatar_' + resourceJid);
  8484. if (show === undefined || show === null) {
  8485. if (!this.isLocal &&
  8486. !this.VideoLayout.isInLastN(resourceJid)) {
  8487. show = true;
  8488. }
  8489. else
  8490. {
  8491. show = APP.RTC.isVideoMuted(this.peerJid);
  8492. }
  8493. }
  8494. if (LargeVideo.showAvatar(resourceJid, show))
  8495. {
  8496. setVisibility(avatar, false);
  8497. setVisibility(video, false);
  8498. } else {
  8499. if (video && video.length > 0) {
  8500. setVisibility(video, !show);
  8501. }
  8502. setVisibility(avatar, show);
  8503. }
  8504. };
  8505. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8506. var thumbnail = $('#' + this.videoSpanId);
  8507. var resourceJid = this.getResourceJid();
  8508. var avatar = $('#avatar_' + resourceJid);
  8509. this.hasAvatar = true;
  8510. // set the avatar in the thumbnail
  8511. if (avatar && avatar.length > 0) {
  8512. avatar[0].src = thumbUrl;
  8513. } else {
  8514. if (thumbnail && thumbnail.length > 0) {
  8515. avatar = document.createElement('img');
  8516. avatar.id = 'avatar_' + resourceJid;
  8517. avatar.className = 'userAvatar';
  8518. avatar.src = thumbUrl;
  8519. thumbnail.append(avatar);
  8520. }
  8521. }
  8522. }
  8523. module.exports = SmallVideo;
  8524. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8525. var AudioLevels = require("../audio_levels/AudioLevels");
  8526. var Avatar = require("../avatar/Avatar");
  8527. var ContactList = require("../side_pannels/contactlist/ContactList");
  8528. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8529. var UIEvents = require("../../../service/UI/UIEvents");
  8530. var RTC = require("../../RTC/RTC");
  8531. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8532. var RemoteVideo = require("./RemoteVideo");
  8533. var LargeVideo = require("./LargeVideo");
  8534. var LocalVideo = require("./LocalVideo");
  8535. var remoteVideos = {};
  8536. var localVideoThumbnail = null;
  8537. var currentDominantSpeaker = null;
  8538. var lastNCount = config.channelLastN;
  8539. var localLastNCount = config.channelLastN;
  8540. var localLastNSet = [];
  8541. var lastNEndpointsCache = [];
  8542. var lastNPickupJid = null;
  8543. var eventEmitter = null;
  8544. /**
  8545. * Currently focused video jid
  8546. * @type {String}
  8547. */
  8548. var focusedVideoResourceJid = null;
  8549. var VideoLayout = (function (my) {
  8550. my.init = function (emitter) {
  8551. eventEmitter = emitter;
  8552. localVideoThumbnail = new LocalVideo(VideoLayout);
  8553. VideoLayout.resizeLargeVideoContainer();
  8554. LargeVideo.init(VideoLayout, emitter);
  8555. };
  8556. my.isInLastN = function(resource) {
  8557. return lastNCount < 0 // lastN is disabled, return true
  8558. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  8559. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  8560. };
  8561. my.changeLocalStream = function (stream, isMuted) {
  8562. VideoLayout.changeLocalVideo(stream, isMuted);
  8563. };
  8564. my.changeLocalAudio = function(stream, isMuted) {
  8565. if (isMuted)
  8566. APP.UI.setAudioMuted(true, true);
  8567. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8568. var localAudio = document.getElementById('localAudio');
  8569. // Writing volume not allowed in IE
  8570. if (!RTCBrowserType.isIExplorer()) {
  8571. localAudio.autoplay = true;
  8572. localAudio.volume = 0;
  8573. }
  8574. };
  8575. my.changeLocalVideo = function(stream, isMuted) {
  8576. // Set default display name.
  8577. localVideoThumbnail.setDisplayName();
  8578. localVideoThumbnail.createConnectionIndicator();
  8579. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8580. localVideoThumbnail.changeVideo(stream, isMuted);
  8581. /* force update if we're currently being displayed */
  8582. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8583. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8584. }
  8585. };
  8586. my.mucJoined = function () {
  8587. var myResourceJid = APP.xmpp.myResource();
  8588. localVideoThumbnail.joined(APP.xmpp.myJid());
  8589. if (!LargeVideo.getResourceJid())
  8590. LargeVideo.updateLargeVideo(myResourceJid, true);
  8591. };
  8592. /**
  8593. * Adds or removes icons for not available camera and microphone.
  8594. * @param resourceJid the jid of user
  8595. * @param devices available devices
  8596. */
  8597. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8598. if(!devices)
  8599. return;
  8600. if(!resourceJid)
  8601. {
  8602. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8603. }
  8604. else
  8605. {
  8606. if(remoteVideos[resourceJid])
  8607. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8608. }
  8609. }
  8610. /**
  8611. * Checks if removed video is currently displayed and tries to display
  8612. * another one instead.
  8613. * @param removedVideoSrc src stream identifier of the video.
  8614. */
  8615. my.updateRemovedVideo = function(resourceJid) {
  8616. if (resourceJid === LargeVideo.getResourceJid()) {
  8617. var newResourceJid;
  8618. // We'll show user's avatar if he is the dominant speaker or if
  8619. // his video thumbnail is pinned
  8620. if (resourceJid === focusedVideoResourceJid ||
  8621. resourceJid === currentDominantSpeaker) {
  8622. newResourceJid = resourceJid;
  8623. } else {
  8624. // Otherwise select last visible video
  8625. newResourceJid = this.electLastVisibleVideo();
  8626. }
  8627. LargeVideo.updateLargeVideo(newResourceJid);
  8628. }
  8629. };
  8630. my.electLastVisibleVideo = function() {
  8631. // pick the last visible video in the row
  8632. // if nobody else is left, this picks the local video
  8633. var jid;
  8634. var videoElem = RTC.getVideoElementName();
  8635. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8636. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8637. return VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8638. } else {
  8639. console.info("Last visible video no longer exists");
  8640. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8641. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8642. return VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8643. } else {
  8644. // Try local video
  8645. console.info("Fallback to local video...");
  8646. return APP.xmpp.myResource();
  8647. }
  8648. }
  8649. };
  8650. my.onRemoteStreamAdded = function (stream) {
  8651. if (stream.peerjid) {
  8652. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8653. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8654. remoteVideos[resourceJid].addRemoteStreamElement(
  8655. stream.sid,
  8656. stream.getOriginalStream(),
  8657. stream.ssrc);
  8658. }
  8659. };
  8660. my.getLargeVideoJid = function () {
  8661. return LargeVideo.getResourceJid();
  8662. };
  8663. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8664. resourceJid) {
  8665. if(focusedVideoResourceJid) {
  8666. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8667. if(oldSmallVideo)
  8668. oldSmallVideo.focus(false);
  8669. }
  8670. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8671. // Unlock current focused.
  8672. if (focusedVideoResourceJid === resourceJid)
  8673. {
  8674. focusedVideoResourceJid = null;
  8675. // Enable the currently set dominant speaker.
  8676. if (currentDominantSpeaker) {
  8677. if(smallVideo && smallVideo.hasVideo())
  8678. {
  8679. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8680. }
  8681. }
  8682. if (!noPinnedEndpointChangedEvent) {
  8683. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8684. }
  8685. return;
  8686. }
  8687. // Lock new video
  8688. focusedVideoResourceJid = resourceJid;
  8689. // Update focused/pinned interface.
  8690. if (resourceJid)
  8691. {
  8692. if(smallVideo)
  8693. smallVideo.focus(true);
  8694. if (!noPinnedEndpointChangedEvent) {
  8695. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8696. }
  8697. }
  8698. // Triggers a "video.selected" event. The "false" parameter indicates
  8699. // this isn't a prezi.
  8700. $(document).trigger("video.selected", [false]);
  8701. LargeVideo.updateLargeVideo(resourceJid);
  8702. // Writing volume not allowed in IE
  8703. if (!RTCBrowserType.isIExplorer()) {
  8704. $('audio').each(function (idx, el) {
  8705. el.volume = 0;
  8706. el.volume = 1;
  8707. });
  8708. }
  8709. };
  8710. /**
  8711. * Checks if container for participant identified by given peerJid exists
  8712. * in the document and creates it eventually.
  8713. *
  8714. * @param peerJid peer Jid to check.
  8715. *
  8716. * @return Returns <tt>true</tt> if the peer container exists,
  8717. * <tt>false</tt> - otherwise
  8718. */
  8719. my.ensurePeerContainerExists = function(peerJid) {
  8720. ContactList.ensureAddContact(peerJid);
  8721. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8722. if(!remoteVideos[resourceJid])
  8723. {
  8724. remoteVideos[resourceJid] = new RemoteVideo(peerJid, VideoLayout);
  8725. // In case this is not currently in the last n we don't show it.
  8726. if (localLastNCount
  8727. && localLastNCount > 0
  8728. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  8729. remoteVideos[resourceJid].showPeerContainer('hide');
  8730. }
  8731. else
  8732. VideoLayout.resizeThumbnails();
  8733. }
  8734. };
  8735. my.inputDisplayNameHandler = function (name) {
  8736. localVideoThumbnail.inputDisplayNameHandler(name);
  8737. };
  8738. my.videoactive = function (videoelem, resourceJid) {
  8739. console.info(resourceJid + " video is now active");
  8740. videoelem.show();
  8741. VideoLayout.resizeThumbnails();
  8742. // Update the large video to the last added video only if there's no
  8743. // current dominant, focused speaker or prezi playing or update it to
  8744. // the current dominant speaker.
  8745. if ((!focusedVideoResourceJid &&
  8746. !currentDominantSpeaker &&
  8747. !require("../prezi/Prezi").isPresentationVisible()) ||
  8748. focusedVideoResourceJid === resourceJid ||
  8749. (resourceJid &&
  8750. currentDominantSpeaker === resourceJid)) {
  8751. LargeVideo.updateLargeVideo(resourceJid, true);
  8752. }
  8753. }
  8754. /**
  8755. * Shows the presence status message for the given video.
  8756. */
  8757. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8758. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8759. };
  8760. /**
  8761. * Shows a visual indicator for the moderator of the conference.
  8762. */
  8763. my.showModeratorIndicator = function () {
  8764. var isModerator = APP.xmpp.isModerator();
  8765. if (isModerator) {
  8766. localVideoThumbnail.createModeratorIndicatorElement();
  8767. }
  8768. var members = APP.xmpp.getMembers();
  8769. Object.keys(members).forEach(function (jid) {
  8770. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8771. // Skip server side focus
  8772. return;
  8773. }
  8774. var resourceJid = Strophe.getResourceFromJid(jid);
  8775. var member = members[jid];
  8776. if (member.role === 'moderator') {
  8777. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8778. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8779. } else if (isModerator) {
  8780. // We are moderator, but user is not - add menu
  8781. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8782. remoteVideos[resourceJid].addRemoteVideoMenu();
  8783. }
  8784. }
  8785. });
  8786. };
  8787. /*
  8788. * Shows or hides the audio muted indicator over the local thumbnail video.
  8789. * @param {boolean} isMuted
  8790. */
  8791. my.showLocalAudioIndicator = function(isMuted) {
  8792. localVideoThumbnail.showAudioIndicator(isMuted);
  8793. };
  8794. /**
  8795. * Resizes the large video container.
  8796. */
  8797. my.resizeLargeVideoContainer = function () {
  8798. LargeVideo.resize();
  8799. VideoLayout.resizeThumbnails();
  8800. LargeVideo.position();
  8801. };
  8802. /**
  8803. * Resizes thumbnails.
  8804. */
  8805. my.resizeThumbnails = function(animate) {
  8806. var videoSpaceWidth = $('#remoteVideos').width();
  8807. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8808. var width = thumbnailSize[0];
  8809. var height = thumbnailSize[1];
  8810. $('.userAvatar').css('left', (width - height) / 2);
  8811. if(animate)
  8812. {
  8813. $('#remoteVideos').animate({
  8814. height: height
  8815. },
  8816. {
  8817. queue: false,
  8818. duration: 500
  8819. });
  8820. $('#remoteVideos>span').animate({
  8821. height: height,
  8822. width: width
  8823. },
  8824. {
  8825. queue: false,
  8826. duration: 500,
  8827. complete: function () {
  8828. $(document).trigger(
  8829. "remotevideo.resized",
  8830. [width,
  8831. height]);
  8832. }
  8833. });
  8834. }
  8835. else
  8836. {
  8837. // size videos so that while keeping AR and max height, we have a
  8838. // nice fit
  8839. $('#remoteVideos').height(height);
  8840. $('#remoteVideos>span').width(width);
  8841. $('#remoteVideos>span').height(height);
  8842. $(document).trigger("remotevideo.resized", [width, height]);
  8843. }
  8844. };
  8845. /**
  8846. * Calculates the thumbnail size.
  8847. *
  8848. * @param videoSpaceWidth the width of the video space
  8849. */
  8850. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8851. // Calculate the available height, which is the inner window height minus
  8852. // 39px for the header minus 2px for the delimiter lines on the top and
  8853. // bottom of the large video, minus the 36px space inside the remoteVideos
  8854. // container used for highlighting shadow.
  8855. var availableHeight = 100;
  8856. var numvids = $('#remoteVideos>span:visible').length;
  8857. if (localLastNCount && localLastNCount > 0) {
  8858. numvids = Math.min(localLastNCount + 1, numvids);
  8859. }
  8860. // Remove the 3px borders arround videos and border around the remote
  8861. // videos area and the 4 pixels between the local video and the others
  8862. //TODO: Find out where the 4 pixels come from and remove them
  8863. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8864. var availableWidth = availableWinWidth / numvids;
  8865. var aspectRatio = 16.0 / 9.0;
  8866. var maxHeight = Math.min(160, availableHeight);
  8867. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  8868. if (availableHeight < availableWidth / aspectRatio) {
  8869. availableWidth = Math.floor(availableHeight * aspectRatio);
  8870. }
  8871. return [availableWidth, availableHeight];
  8872. };
  8873. /**
  8874. * Returns the corresponding resource jid to the given peer container
  8875. * DOM element.
  8876. *
  8877. * @return the corresponding resource jid to the given peer container
  8878. * DOM element
  8879. */
  8880. my.getPeerContainerResourceJid = function (containerElement) {
  8881. var i = containerElement.id.indexOf('participant_');
  8882. if (i >= 0)
  8883. return containerElement.id.substring(i + 12);
  8884. };
  8885. my.getPeerVideoSel = function (peerResourceJid) {
  8886. return $('#participant_' + peerResourceJid +
  8887. '>' + APP.RTC.getVideoElementName());
  8888. };
  8889. /**
  8890. * On contact list item clicked.
  8891. */
  8892. $(ContactList).bind('contactclicked', function(event, jid) {
  8893. if (!jid) {
  8894. return;
  8895. }
  8896. if (jid === APP.xmpp.myJid()) {
  8897. $("#localVideoContainer").click();
  8898. return;
  8899. }
  8900. var resource = Strophe.getResourceFromJid(jid);
  8901. var videoSel = VideoLayout.getPeerVideoSel(resource);
  8902. if (videoSel.length > 0) {
  8903. var videoThumb = videoSel[0];
  8904. // It is not always the case that a videoThumb exists (if there is
  8905. // no actual video).
  8906. if (RTC.getVideoSrc(videoThumb)) {
  8907. // We have a video src, great! Let's update the large video
  8908. // now.
  8909. VideoLayout.handleVideoThumbClicked(
  8910. false,
  8911. Strophe.getResourceFromJid(jid));
  8912. } else {
  8913. // If we don't have a video src for jid, there's absolutely
  8914. // no point in calling handleVideoThumbClicked; Quite
  8915. // simply, it won't work because it needs an src to attach
  8916. // to the large video.
  8917. //
  8918. // Instead, we trigger the pinned endpoint changed event to
  8919. // let the bridge adjust its lastN set for myjid and store
  8920. // the pinned user in the lastNPickupJid variable to be
  8921. // picked up later by the lastN changed event handler.
  8922. lastNPickupJid = jid;
  8923. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  8924. Strophe.getResourceFromJid(jid));
  8925. }
  8926. }
  8927. });
  8928. /**
  8929. * On audio muted event.
  8930. */
  8931. my.onAudioMute = function (jid, isMuted) {
  8932. var resourceJid = Strophe.getResourceFromJid(jid);
  8933. if (resourceJid === APP.xmpp.myResource()) {
  8934. localVideoThumbnail.showAudioIndicator(isMuted);
  8935. } else {
  8936. VideoLayout.ensurePeerContainerExists(jid);
  8937. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  8938. if (APP.xmpp.isModerator()) {
  8939. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  8940. }
  8941. }
  8942. };
  8943. /**
  8944. * On video muted event.
  8945. */
  8946. my.onVideoMute = function (jid, value) {
  8947. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, value))
  8948. return;
  8949. if (jid === APP.xmpp.myJid()) {
  8950. localVideoThumbnail.showVideoIndicator(value);
  8951. } else {
  8952. var resource = Strophe.getResourceFromJid(jid);
  8953. VideoLayout.ensurePeerContainerExists(jid);
  8954. remoteVideos[resource].showVideoIndicator(value);
  8955. var el = VideoLayout.getPeerVideoSel(resource);
  8956. if (!value)
  8957. el.show();
  8958. else
  8959. el.hide();
  8960. }
  8961. };
  8962. /**
  8963. * Display name changed.
  8964. */
  8965. my.onDisplayNameChanged =
  8966. function (jid, displayName, status) {
  8967. if (jid === 'localVideoContainer'
  8968. || jid === APP.xmpp.myJid()) {
  8969. localVideoThumbnail.setDisplayName(displayName);
  8970. } else {
  8971. VideoLayout.ensurePeerContainerExists(jid);
  8972. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  8973. displayName,
  8974. status);
  8975. }
  8976. };
  8977. /**
  8978. * On dominant speaker changed event.
  8979. */
  8980. my.onDominantSpeakerChanged = function (resourceJid) {
  8981. // We ignore local user events.
  8982. if (resourceJid === APP.xmpp.myResource())
  8983. return;
  8984. var members = APP.xmpp.getMembers();
  8985. // Update the current dominant speaker.
  8986. if (resourceJid !== currentDominantSpeaker) {
  8987. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  8988. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  8989. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  8990. !members[currentJID].displayName)) {
  8991. remoteVideos[resourceJid].setDisplayName(null);
  8992. }
  8993. if(resourceJid && (!members || !members[newJID] ||
  8994. !members[newJID].displayName)) {
  8995. remoteVideos[resourceJid].setDisplayName(null,
  8996. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  8997. }
  8998. currentDominantSpeaker = resourceJid;
  8999. } else {
  9000. return;
  9001. }
  9002. // Obtain container for new dominant speaker.
  9003. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9004. // Local video will not have container found, but that's ok
  9005. // since we don't want to switch to local video.
  9006. if (!focusedVideoResourceJid && videoSel.length)
  9007. {
  9008. // Update the large video if the video source is already available,
  9009. // otherwise wait for the "videoactive.jingle" event.
  9010. if (videoSel[0].currentTime > 0) {
  9011. LargeVideo.updateLargeVideo(resourceJid);
  9012. }
  9013. }
  9014. };
  9015. /**
  9016. * On last N change event.
  9017. *
  9018. * @param lastNEndpoints the list of last N endpoints
  9019. * @param endpointsEnteringLastN the list currently entering last N
  9020. * endpoints
  9021. */
  9022. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  9023. endpointsEnteringLastN,
  9024. stream) {
  9025. if (lastNCount !== lastNEndpoints.length)
  9026. lastNCount = lastNEndpoints.length;
  9027. lastNEndpointsCache = lastNEndpoints;
  9028. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9029. //
  9030. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9031. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9032. // so E sees them. C is only in E's local LastN set.
  9033. //
  9034. // If F starts talking and LastN = 3, then E should see thumbnails for
  9035. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9036. // enters E's local LastN ejecting C.
  9037. // Increase the local LastN set size, if necessary.
  9038. if (lastNCount > localLastNCount) {
  9039. localLastNCount = lastNCount;
  9040. }
  9041. // Update the local LastN set preserving the order in which the
  9042. // endpoints appeared in the LastN/local LastN set.
  9043. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9044. for (var i = 0; i < localLastNSet.length; i++) {
  9045. if (nextLocalLastNSet.length >= localLastNCount) {
  9046. break;
  9047. }
  9048. var resourceJid = localLastNSet[i];
  9049. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9050. nextLocalLastNSet.push(resourceJid);
  9051. }
  9052. }
  9053. localLastNSet = nextLocalLastNSet;
  9054. var updateLargeVideo = false;
  9055. // Handle LastN/local LastN changes.
  9056. $('#remoteVideos>span').each(function( index, element ) {
  9057. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9058. var isReceived = true;
  9059. if (resourceJid
  9060. && lastNEndpoints.indexOf(resourceJid) < 0
  9061. && localLastNSet.indexOf(resourceJid) < 0) {
  9062. console.log("Remove from last N", resourceJid);
  9063. remoteVideos[resourceJid].showPeerContainer('hide');
  9064. isReceived = false;
  9065. } else if (resourceJid
  9066. && $('#participant_' + resourceJid).is(':visible')
  9067. && lastNEndpoints.indexOf(resourceJid) < 0
  9068. && localLastNSet.indexOf(resourceJid) >= 0) {
  9069. remoteVideos[resourceJid].showPeerContainer('avatar');
  9070. isReceived = false;
  9071. }
  9072. if (!isReceived) {
  9073. // resourceJid has dropped out of the server side lastN set, so
  9074. // it is no longer being received. If resourceJid was being
  9075. // displayed in the large video we have to switch to another
  9076. // user.
  9077. if (!updateLargeVideo && resourceJid === LargeVideo.getResourceJid()) {
  9078. updateLargeVideo = true;
  9079. }
  9080. }
  9081. });
  9082. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9083. endpointsEnteringLastN = lastNEndpoints;
  9084. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9085. endpointsEnteringLastN.forEach(function (resourceJid) {
  9086. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9087. remoteVideos[resourceJid].showPeerContainer('show');
  9088. if (!isVisible) {
  9089. console.log("Add to last N", resourceJid);
  9090. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9091. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9092. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9093. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9094. if (lastNPickupJid == mediaStream.peerjid) {
  9095. // Clean up the lastN pickup jid.
  9096. lastNPickupJid = null;
  9097. // Don't fire the events again, they've already
  9098. // been fired in the contact list click handler.
  9099. VideoLayout.handleVideoThumbClicked(
  9100. false,
  9101. Strophe.getResourceFromJid(mediaStream.peerjid));
  9102. updateLargeVideo = false;
  9103. }
  9104. remoteVideos[resourceJid].waitForPlayback(mediaStream.stream);
  9105. }
  9106. });
  9107. }
  9108. // The endpoint that was being shown in the large video has dropped out
  9109. // of the lastN set and there was no lastN pickup jid. We need to update
  9110. // the large video now.
  9111. if (updateLargeVideo) {
  9112. var resource, container, src;
  9113. var myResource
  9114. = APP.xmpp.myResource();
  9115. // Find out which endpoint to show in the large video.
  9116. for (var i = 0; i < lastNEndpoints.length; i++) {
  9117. resource = lastNEndpoints[i];
  9118. if (!resource || resource === myResource)
  9119. continue;
  9120. // videoSrcToSsrc needs to be update for this call to succeed.
  9121. LargeVideo.updateLargeVideo(resource);
  9122. break;
  9123. }
  9124. }
  9125. };
  9126. /**
  9127. * Updates local stats
  9128. * @param percent
  9129. * @param object
  9130. */
  9131. my.updateLocalConnectionStats = function (percent, object) {
  9132. var resolution = null;
  9133. if(object.resolution !== null)
  9134. {
  9135. resolution = object.resolution;
  9136. object.resolution = resolution[APP.xmpp.myJid()];
  9137. delete resolution[APP.xmpp.myJid()];
  9138. }
  9139. localVideoThumbnail.updateStatsIndicator(percent, object);
  9140. for(var jid in resolution)
  9141. {
  9142. if(resolution[jid] === null)
  9143. continue;
  9144. var resourceJid = Strophe.getResourceFromJid(jid);
  9145. if(remoteVideos[resourceJid] && remoteVideos[resourceJid].connectionIndicator)
  9146. {
  9147. remoteVideos[resourceJid].connectionIndicator.updateResolution(resolution[jid]);
  9148. }
  9149. }
  9150. };
  9151. /**
  9152. * Updates remote stats.
  9153. * @param jid the jid associated with the stats
  9154. * @param percent the connection quality percent
  9155. * @param object the stats data
  9156. */
  9157. my.updateConnectionStats = function (jid, percent, object) {
  9158. var resourceJid = Strophe.getResourceFromJid(jid);
  9159. if(remoteVideos[resourceJid])
  9160. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9161. };
  9162. /**
  9163. * Removes the connection
  9164. * @param jid
  9165. */
  9166. my.removeConnectionIndicator = function (jid) {
  9167. remoteVideos[Strophe.getResourceFromJid(jid)].removeConnectionIndicator();
  9168. };
  9169. /**
  9170. * Hides the connection indicator
  9171. * @param jid
  9172. */
  9173. my.hideConnectionIndicator = function (jid) {
  9174. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9175. };
  9176. /**
  9177. * Hides all the indicators
  9178. */
  9179. my.onStatsStop = function () {
  9180. for(var video in remoteVideos)
  9181. {
  9182. remoteVideos[video].hideIndicator();
  9183. }
  9184. localVideoThumbnail.hideIndicator();
  9185. };
  9186. my.participantLeft = function (jid) {
  9187. // Unlock large video
  9188. var resourceJid = Strophe.getResourceFromJid(jid);
  9189. if (focusedVideoResourceJid === resourceJid)
  9190. {
  9191. console.info("Focused video owner has left the conference");
  9192. focusedVideoResourceJid = null;
  9193. }
  9194. };
  9195. my.onVideoTypeChanged = function (jid) {
  9196. LargeVideo.onVideoTypeChanged(jid);
  9197. };
  9198. my.showMore = function (jid) {
  9199. if (jid === 'local')
  9200. {
  9201. localVideoThumbnail.connectionIndicator.showMore();
  9202. }
  9203. else
  9204. {
  9205. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9206. if (remoteVideo) {
  9207. remoteVideo.connectionIndicator.showMore();
  9208. } else {
  9209. console.info("Error - no remote video for jid: " + jid);
  9210. }
  9211. }
  9212. };
  9213. my.addPreziContainer = function (id) {
  9214. return RemoteVideo.createContainer(id);
  9215. };
  9216. my.setLargeVideoVisible = function (isVisible) {
  9217. LargeVideo.setLargeVideoVisible(isVisible);
  9218. if(!isVisible && focusedVideoResourceJid)
  9219. {
  9220. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9221. if(smallVideo)
  9222. smallVideo.focus(false);
  9223. smallVideo.showAvatar();
  9224. focusedVideoResourceJid = null;
  9225. }
  9226. };
  9227. /**
  9228. * Resizes the video area
  9229. * @param completeFunction a function to be called when the video space is resized
  9230. */
  9231. my.resizeVideoArea = function(isVisible, completeFunction) {
  9232. LargeVideo.resizeVideoAreaAnimated(isVisible, completeFunction);
  9233. VideoLayout.resizeThumbnails(true);
  9234. };
  9235. my.getSmallVideo = function (resourceJid) {
  9236. if(resourceJid == APP.xmpp.myResource())
  9237. {
  9238. return localVideoThumbnail;
  9239. }
  9240. else
  9241. {
  9242. if(!remoteVideos[resourceJid])
  9243. return null;
  9244. return remoteVideos[resourceJid];
  9245. }
  9246. };
  9247. my.userAvatarChanged = function(resourceJid, thumbUrl)
  9248. {
  9249. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9250. if(smallVideo)
  9251. smallVideo.avatarChanged(thumbUrl);
  9252. else
  9253. console.warn(
  9254. "Missed avatar update - no small video yet for " + resourceJid);
  9255. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9256. };
  9257. return my;
  9258. }(VideoLayout || {}));
  9259. module.exports = VideoLayout;
  9260. },{"../../../service/RTC/MediaStreamTypes":98,"../../../service/UI/UIEvents":102,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  9261. //var nouns = [
  9262. //];
  9263. var pluralNouns = [
  9264. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9265. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9266. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9267. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9268. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9269. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9270. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9271. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9272. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9273. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9274. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9275. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9276. ];
  9277. //var places = [
  9278. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9279. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9280. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9281. // "Bridge"
  9282. //];
  9283. var verbs = [
  9284. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9285. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9286. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9287. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9288. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9289. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9290. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9291. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9292. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9293. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9294. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9295. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9296. ];
  9297. var adverbs = [
  9298. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9299. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9300. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9301. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9302. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9303. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9304. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9305. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9306. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9307. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9308. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9309. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9310. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9311. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9312. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9313. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9314. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9315. ];
  9316. var adjectives = [
  9317. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9318. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9319. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9320. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9321. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9322. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9323. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9324. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9325. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9326. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9327. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9328. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9329. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9330. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9331. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9332. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9333. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9334. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9335. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9336. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9337. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9338. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9339. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9340. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9341. "Zealous"
  9342. ];
  9343. //var pronouns = [
  9344. //];
  9345. //var conjunctions = [
  9346. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9347. //];
  9348. /*
  9349. * Maps a string (category name) to the array of words from that category.
  9350. */
  9351. var CATEGORIES =
  9352. {
  9353. //"_NOUN_": nouns,
  9354. "_PLURALNOUN_": pluralNouns,
  9355. //"_PLACE_": places,
  9356. "_VERB_": verbs,
  9357. "_ADVERB_": adverbs,
  9358. "_ADJECTIVE_": adjectives
  9359. //"_PRONOUN_": pronouns,
  9360. //"_CONJUNCTION_": conjunctions,
  9361. };
  9362. var PATTERNS = [
  9363. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9364. // BeautifulFungiOrSpaghetti
  9365. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9366. // AmazinglyScaryToy
  9367. //"_ADVERB__ADJECTIVE__NOUN_",
  9368. // NeitherTrashNorRifle
  9369. //"Neither_NOUN_Nor_NOUN_",
  9370. //"Either_NOUN_Or_NOUN_",
  9371. // EitherCopulateOrInvestigate
  9372. //"Either_VERB_Or_VERB_",
  9373. //"Neither_VERB_Nor_VERB_",
  9374. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9375. //"The_ADVERB__ADJECTIVE__NOUN_",
  9376. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9377. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9378. // WolvesComputeBadly
  9379. //"_PLURALNOUN__VERB__ADVERB_",
  9380. // UniteFacilitateAndMerge
  9381. //"_VERB__VERB_And_VERB_",
  9382. //NastyWitchesAtThePub
  9383. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9384. ];
  9385. /*
  9386. * Returns a random element from the array 'arr'
  9387. */
  9388. function randomElement(arr)
  9389. {
  9390. return arr[Math.floor(Math.random() * arr.length)];
  9391. }
  9392. /*
  9393. * Returns true if the string 's' contains one of the
  9394. * template strings.
  9395. */
  9396. function hasTemplate(s)
  9397. {
  9398. for (var template in CATEGORIES){
  9399. if (s.indexOf(template) >= 0){
  9400. return true;
  9401. }
  9402. }
  9403. }
  9404. /**
  9405. * Generates new room name.
  9406. */
  9407. var RoomNameGenerator = {
  9408. generateRoomWithoutSeparator: function()
  9409. {
  9410. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  9411. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  9412. var name = randomElement(PATTERNS);
  9413. var word;
  9414. while (hasTemplate(name)){
  9415. for (var template in CATEGORIES){
  9416. word = randomElement(CATEGORIES[template]);
  9417. name = name.replace(template, word);
  9418. }
  9419. }
  9420. return name;
  9421. }
  9422. }
  9423. module.exports = RoomNameGenerator;
  9424. },{}],41:[function(require,module,exports){
  9425. var animateTimeout, updateTimeout;
  9426. var RoomNameGenerator = require("./RoomnameGenerator");
  9427. function enter_room()
  9428. {
  9429. var val = $("#enter_room_field").val();
  9430. if(!val) {
  9431. val = $("#enter_room_field").attr("room_name");
  9432. }
  9433. if (val) {
  9434. window.location.pathname = "/" + val;
  9435. }
  9436. }
  9437. function animate(word) {
  9438. var currentVal = $("#enter_room_field").attr("placeholder");
  9439. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9440. animateTimeout = setTimeout(function() {
  9441. animate(word.substring(1, word.length))
  9442. }, 70);
  9443. }
  9444. function update_roomname()
  9445. {
  9446. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9447. $("#enter_room_field").attr("room_name", word);
  9448. $("#enter_room_field").attr("placeholder", "");
  9449. clearTimeout(animateTimeout);
  9450. animate(word);
  9451. updateTimeout = setTimeout(update_roomname, 10000);
  9452. }
  9453. function setupWelcomePage()
  9454. {
  9455. $("#videoconference_page").hide();
  9456. $("#domain_name").text(
  9457. window.location.protocol + "//" + window.location.host + "/");
  9458. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9459. var leftWatermarkDiv
  9460. = $("#welcome_page_header div[class='watermark leftwatermark']");
  9461. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  9462. {
  9463. leftWatermarkDiv.css({display: 'block'});
  9464. leftWatermarkDiv.parent().get(0).href
  9465. = interfaceConfig.JITSI_WATERMARK_LINK;
  9466. }
  9467. }
  9468. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9469. var rightWatermarkDiv
  9470. = $("#welcome_page_header div[class='watermark rightwatermark']");
  9471. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9472. rightWatermarkDiv.css({display: 'block'});
  9473. rightWatermarkDiv.parent().get(0).href
  9474. = interfaceConfig.BRAND_WATERMARK_LINK;
  9475. rightWatermarkDiv.get(0).style.backgroundImage
  9476. = "url(images/rightwatermark.png)";
  9477. }
  9478. }
  9479. if (interfaceConfig.SHOW_POWERED_BY) {
  9480. $("#welcome_page_header>a[class='poweredby']")
  9481. .css({display: 'block'});
  9482. }
  9483. $("#enter_room_button").click(function()
  9484. {
  9485. enter_room();
  9486. });
  9487. $("#enter_room_field").keydown(function (event) {
  9488. if (event.keyCode === 13 /* enter */) {
  9489. enter_room();
  9490. }
  9491. });
  9492. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  9493. var updateTimeout;
  9494. var animateTimeout;
  9495. $("#reload_roomname").click(function () {
  9496. clearTimeout(updateTimeout);
  9497. clearTimeout(animateTimeout);
  9498. update_roomname();
  9499. });
  9500. $("#reload_roomname").show();
  9501. update_roomname();
  9502. }
  9503. $("#disable_welcome").click(function () {
  9504. window.localStorage.welcomePageDisabled
  9505. = $("#disable_welcome").is(":checked");
  9506. });
  9507. }
  9508. module.exports = setupWelcomePage;
  9509. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9510. var params = {};
  9511. function getConfigParamsFromUrl() {
  9512. if(!location.hash)
  9513. return {};
  9514. var hash = location.hash.substr(1);
  9515. var result = {};
  9516. hash.split("&").forEach(function(part) {
  9517. var item = part.split("=");
  9518. result[item[0]] = JSON.parse(
  9519. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9520. });
  9521. return result;
  9522. }
  9523. params = getConfigParamsFromUrl();
  9524. var URLProcessor = {
  9525. setConfigParametersFromUrl: function () {
  9526. for(var k in params)
  9527. {
  9528. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9529. continue;
  9530. var v = params[k];
  9531. var confKey = k.substr(7);
  9532. if(config[confKey] && typeof config[confKey] !== typeof v)
  9533. {
  9534. console.warn("The type of " + k +
  9535. " is wrong. That parameter won't be updated in config.js.");
  9536. continue;
  9537. }
  9538. config[confKey] = v;
  9539. }
  9540. }
  9541. };
  9542. module.exports = URLProcessor;
  9543. },{}],43:[function(require,module,exports){
  9544. var EventEmitter = require("events");
  9545. var eventEmitter = new EventEmitter();
  9546. var CQEvents = require("../../service/connectionquality/CQEvents");
  9547. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9548. /**
  9549. * local stats
  9550. * @type {{}}
  9551. */
  9552. var stats = {};
  9553. /**
  9554. * remote stats
  9555. * @type {{}}
  9556. */
  9557. var remoteStats = {};
  9558. /**
  9559. * Interval for sending statistics to other participants
  9560. * @type {null}
  9561. */
  9562. var sendIntervalId = null;
  9563. /**
  9564. * Start statistics sending.
  9565. */
  9566. function startSendingStats() {
  9567. sendStats();
  9568. sendIntervalId = setInterval(sendStats, 10000);
  9569. }
  9570. /**
  9571. * Sends statistics to other participants
  9572. */
  9573. function sendStats() {
  9574. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9575. }
  9576. /**
  9577. * Converts statistics to format for sending through XMPP
  9578. * @param stats the statistics
  9579. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9580. */
  9581. function convertToMUCStats(stats) {
  9582. return {
  9583. "bitrate_download": stats.bitrate.download,
  9584. "bitrate_upload": stats.bitrate.upload,
  9585. "packetLoss_total": stats.packetLoss.total,
  9586. "packetLoss_download": stats.packetLoss.download,
  9587. "packetLoss_upload": stats.packetLoss.upload
  9588. };
  9589. }
  9590. /**
  9591. * Converts statitistics to format used by VideoLayout
  9592. * @param stats
  9593. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9594. */
  9595. function parseMUCStats(stats) {
  9596. return {
  9597. bitrate: {
  9598. download: stats.bitrate_download,
  9599. upload: stats.bitrate_upload
  9600. },
  9601. packetLoss: {
  9602. total: stats.packetLoss_total,
  9603. download: stats.packetLoss_download,
  9604. upload: stats.packetLoss_upload
  9605. }
  9606. };
  9607. }
  9608. var ConnectionQuality = {
  9609. init: function () {
  9610. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9611. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9612. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9613. },
  9614. /**
  9615. * Updates the local statistics
  9616. * @param data new statistics
  9617. */
  9618. updateLocalStats: function (data) {
  9619. stats = data;
  9620. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9621. if (sendIntervalId == null) {
  9622. startSendingStats();
  9623. }
  9624. },
  9625. /**
  9626. * Updates remote statistics
  9627. * @param jid the jid associated with the statistics
  9628. * @param data the statistics
  9629. */
  9630. updateRemoteStats: function (jid, data) {
  9631. if (data == null || data.packetLoss_total == null) {
  9632. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9633. return;
  9634. }
  9635. remoteStats[jid] = parseMUCStats(data);
  9636. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9637. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9638. },
  9639. /**
  9640. * Stops statistics sending.
  9641. */
  9642. stopSendingStats: function () {
  9643. clearInterval(sendIntervalId);
  9644. sendIntervalId = null;
  9645. //notify UI about stopping statistics gathering
  9646. eventEmitter.emit(CQEvents.STOP);
  9647. },
  9648. /**
  9649. * Returns the local statistics.
  9650. */
  9651. getStats: function () {
  9652. return stats;
  9653. },
  9654. addListener: function (type, listener) {
  9655. eventEmitter.on(type, listener);
  9656. }
  9657. };
  9658. module.exports = ConnectionQuality;
  9659. },{"../../service/connectionquality/CQEvents":104,"../../service/xmpp/XMPPEvents":108,"events":109}],44:[function(require,module,exports){
  9660. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9661. getUserMediaWithConstraints */
  9662. /**
  9663. * Indicates that desktop stream is currently in use(for toggle purpose).
  9664. * @type {boolean}
  9665. */
  9666. var isUsingScreenStream = false;
  9667. /**
  9668. * Indicates that switch stream operation is in progress and prevent from
  9669. * triggering new events.
  9670. * @type {boolean}
  9671. */
  9672. var switchInProgress = false;
  9673. /**
  9674. * Method used to get screen sharing stream.
  9675. *
  9676. * @type {function (stream_callback, failure_callback}
  9677. */
  9678. var obtainDesktopStream = null;
  9679. /**
  9680. * Indicates whether desktop sharing extension is installed.
  9681. * @type {boolean}
  9682. */
  9683. var extInstalled = false;
  9684. /**
  9685. * Indicates whether update of desktop sharing extension is required.
  9686. * @type {boolean}
  9687. */
  9688. var extUpdateRequired = false;
  9689. var AdapterJS = require("../RTC/adapter.screenshare");
  9690. var EventEmitter = require("events");
  9691. var eventEmitter = new EventEmitter();
  9692. var DesktopSharingEventTypes
  9693. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9694. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9695. var RTCEvents = require("../../service/RTC/RTCEvents");
  9696. /**
  9697. * Method obtains desktop stream from WebRTC 'screen' source.
  9698. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9699. */
  9700. function obtainWebRTCScreen(streamCallback, failCallback) {
  9701. APP.RTC.getUserMediaWithConstraints(
  9702. ['screen'],
  9703. streamCallback,
  9704. failCallback
  9705. );
  9706. }
  9707. /**
  9708. * Constructs inline install URL for Chrome desktop streaming extension.
  9709. * The 'chromeExtensionId' must be defined in config.js.
  9710. * @returns {string}
  9711. */
  9712. function getWebStoreInstallUrl()
  9713. {
  9714. return "https://chrome.google.com/webstore/detail/" +
  9715. config.chromeExtensionId;
  9716. }
  9717. /**
  9718. * Checks whether extension update is required.
  9719. * @param minVersion minimal required version
  9720. * @param extVersion current extension version
  9721. * @returns {boolean}
  9722. */
  9723. function isUpdateRequired(minVersion, extVersion)
  9724. {
  9725. try
  9726. {
  9727. var s1 = minVersion.split('.');
  9728. var s2 = extVersion.split('.');
  9729. var len = Math.max(s1.length, s2.length);
  9730. for (var i = 0; i < len; i++)
  9731. {
  9732. var n1 = 0,
  9733. n2 = 0;
  9734. if (i < s1.length)
  9735. n1 = parseInt(s1[i]);
  9736. if (i < s2.length)
  9737. n2 = parseInt(s2[i]);
  9738. if (isNaN(n1) || isNaN(n2))
  9739. {
  9740. return true;
  9741. }
  9742. else if (n1 !== n2)
  9743. {
  9744. return n1 > n2;
  9745. }
  9746. }
  9747. // will happen if boths version has identical numbers in
  9748. // their components (even if one of them is longer, has more components)
  9749. return false;
  9750. }
  9751. catch (e)
  9752. {
  9753. console.error("Failed to parse extension version", e);
  9754. APP.UI.messageHandler.showError("dialog.error",
  9755. "dialog.detectext");
  9756. return true;
  9757. }
  9758. }
  9759. function checkChromeExtInstalled(callback) {
  9760. if (!chrome.runtime) {
  9761. // No API, so no extension for sure
  9762. callback(false, false);
  9763. return;
  9764. }
  9765. chrome.runtime.sendMessage(
  9766. config.chromeExtensionId,
  9767. { getVersion: true },
  9768. function (response) {
  9769. if (!response || !response.version) {
  9770. // Communication failure - assume that no endpoint exists
  9771. console.warn(
  9772. "Extension not installed?: ", chrome.runtime.lastError);
  9773. callback(false, false);
  9774. return;
  9775. }
  9776. // Check installed extension version
  9777. var extVersion = response.version;
  9778. console.log('Extension version is: ' + extVersion);
  9779. var updateRequired
  9780. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  9781. callback(!updateRequired, updateRequired);
  9782. }
  9783. );
  9784. }
  9785. function doGetStreamFromExtension(streamCallback, failCallback) {
  9786. // Sends 'getStream' msg to the extension.
  9787. // Extension id must be defined in the config.
  9788. chrome.runtime.sendMessage(
  9789. config.chromeExtensionId,
  9790. { getStream: true, sources: config.desktopSharingSources },
  9791. function (response) {
  9792. if (!response) {
  9793. failCallback(chrome.runtime.lastError);
  9794. return;
  9795. }
  9796. console.log("Response from extension: " + response);
  9797. if (response.streamId) {
  9798. APP.RTC.getUserMediaWithConstraints(
  9799. ['desktop'],
  9800. function (stream) {
  9801. streamCallback(stream);
  9802. },
  9803. failCallback,
  9804. null, null, null,
  9805. response.streamId);
  9806. } else {
  9807. failCallback("Extension failed to get the stream");
  9808. }
  9809. }
  9810. );
  9811. }
  9812. /**
  9813. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  9814. * stream for returned stream token.
  9815. */
  9816. function obtainScreenFromExtension(streamCallback, failCallback) {
  9817. if (extInstalled) {
  9818. doGetStreamFromExtension(streamCallback, failCallback);
  9819. } else {
  9820. if (extUpdateRequired) {
  9821. alert(
  9822. 'Jitsi Desktop Streamer requires update. ' +
  9823. 'Changes will take effect after next Chrome restart.');
  9824. }
  9825. chrome.webstore.install(
  9826. getWebStoreInstallUrl(),
  9827. function (arg) {
  9828. console.log("Extension installed successfully", arg);
  9829. extInstalled = true;
  9830. // We need to give a moment for the endpoint to become available
  9831. window.setTimeout(function () {
  9832. doGetStreamFromExtension(streamCallback, failCallback);
  9833. }, 500);
  9834. },
  9835. function (arg) {
  9836. console.log("Failed to install the extension", arg);
  9837. failCallback(arg);
  9838. APP.UI.messageHandler.showError("dialog.error",
  9839. "dialog.failtoinstall");
  9840. }
  9841. );
  9842. }
  9843. }
  9844. /**
  9845. * Call this method to toggle desktop sharing feature.
  9846. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  9847. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  9848. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  9849. * enabled), pass any other string or nothing in order to disable this
  9850. * feature completely.
  9851. */
  9852. function setDesktopSharing(method) {
  9853. obtainDesktopStream = null;
  9854. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  9855. // care about 'method' parameter
  9856. if (RTCBrowserType.isTemasysPluginUsed()) {
  9857. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  9858. console.info("Screensharing not supported by this plugin version");
  9859. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  9860. console.info(
  9861. "Screensharing not available with Temasys plugin on this site");
  9862. } else {
  9863. obtainDesktopStream = obtainWebRTCScreen;
  9864. console.info("Using Temasys plugin for desktop sharing");
  9865. }
  9866. } else if (RTCBrowserType.isChrome()) {
  9867. if (method == "ext") {
  9868. if (RTCBrowserType.getChromeVersion() >= 34) {
  9869. obtainDesktopStream = obtainScreenFromExtension;
  9870. console.info("Using Chrome extension for desktop sharing");
  9871. initChromeExtension();
  9872. } else {
  9873. console.info("Chrome extension not supported until ver 34");
  9874. }
  9875. } else if (method == "webrtc") {
  9876. obtainDesktopStream = obtainWebRTCScreen;
  9877. console.info("Using Chrome WebRTC for desktop sharing");
  9878. }
  9879. }
  9880. if (!obtainDesktopStream) {
  9881. console.info("Desktop sharing disabled");
  9882. }
  9883. }
  9884. /**
  9885. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  9886. * config.js to support inline installs. Host site must be selected as main
  9887. * website of published extension.
  9888. */
  9889. function initInlineInstalls()
  9890. {
  9891. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  9892. }
  9893. function initChromeExtension() {
  9894. // Initialize Chrome extension inline installs
  9895. initInlineInstalls();
  9896. // Check if extension is installed
  9897. checkChromeExtInstalled(function (installed, updateRequired) {
  9898. extInstalled = installed;
  9899. extUpdateRequired = updateRequired;
  9900. console.info(
  9901. "Chrome extension installed: " + extInstalled +
  9902. " updateRequired: " + extUpdateRequired);
  9903. });
  9904. }
  9905. function getVideoStreamFailed(error) {
  9906. console.error("Failed to obtain the stream to switch to", error);
  9907. switchInProgress = false;
  9908. isUsingScreenStream = false;
  9909. newStreamCreated(null);
  9910. }
  9911. function getDesktopStreamFailed(error) {
  9912. console.error("Failed to obtain the stream to switch to", error);
  9913. switchInProgress = false;
  9914. }
  9915. function streamSwitchDone() {
  9916. switchInProgress = false;
  9917. eventEmitter.emit(
  9918. DesktopSharingEventTypes.SWITCHING_DONE,
  9919. isUsingScreenStream);
  9920. }
  9921. function newStreamCreated(stream)
  9922. {
  9923. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  9924. stream, isUsingScreenStream, streamSwitchDone);
  9925. }
  9926. function onEndedHandler(stream) {
  9927. if (!switchInProgress && isUsingScreenStream) {
  9928. APP.desktopsharing.toggleScreenSharing();
  9929. }
  9930. //FIXME: to be verified
  9931. if (stream.removeEventListener) {
  9932. stream.removeEventListener('ended', onEndedHandler);
  9933. } else {
  9934. stream.detachEvent('ended', onEndedHandler);
  9935. }
  9936. }
  9937. // Called when RTC finishes initialization
  9938. function onWebRtcReady() {
  9939. setDesktopSharing(config.desktopSharing);
  9940. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  9941. }
  9942. module.exports = {
  9943. isUsingScreenStream: function () {
  9944. return isUsingScreenStream;
  9945. },
  9946. /**
  9947. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  9948. * and enabled.
  9949. */
  9950. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  9951. init: function () {
  9952. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  9953. },
  9954. addListener: function (listener, type)
  9955. {
  9956. eventEmitter.on(type, listener);
  9957. },
  9958. removeListener: function (listener, type) {
  9959. eventEmitter.removeListener(type, listener);
  9960. },
  9961. /*
  9962. * Toggles screen sharing.
  9963. */
  9964. toggleScreenSharing: function () {
  9965. if (switchInProgress || !obtainDesktopStream) {
  9966. console.warn("Switch in progress or no method defined");
  9967. return;
  9968. }
  9969. switchInProgress = true;
  9970. if (!isUsingScreenStream)
  9971. {
  9972. // Switch to desktop stream
  9973. obtainDesktopStream(
  9974. function (stream) {
  9975. // We now use screen stream
  9976. isUsingScreenStream = true;
  9977. // Hook 'ended' event to restore camera
  9978. // when screen stream stops
  9979. //FIXME: to be verified
  9980. if (stream.addEventListener) {
  9981. stream.addEventListener('ended', function () {
  9982. onEndedHandler(stream);
  9983. });
  9984. } else {
  9985. stream.attachEvent('ended', function () {
  9986. onEndedHandler(stream);
  9987. });
  9988. }
  9989. newStreamCreated(stream);
  9990. },
  9991. getDesktopStreamFailed);
  9992. } else {
  9993. // Disable screen stream
  9994. APP.RTC.getUserMediaWithConstraints(
  9995. ['video'],
  9996. function (stream) {
  9997. // We are now using camera stream
  9998. isUsingScreenStream = false;
  9999. newStreamCreated(stream);
  10000. },
  10001. getVideoStreamFailed, config.resolution || '360'
  10002. );
  10003. }
  10004. }
  10005. };
  10006. },{"../../service/RTC/RTCEvents":99,"../../service/desktopsharing/DesktopSharingEventTypes":105,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":109}],45:[function(require,module,exports){
  10007. //maps keycode to character, id of popover for given function and function
  10008. var shortcuts = {};
  10009. function initShortcutHandlers() {
  10010. shortcuts = {
  10011. 67: {
  10012. character: "C",
  10013. id: "toggleChatPopover",
  10014. function: APP.UI.toggleChat
  10015. },
  10016. 70: {
  10017. character: "F",
  10018. id: "filmstripPopover",
  10019. function: APP.UI.toggleFilmStrip
  10020. },
  10021. 77: {
  10022. character: "M",
  10023. id: "mutePopover",
  10024. function: APP.UI.toggleAudio
  10025. },
  10026. 84: {
  10027. character: "T",
  10028. function: function() {
  10029. if(!APP.RTC.localAudio.isMuted()) {
  10030. APP.UI.toggleAudio();
  10031. }
  10032. }
  10033. },
  10034. 86: {
  10035. character: "V",
  10036. id: "toggleVideoPopover",
  10037. function: APP.UI.toggleVideo
  10038. }
  10039. };
  10040. }
  10041. var KeyboardShortcut = {
  10042. init: function () {
  10043. initShortcutHandlers();
  10044. window.onkeyup = function(e) {
  10045. var keycode = e.which;
  10046. if(!($(":focus").is("input[type=text]") ||
  10047. $(":focus").is("input[type=password]") ||
  10048. $(":focus").is("textarea"))) {
  10049. if (typeof shortcuts[keycode] === "object") {
  10050. shortcuts[keycode].function();
  10051. }
  10052. else if (keycode >= "0".charCodeAt(0) &&
  10053. keycode <= "9".charCodeAt(0)) {
  10054. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10055. }
  10056. //esc while the smileys are visible hides them
  10057. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10058. APP.UI.toggleSmileys();
  10059. }
  10060. };
  10061. window.onkeydown = function(e) {
  10062. if(!($(":focus").is("input[type=text]") ||
  10063. $(":focus").is("input[type=password]") ||
  10064. $(":focus").is("textarea"))) {
  10065. if(e.which === "T".charCodeAt(0)) {
  10066. if(APP.RTC.localAudio.isMuted()) {
  10067. APP.UI.toggleAudio();
  10068. }
  10069. }
  10070. }
  10071. };
  10072. var self = this;
  10073. $('body').popover({ selector: '[data-toggle=popover]',
  10074. trigger: 'click hover',
  10075. content: function() {
  10076. return this.getAttribute("content") +
  10077. self.getShortcut(this.getAttribute("shortcut"));
  10078. }
  10079. });
  10080. },
  10081. /**
  10082. *
  10083. * @param id indicates the popover associated with the shortcut
  10084. * @returns {string} the keyboard shortcut used for the id given
  10085. */
  10086. getShortcut: function (id) {
  10087. for (var keycode in shortcuts) {
  10088. if (shortcuts.hasOwnProperty(keycode)) {
  10089. if (shortcuts[keycode].id === id) {
  10090. return " (" + shortcuts[keycode].character + ")";
  10091. }
  10092. }
  10093. }
  10094. return "";
  10095. }
  10096. };
  10097. module.exports = KeyboardShortcut;
  10098. },{}],46:[function(require,module,exports){
  10099. /* global APP */
  10100. /**
  10101. * This module is meant to (eventually) contain and manage all information
  10102. * about members/participants of the conference, so that other modules don't
  10103. * have to do it on their own, and so that other modules can access members'
  10104. * information from a single place.
  10105. *
  10106. * Currently this module only manages information about the support of jingle
  10107. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10108. * be added as needed.
  10109. */
  10110. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10111. var Events = require("../../service/members/Events");
  10112. var EventEmitter = require("events");
  10113. var eventEmitter = new EventEmitter();
  10114. /**
  10115. * The actual container.
  10116. */
  10117. var members = {};
  10118. /**
  10119. * There is at least one member that supports DTMF (i.e. is jigasi).
  10120. */
  10121. var atLeastOneDtmf = false;
  10122. function registerListeners() {
  10123. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10124. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10125. }
  10126. /**
  10127. * Handles a new member joining the MUC.
  10128. */
  10129. function onMucMemberJoined(jid, id, displayName) {
  10130. var member = {
  10131. displayName: displayName
  10132. };
  10133. APP.xmpp.getConnection().disco.info(
  10134. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10135. members[jid] = member;
  10136. }
  10137. /**
  10138. * Handles a member leaving the MUC.
  10139. */
  10140. function onMucMemberLeft(jid) {
  10141. delete members[jid];
  10142. updateAtLeastOneDtmf();
  10143. }
  10144. /**
  10145. * Handles the reception of a disco#info packet from a particular JID.
  10146. * @param jid the JID sending the packet.
  10147. * @param iq the packet.
  10148. */
  10149. function onDiscoInfoReceived(jid, iq) {
  10150. if (!members[jid])
  10151. return;
  10152. var supportsDtmf
  10153. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10154. updateDtmf(jid, supportsDtmf);
  10155. }
  10156. /**
  10157. * Updates the 'supportsDtmf' field for a member.
  10158. * @param jid the jid of the member.
  10159. * @param newValue the new value for the 'supportsDtmf' field.
  10160. */
  10161. function updateDtmf(jid, newValue) {
  10162. var oldValue = members[jid].supportsDtmf;
  10163. members[jid].supportsDtmf = newValue;
  10164. if (newValue != oldValue) {
  10165. updateAtLeastOneDtmf();
  10166. }
  10167. }
  10168. /**
  10169. * Checks each member's 'supportsDtmf' field and updates
  10170. * 'atLastOneSupportsDtmf'.
  10171. */
  10172. function updateAtLeastOneDtmf(){
  10173. var newAtLeastOneDtmf = false;
  10174. for (var key in members) {
  10175. if (typeof members[key].supportsDtmf !== 'undefined'
  10176. && members[key].supportsDtmf) {
  10177. newAtLeastOneDtmf= true;
  10178. break;
  10179. }
  10180. }
  10181. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10182. atLeastOneDtmf = newAtLeastOneDtmf;
  10183. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10184. }
  10185. }
  10186. /**
  10187. * Exported interface.
  10188. */
  10189. var Members = {
  10190. start: function(){
  10191. registerListeners();
  10192. },
  10193. addListener: function(type, listener)
  10194. {
  10195. eventEmitter.on(type, listener);
  10196. },
  10197. removeListener: function (type, listener) {
  10198. eventEmitter.removeListener(type, listener);
  10199. },
  10200. size: function () {
  10201. return Object.keys(members).length;
  10202. },
  10203. getMembers: function () {
  10204. return members;
  10205. }
  10206. };
  10207. module.exports = Members;
  10208. },{"../../service/members/Events":106,"../../service/xmpp/XMPPEvents":108,"events":109}],47:[function(require,module,exports){
  10209. var email = '';
  10210. var displayName = '';
  10211. var userId;
  10212. var language = null;
  10213. function supportsLocalStorage() {
  10214. try {
  10215. return 'localStorage' in window && window.localStorage !== null;
  10216. } catch (e) {
  10217. console.log("localstorage is not supported");
  10218. return false;
  10219. }
  10220. }
  10221. function generateUniqueId() {
  10222. function _p8() {
  10223. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10224. }
  10225. return _p8() + _p8() + _p8() + _p8();
  10226. }
  10227. if (supportsLocalStorage()) {
  10228. if (!window.localStorage.jitsiMeetId) {
  10229. window.localStorage.jitsiMeetId = generateUniqueId();
  10230. console.log("generated id", window.localStorage.jitsiMeetId);
  10231. }
  10232. userId = window.localStorage.jitsiMeetId || '';
  10233. email = window.localStorage.email || '';
  10234. displayName = window.localStorage.displayname || '';
  10235. language = window.localStorage.language;
  10236. } else {
  10237. console.log("local storage is not supported");
  10238. userId = generateUniqueId();
  10239. }
  10240. var Settings =
  10241. {
  10242. setDisplayName: function (newDisplayName) {
  10243. displayName = newDisplayName;
  10244. window.localStorage.displayname = displayName;
  10245. return displayName;
  10246. },
  10247. setEmail: function (newEmail)
  10248. {
  10249. email = newEmail;
  10250. window.localStorage.email = newEmail;
  10251. return email;
  10252. },
  10253. getSettings: function () {
  10254. return {
  10255. email: email,
  10256. displayName: displayName,
  10257. uid: userId,
  10258. language: language
  10259. };
  10260. },
  10261. setLanguage: function (lang) {
  10262. language = lang;
  10263. window.localStorage.language = lang;
  10264. }
  10265. };
  10266. module.exports = Settings;
  10267. },{}],48:[function(require,module,exports){
  10268. var callStats = null;
  10269. function initCallback (err, msg) {
  10270. console.log("Initializing Status: err="+err+" msg="+msg);
  10271. }
  10272. var CallStats = {
  10273. init: function (jingleSession) {
  10274. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10275. return;
  10276. callStats = new callstats($,io,jsSHA);
  10277. this.session = jingleSession;
  10278. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10279. this.userID = APP.xmpp.myResource();
  10280. var location = window.location;
  10281. this.confID = location.protocol + "//" +
  10282. location.hostname + location.pathname;
  10283. //userID is generated or given by the origin server
  10284. callStats.initialize(config.callStatsID,
  10285. config.callStatsSecret,
  10286. this.userID,
  10287. initCallback);
  10288. var usage = callStats.fabricUsage.unbundled;
  10289. if(config.useBundle)
  10290. usage = callStats.fabricUsage.multiplex;
  10291. callStats.addNewFabric(this.peerconnection,
  10292. Strophe.getResourceFromJid(jingleSession.peerjid),
  10293. usage,
  10294. this.confID,
  10295. this.pcCallback.bind(this));
  10296. },
  10297. pcCallback: function (err, msg) {
  10298. if(!callStats)
  10299. return;
  10300. console.log("Monitoring status: "+ err + " msg: " + msg);
  10301. callStats.sendFabricEvent(this.peerconnection,
  10302. callStats.fabricEvent.fabricSetup, this.confID);
  10303. },
  10304. sendMuteEvent: function (mute, type) {
  10305. if(!callStats)
  10306. return;
  10307. var event = null;
  10308. if(type === "video")
  10309. {
  10310. event = (mute? callStats.fabricEvent.videoPause :
  10311. callStats.fabricEvent.videoResume);
  10312. }
  10313. else
  10314. {
  10315. event = (mute? callStats.fabricEvent.audioMute :
  10316. callStats.fabricEvent.audioUnmute);
  10317. }
  10318. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10319. },
  10320. sendTerminateEvent: function () {
  10321. if(!callStats)
  10322. return;
  10323. callStats.sendFabricEvent(this.peerconnection,
  10324. callStats.fabricEvent.fabricTerminated, this.confID);
  10325. },
  10326. sendSetupFailedEvent: function () {
  10327. if(!callStats)
  10328. return;
  10329. callStats.sendFabricEvent(this.peerconnection,
  10330. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10331. }
  10332. };
  10333. module.exports = CallStats;
  10334. },{}],49:[function(require,module,exports){
  10335. /**
  10336. * Provides statistics for the local stream.
  10337. */
  10338. /**
  10339. * Size of the webaudio analizer buffer.
  10340. * @type {number}
  10341. */
  10342. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  10343. /**
  10344. * Value of the webaudio analizer smoothing time parameter.
  10345. * @type {number}
  10346. */
  10347. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  10348. /**
  10349. * Converts time domain data array to audio level.
  10350. * @param array the time domain data array.
  10351. * @returns {number} the audio level
  10352. */
  10353. function timeDomainDataToAudioLevel(samples) {
  10354. var maxVolume = 0;
  10355. var length = samples.length;
  10356. for (var i = 0; i < length; i++) {
  10357. if (maxVolume < samples[i])
  10358. maxVolume = samples[i];
  10359. }
  10360. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10361. };
  10362. /**
  10363. * Animates audio level change
  10364. * @param newLevel the new audio level
  10365. * @param lastLevel the last audio level
  10366. * @returns {Number} the audio level to be set
  10367. */
  10368. function animateLevel(newLevel, lastLevel)
  10369. {
  10370. var value = 0;
  10371. var diff = lastLevel - newLevel;
  10372. if(diff > 0.2)
  10373. {
  10374. value = lastLevel - 0.2;
  10375. }
  10376. else if(diff < -0.4)
  10377. {
  10378. value = lastLevel + 0.4;
  10379. }
  10380. else
  10381. {
  10382. value = newLevel;
  10383. }
  10384. return parseFloat(value.toFixed(3));
  10385. }
  10386. /**
  10387. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10388. *
  10389. * @param stream the local stream
  10390. * @param interval stats refresh interval given in ms.
  10391. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  10392. * update.
  10393. * @constructor
  10394. */
  10395. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10396. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10397. this.stream = stream;
  10398. this.intervalId = null;
  10399. this.intervalMilis = interval;
  10400. this.eventEmitter = eventEmitter;
  10401. this.audioLevel = 0;
  10402. this.statisticsService = statisticsService;
  10403. }
  10404. /**
  10405. * Starts the collecting the statistics.
  10406. */
  10407. LocalStatsCollector.prototype.start = function () {
  10408. if (config.disableAudioLevels || !window.AudioContext)
  10409. return;
  10410. var context = new AudioContext();
  10411. var analyser = context.createAnalyser();
  10412. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  10413. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  10414. var source = context.createMediaStreamSource(this.stream);
  10415. source.connect(analyser);
  10416. var self = this;
  10417. this.intervalId = setInterval(
  10418. function () {
  10419. var array = new Uint8Array(analyser.frequencyBinCount);
  10420. analyser.getByteTimeDomainData(array);
  10421. var audioLevel = timeDomainDataToAudioLevel(array);
  10422. if(audioLevel != self.audioLevel) {
  10423. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10424. self.eventEmitter.emit(
  10425. "statistics.audioLevel",
  10426. self.statisticsService.LOCAL_JID,
  10427. self.audioLevel);
  10428. }
  10429. },
  10430. this.intervalMilis
  10431. );
  10432. };
  10433. /**
  10434. * Stops collecting the statistics.
  10435. */
  10436. LocalStatsCollector.prototype.stop = function () {
  10437. if (this.intervalId) {
  10438. clearInterval(this.intervalId);
  10439. this.intervalId = null;
  10440. }
  10441. };
  10442. module.exports = LocalStatsCollector;
  10443. },{}],50:[function(require,module,exports){
  10444. /* global ssrc2jid */
  10445. /* jshint -W117 */
  10446. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10447. /**
  10448. * Calculates packet lost percent using the number of lost packets and the
  10449. * number of all packet.
  10450. * @param lostPackets the number of lost packets
  10451. * @param totalPackets the number of all packets.
  10452. * @returns {number} packet loss percent
  10453. */
  10454. function calculatePacketLoss(lostPackets, totalPackets) {
  10455. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10456. return 0;
  10457. return Math.round((lostPackets/totalPackets)*100);
  10458. }
  10459. function getStatValue(item, name) {
  10460. var browserType = RTCBrowserType.getBrowserType();
  10461. if (!keyMap[browserType][name])
  10462. throw "The property isn't supported!";
  10463. var key = keyMap[browserType][name];
  10464. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10465. item.stat(key) : item[key];
  10466. }
  10467. /**
  10468. * Peer statistics data holder.
  10469. * @constructor
  10470. */
  10471. function PeerStats()
  10472. {
  10473. this.ssrc2Loss = {};
  10474. this.ssrc2AudioLevel = {};
  10475. this.ssrc2bitrate = {};
  10476. this.ssrc2resolution = {};
  10477. }
  10478. /**
  10479. * The bandwidth
  10480. * @type {{}}
  10481. */
  10482. PeerStats.bandwidth = {};
  10483. /**
  10484. * The bit rate
  10485. * @type {{}}
  10486. */
  10487. PeerStats.bitrate = {};
  10488. /**
  10489. * The packet loss rate
  10490. * @type {{}}
  10491. */
  10492. PeerStats.packetLoss = null;
  10493. /**
  10494. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10495. * represented by this instance.
  10496. * @param ssrc audio or video RTP stream SSRC.
  10497. * @param lossRate new packet loss rate value to be set.
  10498. */
  10499. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10500. {
  10501. this.ssrc2Loss[ssrc] = lossRate;
  10502. };
  10503. /**
  10504. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10505. * represented by this instance.
  10506. * @param ssrc audio or video RTP stream SSRC.
  10507. * @param resolution new resolution value to be set.
  10508. */
  10509. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10510. {
  10511. if(resolution === null && this.ssrc2resolution[ssrc])
  10512. {
  10513. delete this.ssrc2resolution[ssrc];
  10514. }
  10515. else if(resolution !== null)
  10516. this.ssrc2resolution[ssrc] = resolution;
  10517. };
  10518. /**
  10519. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10520. * represented by this instance.
  10521. * @param ssrc audio or video RTP stream SSRC.
  10522. * @param bitrate new bitrate value to be set.
  10523. */
  10524. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10525. {
  10526. if(this.ssrc2bitrate[ssrc])
  10527. {
  10528. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10529. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10530. }
  10531. else {
  10532. this.ssrc2bitrate[ssrc] = bitrate;
  10533. }
  10534. };
  10535. /**
  10536. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10537. * the stream which belongs to the peer represented by this instance.
  10538. * @param ssrc RTP stream SSRC for which current audio level value will be
  10539. * updated.
  10540. * @param audioLevel the new audio level value to be set. Value is truncated to
  10541. * fit the range from 0 to 1.
  10542. */
  10543. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10544. {
  10545. // Range limit 0 - 1
  10546. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10547. };
  10548. function formatAudioLevel(audioLevel) {
  10549. return Math.min(Math.max(audioLevel, 0), 1);
  10550. }
  10551. /**
  10552. * Array with the transport information.
  10553. * @type {Array}
  10554. */
  10555. PeerStats.transport = [];
  10556. /**
  10557. * <tt>StatsCollector</tt> registers for stats updates of given
  10558. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10559. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10560. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10561. * instance as an event source.
  10562. *
  10563. * @param peerconnection webRTC peer connection object.
  10564. * @param interval stats refresh interval given in ms.
  10565. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10566. * called on stats update.
  10567. * @constructor
  10568. */
  10569. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10570. {
  10571. this.peerconnection = peerconnection;
  10572. this.baselineAudioLevelsReport = null;
  10573. this.currentAudioLevelsReport = null;
  10574. this.currentStatsReport = null;
  10575. this.baselineStatsReport = null;
  10576. this.audioLevelsIntervalId = null;
  10577. this.eventEmitter = eventEmitter;
  10578. /**
  10579. * Gather PeerConnection stats once every this many milliseconds.
  10580. */
  10581. this.GATHER_INTERVAL = 15000;
  10582. /**
  10583. * Log stats via the focus once every this many milliseconds.
  10584. */
  10585. this.LOG_INTERVAL = 60000;
  10586. /**
  10587. * Gather stats and store them in this.statsToBeLogged.
  10588. */
  10589. this.gatherStatsIntervalId = null;
  10590. /**
  10591. * Send the stats already saved in this.statsToBeLogged to be logged via
  10592. * the focus.
  10593. */
  10594. this.logStatsIntervalId = null;
  10595. /**
  10596. * Stores the statistics which will be send to the focus to be logged.
  10597. */
  10598. this.statsToBeLogged =
  10599. {
  10600. timestamps: [],
  10601. stats: {}
  10602. };
  10603. // Updates stats interval
  10604. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10605. this.statsIntervalId = null;
  10606. this.statsIntervalMilis = statsInterval;
  10607. // Map of jids to PeerStats
  10608. this.jid2stats = {};
  10609. }
  10610. module.exports = StatsCollector;
  10611. /**
  10612. * Stops stats updates.
  10613. */
  10614. StatsCollector.prototype.stop = function () {
  10615. if (this.audioLevelsIntervalId) {
  10616. clearInterval(this.audioLevelsIntervalId);
  10617. this.audioLevelsIntervalId = null;
  10618. }
  10619. if (this.statsIntervalId)
  10620. {
  10621. clearInterval(this.statsIntervalId);
  10622. this.statsIntervalId = null;
  10623. }
  10624. if(this.logStatsIntervalId)
  10625. {
  10626. clearInterval(this.logStatsIntervalId);
  10627. this.logStatsIntervalId = null;
  10628. }
  10629. if(this.gatherStatsIntervalId)
  10630. {
  10631. clearInterval(this.gatherStatsIntervalId);
  10632. this.gatherStatsIntervalId = null;
  10633. }
  10634. };
  10635. /**
  10636. * Callback passed to <tt>getStats</tt> method.
  10637. * @param error an error that occurred on <tt>getStats</tt> call.
  10638. */
  10639. StatsCollector.prototype.errorCallback = function (error)
  10640. {
  10641. console.error("Get stats error", error);
  10642. this.stop();
  10643. };
  10644. /**
  10645. * Starts stats updates.
  10646. */
  10647. StatsCollector.prototype.start = function ()
  10648. {
  10649. var self = this;
  10650. if(!config.disableAudioLevels) {
  10651. this.audioLevelsIntervalId = setInterval(
  10652. function () {
  10653. // Interval updates
  10654. self.peerconnection.getStats(
  10655. function (report) {
  10656. var results = null;
  10657. if (!report || !report.result ||
  10658. typeof report.result != 'function') {
  10659. results = report;
  10660. }
  10661. else {
  10662. results = report.result();
  10663. }
  10664. //console.error("Got interval report", results);
  10665. self.currentAudioLevelsReport = results;
  10666. self.processAudioLevelReport();
  10667. self.baselineAudioLevelsReport =
  10668. self.currentAudioLevelsReport;
  10669. },
  10670. self.errorCallback
  10671. );
  10672. },
  10673. self.audioLevelsIntervalMilis
  10674. );
  10675. }
  10676. if(!config.disableStats && !navigator.mozGetUserMedia) {
  10677. this.statsIntervalId = setInterval(
  10678. function () {
  10679. // Interval updates
  10680. self.peerconnection.getStats(
  10681. function (report) {
  10682. var results = null;
  10683. if (!report || !report.result ||
  10684. typeof report.result != 'function') {
  10685. //firefox
  10686. results = report;
  10687. }
  10688. else {
  10689. //chrome
  10690. results = report.result();
  10691. }
  10692. //console.error("Got interval report", results);
  10693. self.currentStatsReport = results;
  10694. try {
  10695. self.processStatsReport();
  10696. }
  10697. catch (e) {
  10698. console.error("Unsupported key:" + e, e);
  10699. }
  10700. self.baselineStatsReport = self.currentStatsReport;
  10701. },
  10702. self.errorCallback
  10703. );
  10704. },
  10705. self.statsIntervalMilis
  10706. );
  10707. }
  10708. if (config.logStats && !navigator.mozGetUserMedia) {
  10709. this.gatherStatsIntervalId = setInterval(
  10710. function () {
  10711. self.peerconnection.getStats(
  10712. function (report) {
  10713. self.addStatsToBeLogged(report.result());
  10714. },
  10715. function () {
  10716. }
  10717. );
  10718. },
  10719. this.GATHER_INTERVAL
  10720. );
  10721. this.logStatsIntervalId = setInterval(
  10722. function() { self.logStats(); },
  10723. this.LOG_INTERVAL);
  10724. }
  10725. };
  10726. /**
  10727. * Checks whether a certain record should be included in the logged statistics.
  10728. */
  10729. function acceptStat(reportId, reportType, statName) {
  10730. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10731. return false;
  10732. if (reportType == "ssrc") {
  10733. if (statName == "googTrackId" ||
  10734. statName == "transportId" ||
  10735. statName == "ssrc")
  10736. return false;
  10737. }
  10738. return true;
  10739. }
  10740. /**
  10741. * Checks whether a certain record should be included in the logged statistics.
  10742. */
  10743. function acceptReport(id, type) {
  10744. if (id.substring(0, 15) == "googCertificate" ||
  10745. id.substring(0, 9) == "googTrack" ||
  10746. id.substring(0, 20) == "googLibjingleSession")
  10747. return false;
  10748. if (type == "googComponent")
  10749. return false;
  10750. return true;
  10751. }
  10752. /**
  10753. * Converts the stats to the format used for logging, and saves the data in
  10754. * this.statsToBeLogged.
  10755. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10756. */
  10757. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10758. var self = this;
  10759. var num_records = this.statsToBeLogged.timestamps.length;
  10760. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10761. reports.map(function (report) {
  10762. if (!acceptReport(report.id, report.type))
  10763. return;
  10764. var stat = self.statsToBeLogged.stats[report.id];
  10765. if (!stat) {
  10766. stat = self.statsToBeLogged.stats[report.id] = {};
  10767. }
  10768. stat.type = report.type;
  10769. report.names().map(function (name) {
  10770. if (!acceptStat(report.id, report.type, name))
  10771. return;
  10772. var values = stat[name];
  10773. if (!values) {
  10774. values = stat[name] = [];
  10775. }
  10776. while (values.length < num_records) {
  10777. values.push(null);
  10778. }
  10779. values.push(report.stat(name));
  10780. });
  10781. });
  10782. };
  10783. StatsCollector.prototype.logStats = function () {
  10784. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10785. return;
  10786. // Reset the stats
  10787. this.statsToBeLogged.stats = {};
  10788. this.statsToBeLogged.timestamps = [];
  10789. };
  10790. var keyMap = {};
  10791. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10792. "ssrc": "ssrc",
  10793. "packetsReceived": "packetsReceived",
  10794. "packetsLost": "packetsLost",
  10795. "packetsSent": "packetsSent",
  10796. "bytesReceived": "bytesReceived",
  10797. "bytesSent": "bytesSent"
  10798. };
  10799. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10800. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10801. "sendBandwidth": "googAvailableSendBandwidth",
  10802. "remoteAddress": "googRemoteAddress",
  10803. "transportType": "googTransportType",
  10804. "localAddress": "googLocalAddress",
  10805. "activeConnection": "googActiveConnection",
  10806. "ssrc": "ssrc",
  10807. "packetsReceived": "packetsReceived",
  10808. "packetsSent": "packetsSent",
  10809. "packetsLost": "packetsLost",
  10810. "bytesReceived": "bytesReceived",
  10811. "bytesSent": "bytesSent",
  10812. "googFrameHeightReceived": "googFrameHeightReceived",
  10813. "googFrameWidthReceived": "googFrameWidthReceived",
  10814. "googFrameHeightSent": "googFrameHeightSent",
  10815. "googFrameWidthSent": "googFrameWidthSent",
  10816. "audioInputLevel": "audioInputLevel",
  10817. "audioOutputLevel": "audioOutputLevel"
  10818. };
  10819. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  10820. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  10821. /**
  10822. * Stats processing logic.
  10823. */
  10824. StatsCollector.prototype.processStatsReport = function () {
  10825. if (!this.baselineStatsReport) {
  10826. return;
  10827. }
  10828. for (var idx in this.currentStatsReport) {
  10829. var now = this.currentStatsReport[idx];
  10830. try {
  10831. if (getStatValue(now, 'receiveBandwidth') ||
  10832. getStatValue(now, 'sendBandwidth')) {
  10833. PeerStats.bandwidth = {
  10834. "download": Math.round(
  10835. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10836. "upload": Math.round(
  10837. (getStatValue(now, 'sendBandwidth')) / 1000)
  10838. };
  10839. }
  10840. }
  10841. catch(e){/*not supported*/}
  10842. if(now.type == 'googCandidatePair')
  10843. {
  10844. var ip, type, localIP, active;
  10845. try {
  10846. ip = getStatValue(now, 'remoteAddress');
  10847. type = getStatValue(now, "transportType");
  10848. localIP = getStatValue(now, "localAddress");
  10849. active = getStatValue(now, "activeConnection");
  10850. }
  10851. catch(e){/*not supported*/}
  10852. if(!ip || !type || !localIP || active != "true")
  10853. continue;
  10854. var addressSaved = false;
  10855. for(var i = 0; i < PeerStats.transport.length; i++)
  10856. {
  10857. if(PeerStats.transport[i].ip == ip &&
  10858. PeerStats.transport[i].type == type &&
  10859. PeerStats.transport[i].localip == localIP)
  10860. {
  10861. addressSaved = true;
  10862. }
  10863. }
  10864. if(addressSaved)
  10865. continue;
  10866. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10867. continue;
  10868. }
  10869. if(now.type == "candidatepair")
  10870. {
  10871. if(now.state == "succeeded")
  10872. continue;
  10873. var local = this.currentStatsReport[now.localCandidateId];
  10874. var remote = this.currentStatsReport[now.remoteCandidateId];
  10875. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10876. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10877. }
  10878. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10879. now.type != "inboundrtp") {
  10880. continue;
  10881. }
  10882. var before = this.baselineStatsReport[idx];
  10883. if (!before) {
  10884. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10885. continue;
  10886. }
  10887. var ssrc = getStatValue(now, 'ssrc');
  10888. if(!ssrc)
  10889. continue;
  10890. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10891. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10892. console.warn("No jid for ssrc: " + ssrc);
  10893. continue;
  10894. }
  10895. var jidStats = this.jid2stats[jid];
  10896. if (!jidStats) {
  10897. jidStats = new PeerStats();
  10898. this.jid2stats[jid] = jidStats;
  10899. }
  10900. var isDownloadStream = true;
  10901. var key = 'packetsReceived';
  10902. if (!getStatValue(now, key))
  10903. {
  10904. isDownloadStream = false;
  10905. key = 'packetsSent';
  10906. if (!getStatValue(now, key))
  10907. {
  10908. console.warn("No packetsReceived nor packetSent stat found");
  10909. continue;
  10910. }
  10911. }
  10912. var packetsNow = getStatValue(now, key);
  10913. if(!packetsNow || packetsNow < 0)
  10914. packetsNow = 0;
  10915. var packetsBefore = getStatValue(before, key);
  10916. if(!packetsBefore || packetsBefore < 0)
  10917. packetsBefore = 0;
  10918. var packetRate = packetsNow - packetsBefore;
  10919. if(!packetRate || packetRate < 0)
  10920. packetRate = 0;
  10921. var currentLoss = getStatValue(now, 'packetsLost');
  10922. if(!currentLoss || currentLoss < 0)
  10923. currentLoss = 0;
  10924. var previousLoss = getStatValue(before, 'packetsLost');
  10925. if(!previousLoss || previousLoss < 0)
  10926. previousLoss = 0;
  10927. var lossRate = currentLoss - previousLoss;
  10928. if(!lossRate || lossRate < 0)
  10929. lossRate = 0;
  10930. var packetsTotal = (packetRate + lossRate);
  10931. jidStats.setSsrcLoss(ssrc,
  10932. {"packetsTotal": packetsTotal,
  10933. "packetsLost": lossRate,
  10934. "isDownloadStream": isDownloadStream});
  10935. var bytesReceived = 0, bytesSent = 0;
  10936. if(getStatValue(now, "bytesReceived"))
  10937. {
  10938. bytesReceived = getStatValue(now, "bytesReceived") -
  10939. getStatValue(before, "bytesReceived");
  10940. }
  10941. if(getStatValue(now, "bytesSent"))
  10942. {
  10943. bytesSent = getStatValue(now, "bytesSent") -
  10944. getStatValue(before, "bytesSent");
  10945. }
  10946. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10947. if(bytesReceived <= 0 || time <= 0)
  10948. {
  10949. bytesReceived = 0;
  10950. }
  10951. else
  10952. {
  10953. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10954. }
  10955. if(bytesSent <= 0 || time <= 0)
  10956. {
  10957. bytesSent = 0;
  10958. }
  10959. else
  10960. {
  10961. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10962. }
  10963. jidStats.setSsrcBitrate(ssrc, {
  10964. "download": bytesReceived,
  10965. "upload": bytesSent});
  10966. var resolution = {height: null, width: null};
  10967. try {
  10968. if (getStatValue(now, "googFrameHeightReceived") &&
  10969. getStatValue(now, "googFrameWidthReceived")) {
  10970. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10971. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10972. }
  10973. else if (getStatValue(now, "googFrameHeightSent") &&
  10974. getStatValue(now, "googFrameWidthSent")) {
  10975. resolution.height = getStatValue(now, "googFrameHeightSent");
  10976. resolution.width = getStatValue(now, "googFrameWidthSent");
  10977. }
  10978. }
  10979. catch(e){/*not supported*/}
  10980. if(resolution.height && resolution.width)
  10981. {
  10982. jidStats.setSsrcResolution(ssrc, resolution);
  10983. }
  10984. else
  10985. {
  10986. jidStats.setSsrcResolution(ssrc, null);
  10987. }
  10988. }
  10989. var self = this;
  10990. // Jid stats
  10991. var totalPackets = {download: 0, upload: 0};
  10992. var lostPackets = {download: 0, upload: 0};
  10993. var bitrateDownload = 0;
  10994. var bitrateUpload = 0;
  10995. var resolutions = {};
  10996. Object.keys(this.jid2stats).forEach(
  10997. function (jid)
  10998. {
  10999. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11000. function (ssrc)
  11001. {
  11002. var type = "upload";
  11003. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11004. type = "download";
  11005. totalPackets[type] +=
  11006. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11007. lostPackets[type] +=
  11008. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11009. }
  11010. );
  11011. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11012. function (ssrc) {
  11013. bitrateDownload +=
  11014. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11015. bitrateUpload +=
  11016. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11017. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11018. }
  11019. );
  11020. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11021. }
  11022. );
  11023. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11024. PeerStats.packetLoss = {
  11025. total:
  11026. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11027. totalPackets.download + totalPackets.upload),
  11028. download:
  11029. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11030. upload:
  11031. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11032. };
  11033. this.eventEmitter.emit("statistics.connectionstats",
  11034. {
  11035. "bitrate": PeerStats.bitrate,
  11036. "packetLoss": PeerStats.packetLoss,
  11037. "bandwidth": PeerStats.bandwidth,
  11038. "resolution": resolutions,
  11039. "transport": PeerStats.transport
  11040. });
  11041. PeerStats.transport = [];
  11042. };
  11043. /**
  11044. * Stats processing logic.
  11045. */
  11046. StatsCollector.prototype.processAudioLevelReport = function ()
  11047. {
  11048. if (!this.baselineAudioLevelsReport)
  11049. {
  11050. return;
  11051. }
  11052. for (var idx in this.currentAudioLevelsReport)
  11053. {
  11054. var now = this.currentAudioLevelsReport[idx];
  11055. if (now.type != 'ssrc')
  11056. {
  11057. continue;
  11058. }
  11059. var before = this.baselineAudioLevelsReport[idx];
  11060. if (!before)
  11061. {
  11062. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11063. continue;
  11064. }
  11065. var ssrc = getStatValue(now, 'ssrc');
  11066. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11067. if (!jid)
  11068. {
  11069. if((Date.now() - now.timestamp) < 3000)
  11070. console.warn("No jid for ssrc: " + ssrc);
  11071. continue;
  11072. }
  11073. var jidStats = this.jid2stats[jid];
  11074. if (!jidStats)
  11075. {
  11076. jidStats = new PeerStats();
  11077. this.jid2stats[jid] = jidStats;
  11078. }
  11079. // Audio level
  11080. var audioLevel = null;
  11081. try {
  11082. audioLevel = getStatValue(now, 'audioInputLevel');
  11083. if (!audioLevel)
  11084. audioLevel = getStatValue(now, 'audioOutputLevel');
  11085. }
  11086. catch(e) {/*not supported*/
  11087. console.warn("Audio Levels are not available in the statistics.");
  11088. clearInterval(this.audioLevelsIntervalId);
  11089. return;
  11090. }
  11091. if (audioLevel)
  11092. {
  11093. // TODO: can't find specs about what this value really is,
  11094. // but it seems to vary between 0 and around 32k.
  11095. audioLevel = audioLevel / 32767;
  11096. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11097. if(jid != APP.xmpp.myJid())
  11098. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11099. }
  11100. }
  11101. };
  11102. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11103. /**
  11104. * Created by hristo on 8/4/14.
  11105. */
  11106. var LocalStats = require("./LocalStatsCollector.js");
  11107. var RTPStats = require("./RTPStatsCollector.js");
  11108. var EventEmitter = require("events");
  11109. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11110. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11111. var CallStats = require("./CallStats");
  11112. var RTCEvents = require("../../service/RTC/RTCEvents");
  11113. var eventEmitter = new EventEmitter();
  11114. var localStats = null;
  11115. var rtpStats = null;
  11116. function stopLocal()
  11117. {
  11118. if(localStats)
  11119. {
  11120. localStats.stop();
  11121. localStats = null;
  11122. }
  11123. }
  11124. function stopRemote()
  11125. {
  11126. if(rtpStats)
  11127. {
  11128. rtpStats.stop();
  11129. eventEmitter.emit("statistics.stop");
  11130. rtpStats = null;
  11131. }
  11132. }
  11133. function startRemoteStats (peerconnection) {
  11134. if(rtpStats)
  11135. {
  11136. rtpStats.stop();
  11137. rtpStats = null;
  11138. }
  11139. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11140. rtpStats.start();
  11141. }
  11142. function onStreamCreated(stream)
  11143. {
  11144. if(stream.getOriginalStream().getAudioTracks().length === 0)
  11145. return;
  11146. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11147. eventEmitter);
  11148. localStats.start();
  11149. }
  11150. function onDisposeConference(onUnload) {
  11151. CallStats.sendTerminateEvent();
  11152. stopRemote();
  11153. if(onUnload) {
  11154. stopLocal();
  11155. eventEmitter.removeAllListeners();
  11156. }
  11157. }
  11158. var statistics =
  11159. {
  11160. /**
  11161. * Indicates that this audio level is for local jid.
  11162. * @type {string}
  11163. */
  11164. LOCAL_JID: 'local',
  11165. addAudioLevelListener: function(listener)
  11166. {
  11167. eventEmitter.on("statistics.audioLevel", listener);
  11168. },
  11169. removeAudioLevelListener: function(listener)
  11170. {
  11171. eventEmitter.removeListener("statistics.audioLevel", listener);
  11172. },
  11173. addConnectionStatsListener: function(listener)
  11174. {
  11175. eventEmitter.on("statistics.connectionstats", listener);
  11176. },
  11177. removeConnectionStatsListener: function(listener)
  11178. {
  11179. eventEmitter.removeListener("statistics.connectionstats", listener);
  11180. },
  11181. addRemoteStatsStopListener: function(listener)
  11182. {
  11183. eventEmitter.on("statistics.stop", listener);
  11184. },
  11185. removeRemoteStatsStopListener: function(listener)
  11186. {
  11187. eventEmitter.removeListener("statistics.stop", listener);
  11188. },
  11189. stop: function () {
  11190. stopLocal();
  11191. stopRemote();
  11192. if(eventEmitter)
  11193. {
  11194. eventEmitter.removeAllListeners();
  11195. }
  11196. },
  11197. stopRemoteStatistics: function()
  11198. {
  11199. stopRemote();
  11200. },
  11201. start: function () {
  11202. APP.RTC.addStreamListener(onStreamCreated,
  11203. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11204. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11205. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11206. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11207. startRemoteStats(event.peerconnection);
  11208. // CallStats.init(event);
  11209. });
  11210. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11211. CallStats.init(session);
  11212. })
  11213. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11214. CallStats.sendMuteEvent(mute, "audio");
  11215. });
  11216. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11217. CallStats.sendSetupFailedEvent();
  11218. })
  11219. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11220. CallStats.sendMuteEvent(mute, "video");
  11221. });
  11222. }
  11223. };
  11224. module.exports = statistics;
  11225. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes.js":101,"../../service/xmpp/XMPPEvents":108,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":109}],52:[function(require,module,exports){
  11226. var i18n = require("i18next-client");
  11227. var languages = require("../../service/translation/languages");
  11228. var Settings = require("../settings/Settings");
  11229. var DEFAULT_LANG = languages.EN;
  11230. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11231. return value.replace("__app__", interfaceConfig.APP_NAME);
  11232. });
  11233. var defaultOptions = {
  11234. detectLngQS: "lang",
  11235. useCookie: false,
  11236. fallbackLng: DEFAULT_LANG,
  11237. load: "unspecific",
  11238. resGetPath: 'lang/__ns__-__lng__.json',
  11239. ns: {
  11240. namespaces: ['main', 'languages'],
  11241. defaultNs: 'main'
  11242. },
  11243. lngWhitelist : languages.getLanguages(),
  11244. fallbackOnNull: true,
  11245. fallbackOnEmpty: true,
  11246. useDataAttrOptions: true,
  11247. defaultValueFromContent: false,
  11248. app: interfaceConfig.APP_NAME,
  11249. getAsync: false,
  11250. defaultValueFromContent: false,
  11251. customLoad: function(lng, ns, options, done) {
  11252. var resPath = "lang/__ns__-__lng__.json";
  11253. if(lng === languages.EN)
  11254. resPath = "lang/__ns__.json";
  11255. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11256. i18n.functions.ajax({
  11257. url: url,
  11258. success: function(data, status, xhr) {
  11259. i18n.functions.log('loaded: ' + url);
  11260. done(null, data);
  11261. },
  11262. error : function(xhr, status, error) {
  11263. if ((status && status == 200) ||
  11264. (xhr && xhr.status && xhr.status == 200)) {
  11265. // file loaded but invalid json, stop waste time !
  11266. i18n.functions.error('There is a typo in: ' + url);
  11267. } else if ((status && status == 404) ||
  11268. (xhr && xhr.status && xhr.status == 404)) {
  11269. i18n.functions.log('Does not exist: ' + url);
  11270. } else {
  11271. var theStatus = status ? status :
  11272. ((xhr && xhr.status) ? xhr.status : null);
  11273. i18n.functions.log(theStatus + ' when loading ' + url);
  11274. }
  11275. done(error, {});
  11276. },
  11277. dataType: "json",
  11278. async : options.getAsync
  11279. });
  11280. }
  11281. // options for caching
  11282. // useLocalStorage: true,
  11283. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11284. };
  11285. function initCompleted(t)
  11286. {
  11287. $("[data-i18n]").i18n();
  11288. }
  11289. function checkForParameter() {
  11290. var query = window.location.search.substring(1);
  11291. var vars = query.split("&");
  11292. for (var i=0;i<vars.length;i++) {
  11293. var pair = vars[i].split("=");
  11294. if(pair[0] == "lang")
  11295. {
  11296. return pair[1];
  11297. }
  11298. }
  11299. return null;
  11300. }
  11301. module.exports = {
  11302. init: function (lang) {
  11303. var options = defaultOptions;
  11304. if(!lang)
  11305. {
  11306. lang = checkForParameter();
  11307. if(!lang)
  11308. {
  11309. var settings = Settings.getSettings();
  11310. if(settings)
  11311. lang = settings.language;
  11312. if(!lang && config.defaultLanguage)
  11313. {
  11314. lang = config.defaultLanguage;
  11315. }
  11316. }
  11317. }
  11318. if(lang) {
  11319. options.lng = lang;
  11320. }
  11321. i18n.init(options, initCompleted);
  11322. },
  11323. translateString: function (key, options) {
  11324. return i18n.t(key, options);
  11325. },
  11326. setLanguage: function (lang) {
  11327. if(!lang)
  11328. lang = DEFAULT_LANG;
  11329. i18n.setLng(lang, defaultOptions, initCompleted);
  11330. },
  11331. getCurrentLanguage: function () {
  11332. return i18n.lng();
  11333. },
  11334. translateElement: function (selector) {
  11335. selector.i18n();
  11336. },
  11337. generateTranslationHTML: function (key, options) {
  11338. var str = "<span data-i18n=\"" + key + "\"";
  11339. if(options)
  11340. {
  11341. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11342. }
  11343. str += ">";
  11344. str += this.translateString(key, options);
  11345. str += "</span>";
  11346. return str;
  11347. }
  11348. };
  11349. },{"../../service/translation/languages":107,"../settings/Settings":47,"i18next-client":68}],53:[function(require,module,exports){
  11350. /* jshint -W117 */
  11351. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11352. var SDPDiffer = require("./SDPDiffer");
  11353. var SDPUtil = require("./SDPUtil");
  11354. var SDP = require("./SDP");
  11355. var async = require("async");
  11356. var transform = require("sdp-transform");
  11357. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11358. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11359. // Jingle stuff
  11360. function JingleSession(me, sid, connection, service, eventEmitter) {
  11361. this.me = me;
  11362. this.sid = sid;
  11363. this.connection = connection;
  11364. this.initiator = null;
  11365. this.responder = null;
  11366. this.isInitiator = null;
  11367. this.peerjid = null;
  11368. this.state = null;
  11369. this.localSDP = null;
  11370. this.remoteSDP = null;
  11371. this.relayedStreams = [];
  11372. this.startTime = null;
  11373. this.stopTime = null;
  11374. this.media_constraints = null;
  11375. this.pc_constraints = null;
  11376. this.ice_config = {};
  11377. this.drip_container = [];
  11378. this.service = service;
  11379. this.usetrickle = true;
  11380. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11381. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11382. this.hadstuncandidate = false;
  11383. this.hadturncandidate = false;
  11384. this.lasticecandidate = false;
  11385. this.statsinterval = null;
  11386. this.reason = null;
  11387. this.addssrc = [];
  11388. this.removessrc = [];
  11389. this.pendingop = null;
  11390. this.switchstreams = false;
  11391. this.wait = true;
  11392. this.localStreamsSSRC = null;
  11393. this.ssrcOwners = {};
  11394. this.ssrcVideoTypes = {};
  11395. this.eventEmitter = eventEmitter;
  11396. /**
  11397. * The indicator which determines whether the (local) video has been muted
  11398. * in response to a user command in contrast to an automatic decision made
  11399. * by the application logic.
  11400. */
  11401. this.videoMuteByUser = false;
  11402. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11403. // We start with the queue paused. We resume it when the signaling state is
  11404. // stable and the ice connection state is connected.
  11405. this.modifySourcesQueue.pause();
  11406. }
  11407. JingleSession.prototype.updateModifySourcesQueue = function() {
  11408. var signalingState = this.peerconnection.signalingState;
  11409. var iceConnectionState = this.peerconnection.iceConnectionState;
  11410. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11411. this.modifySourcesQueue.resume();
  11412. } else {
  11413. this.modifySourcesQueue.pause();
  11414. }
  11415. };
  11416. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11417. var self = this;
  11418. if (this.state !== null) {
  11419. console.error('attempt to initiate on session ' + this.sid +
  11420. 'in state ' + this.state);
  11421. return;
  11422. }
  11423. this.isInitiator = isInitiator;
  11424. this.state = 'pending';
  11425. this.initiator = isInitiator ? this.me : peerjid;
  11426. this.responder = !isInitiator ? this.me : peerjid;
  11427. this.peerjid = peerjid;
  11428. this.hadstuncandidate = false;
  11429. this.hadturncandidate = false;
  11430. this.lasticecandidate = false;
  11431. this.peerconnection
  11432. = new TraceablePeerConnection(
  11433. this.connection.jingle.ice_config,
  11434. this.connection.jingle.pc_constraints,
  11435. this);
  11436. this.peerconnection.onicecandidate = function (event) {
  11437. self.sendIceCandidate(event.candidate);
  11438. };
  11439. this.peerconnection.onaddstream = function (event) {
  11440. if (event.stream.id !== 'default') {
  11441. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11442. self.remoteStreamAdded(event);
  11443. } else {
  11444. // This is a recvonly stream. Clients that implement Unified Plan,
  11445. // such as Firefox use recvonly "streams/channels/tracks" for
  11446. // receiving remote stream/tracks, as opposed to Plan B where there
  11447. // are only 3 channels: audio, video and data.
  11448. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11449. }
  11450. };
  11451. this.peerconnection.onremovestream = function (event) {
  11452. // Remove the stream from remoteStreams
  11453. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11454. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11455. };
  11456. this.peerconnection.onsignalingstatechange = function (event) {
  11457. if (!(self && self.peerconnection)) return;
  11458. self.updateModifySourcesQueue();
  11459. };
  11460. this.peerconnection.oniceconnectionstatechange = function (event) {
  11461. if (!(self && self.peerconnection)) return;
  11462. self.updateModifySourcesQueue();
  11463. switch (self.peerconnection.iceConnectionState) {
  11464. case 'connected':
  11465. this.startTime = new Date();
  11466. break;
  11467. case 'disconnected':
  11468. this.stopTime = new Date();
  11469. break;
  11470. case 'failed':
  11471. self.eventEmitter(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11472. break;
  11473. }
  11474. onIceConnectionStateChange(self.sid, self);
  11475. };
  11476. this.peerconnection.onnegotiationneeded = function (event) {
  11477. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11478. };
  11479. // add any local and relayed stream
  11480. APP.RTC.localStreams.forEach(function(stream) {
  11481. self.peerconnection.addStream(stream.getOriginalStream());
  11482. });
  11483. this.relayedStreams.forEach(function(stream) {
  11484. self.peerconnection.addStream(stream);
  11485. });
  11486. };
  11487. function onIceConnectionStateChange(sid, session) {
  11488. switch (session.peerconnection.iceConnectionState) {
  11489. case 'checking':
  11490. session.timeChecking = (new Date()).getTime();
  11491. session.firstconnect = true;
  11492. break;
  11493. case 'completed': // on caller side
  11494. case 'connected':
  11495. if (session.firstconnect) {
  11496. session.firstconnect = false;
  11497. var metadata = {};
  11498. metadata.setupTime
  11499. = (new Date()).getTime() - session.timeChecking;
  11500. session.peerconnection.getStats(function (res) {
  11501. if(res && res.result) {
  11502. res.result().forEach(function (report) {
  11503. if (report.type == 'googCandidatePair' &&
  11504. report.stat('googActiveConnection') == 'true') {
  11505. metadata.localCandidateType
  11506. = report.stat('googLocalCandidateType');
  11507. metadata.remoteCandidateType
  11508. = report.stat('googRemoteCandidateType');
  11509. // log pair as well so we can get nice pie
  11510. // charts
  11511. metadata.candidatePair
  11512. = report.stat('googLocalCandidateType') +
  11513. ';' +
  11514. report.stat('googRemoteCandidateType');
  11515. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11516. {
  11517. metadata.ipv6 = true;
  11518. }
  11519. }
  11520. });
  11521. }
  11522. });
  11523. }
  11524. break;
  11525. }
  11526. }
  11527. JingleSession.prototype.getVideoType = function () {
  11528. return APP.desktopsharing.isUsingScreenStream() ? 'screen' : 'camera';
  11529. };
  11530. JingleSession.prototype.accept = function () {
  11531. this.state = 'active';
  11532. var pranswer = this.peerconnection.localDescription;
  11533. if (!pranswer || pranswer.type != 'pranswer') {
  11534. return;
  11535. }
  11536. console.log('going from pranswer to answer');
  11537. if (this.usetrickle) {
  11538. // remove candidates already sent from session-accept
  11539. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11540. for (var i = 0; i < lines.length; i++) {
  11541. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11542. }
  11543. }
  11544. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11545. // FIXME: change any inactive to sendrecv or whatever they were originally
  11546. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11547. }
  11548. var prsdp = new SDP(pranswer.sdp);
  11549. var accept = $iq({to: this.peerjid,
  11550. type: 'set'})
  11551. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11552. action: 'session-accept',
  11553. initiator: this.initiator,
  11554. responder: this.responder,
  11555. sid: this.sid });
  11556. // FIXME why do we generate session-accept in 3 different places ?
  11557. prsdp.toJingle(
  11558. accept,
  11559. this.initiator == this.me ? 'initiator' : 'responder',
  11560. this.localStreamsSSRC,
  11561. self.getVideoType());
  11562. var sdp = this.peerconnection.localDescription.sdp;
  11563. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11564. // FIXME: change any inactive to sendrecv or whatever they were originally
  11565. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11566. }
  11567. var self = this;
  11568. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11569. function () {
  11570. //console.log('setLocalDescription success');
  11571. self.setLocalDescription();
  11572. self.connection.sendIQ(accept,
  11573. function () {
  11574. var ack = {};
  11575. ack.source = 'answer';
  11576. $(document).trigger('ack.jingle', [self.sid, ack]);
  11577. },
  11578. function (stanza) {
  11579. var error = ($(stanza).find('error').length) ? {
  11580. code: $(stanza).find('error').attr('code'),
  11581. reason: $(stanza).find('error :first')[0].tagName
  11582. }:{};
  11583. error.source = 'answer';
  11584. JingleSession.onJingleError(self.sid, error);
  11585. },
  11586. 10000);
  11587. },
  11588. function (e) {
  11589. console.error('setLocalDescription failed', e);
  11590. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11591. }
  11592. );
  11593. };
  11594. JingleSession.prototype.terminate = function (reason) {
  11595. this.state = 'ended';
  11596. this.reason = reason;
  11597. this.peerconnection.close();
  11598. if (this.statsinterval !== null) {
  11599. window.clearInterval(this.statsinterval);
  11600. this.statsinterval = null;
  11601. }
  11602. };
  11603. JingleSession.prototype.active = function () {
  11604. return this.state == 'active';
  11605. };
  11606. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11607. var self = this;
  11608. if (candidate && !this.lasticecandidate) {
  11609. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11610. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11611. if (!(ice && jcand)) {
  11612. console.error('failed to get ice && jcand');
  11613. return;
  11614. }
  11615. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11616. if (jcand.type === 'srflx') {
  11617. this.hadstuncandidate = true;
  11618. } else if (jcand.type === 'relay') {
  11619. this.hadturncandidate = true;
  11620. }
  11621. if (this.usetrickle) {
  11622. if (this.usedrip) {
  11623. if (this.drip_container.length === 0) {
  11624. // start 20ms callout
  11625. window.setTimeout(function () {
  11626. if (self.drip_container.length === 0) return;
  11627. self.sendIceCandidates(self.drip_container);
  11628. self.drip_container = [];
  11629. }, 20);
  11630. }
  11631. this.drip_container.push(candidate);
  11632. return;
  11633. } else {
  11634. self.sendIceCandidate([candidate]);
  11635. }
  11636. }
  11637. } else {
  11638. //console.log('sendIceCandidate: last candidate.');
  11639. if (!this.usetrickle) {
  11640. //console.log('should send full offer now...');
  11641. //FIXME why do we generate session-accept in 3 different places ?
  11642. var init = $iq({to: this.peerjid,
  11643. type: 'set'})
  11644. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11645. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11646. initiator: this.initiator,
  11647. sid: this.sid});
  11648. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11649. var self = this;
  11650. var sendJingle = function (ssrc) {
  11651. if(!ssrc)
  11652. ssrc = {};
  11653. self.localSDP.toJingle(
  11654. init,
  11655. self.initiator == self.me ? 'initiator' : 'responder',
  11656. ssrc,
  11657. self.getVideoType());
  11658. self.connection.sendIQ(init,
  11659. function () {
  11660. //console.log('session initiate ack');
  11661. var ack = {};
  11662. ack.source = 'offer';
  11663. $(document).trigger('ack.jingle', [self.sid, ack]);
  11664. },
  11665. function (stanza) {
  11666. self.state = 'error';
  11667. self.peerconnection.close();
  11668. var error = ($(stanza).find('error').length) ? {
  11669. code: $(stanza).find('error').attr('code'),
  11670. reason: $(stanza).find('error :first')[0].tagName,
  11671. }:{};
  11672. error.source = 'offer';
  11673. JingleSession.onJingleError(self.sid, error);
  11674. },
  11675. 10000);
  11676. }
  11677. sendJingle();
  11678. }
  11679. this.lasticecandidate = true;
  11680. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11681. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11682. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11683. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11684. }
  11685. }
  11686. };
  11687. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11688. console.log('sendIceCandidates', candidates);
  11689. var cand = $iq({to: this.peerjid, type: 'set'})
  11690. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11691. action: 'transport-info',
  11692. initiator: this.initiator,
  11693. sid: this.sid});
  11694. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11695. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11696. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11697. if (cands.length > 0) {
  11698. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11699. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11700. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11701. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11702. }).c('transport', ice);
  11703. for (var i = 0; i < cands.length; i++) {
  11704. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11705. }
  11706. // add fingerprint
  11707. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11708. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11709. tmp.required = true;
  11710. cand.c(
  11711. 'fingerprint',
  11712. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11713. .t(tmp.fingerprint);
  11714. delete tmp.fingerprint;
  11715. cand.attrs(tmp);
  11716. cand.up();
  11717. }
  11718. cand.up(); // transport
  11719. cand.up(); // content
  11720. }
  11721. }
  11722. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11723. //console.log('was this the last candidate', this.lasticecandidate);
  11724. this.connection.sendIQ(cand,
  11725. function () {
  11726. var ack = {};
  11727. ack.source = 'transportinfo';
  11728. $(document).trigger('ack.jingle', [this.sid, ack]);
  11729. },
  11730. function (stanza) {
  11731. var error = ($(stanza).find('error').length) ? {
  11732. code: $(stanza).find('error').attr('code'),
  11733. reason: $(stanza).find('error :first')[0].tagName,
  11734. }:{};
  11735. error.source = 'transportinfo';
  11736. JingleSession.onJingleError(this.sid, error);
  11737. },
  11738. 10000);
  11739. };
  11740. JingleSession.prototype.sendOffer = function () {
  11741. //console.log('sendOffer...');
  11742. var self = this;
  11743. this.peerconnection.createOffer(function (sdp) {
  11744. self.createdOffer(sdp);
  11745. },
  11746. function (e) {
  11747. console.error('createOffer failed', e);
  11748. },
  11749. this.media_constraints
  11750. );
  11751. };
  11752. // FIXME createdOffer is never used in jitsi-meet
  11753. JingleSession.prototype.createdOffer = function (sdp) {
  11754. //console.log('createdOffer', sdp);
  11755. var self = this;
  11756. this.localSDP = new SDP(sdp.sdp);
  11757. //this.localSDP.mangle();
  11758. var sendJingle = function () {
  11759. var init = $iq({to: this.peerjid,
  11760. type: 'set'})
  11761. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11762. action: 'session-initiate',
  11763. initiator: this.initiator,
  11764. sid: this.sid});
  11765. self.localSDP.toJingle(
  11766. init,
  11767. this.initiator == this.me ? 'initiator' : 'responder',
  11768. this.localStreamsSSRC,
  11769. self.getVideoType());
  11770. self.connection.sendIQ(init,
  11771. function () {
  11772. var ack = {};
  11773. ack.source = 'offer';
  11774. $(document).trigger('ack.jingle', [self.sid, ack]);
  11775. },
  11776. function (stanza) {
  11777. self.state = 'error';
  11778. self.peerconnection.close();
  11779. var error = ($(stanza).find('error').length) ? {
  11780. code: $(stanza).find('error').attr('code'),
  11781. reason: $(stanza).find('error :first')[0].tagName,
  11782. }:{};
  11783. error.source = 'offer';
  11784. JingleSession.onJingleError(self.sid, error);
  11785. },
  11786. 10000);
  11787. }
  11788. sdp.sdp = this.localSDP.raw;
  11789. this.peerconnection.setLocalDescription(sdp,
  11790. function () {
  11791. if(self.usetrickle)
  11792. {
  11793. sendJingle();
  11794. }
  11795. self.setLocalDescription();
  11796. //console.log('setLocalDescription success');
  11797. },
  11798. function (e) {
  11799. console.error('setLocalDescription failed', e);
  11800. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11801. }
  11802. );
  11803. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11804. for (var i = 0; i < cands.length; i++) {
  11805. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11806. if (cand.type == 'srflx') {
  11807. this.hadstuncandidate = true;
  11808. } else if (cand.type == 'relay') {
  11809. this.hadturncandidate = true;
  11810. }
  11811. }
  11812. };
  11813. JingleSession.prototype.readSsrcInfo = function (contents) {
  11814. var self = this;
  11815. $(contents).each(function (idx, content) {
  11816. var name = $(content).attr('name');
  11817. var mediaType = this.getAttribute('name');
  11818. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11819. ssrcs.each(function () {
  11820. var ssrc = this.getAttribute('ssrc');
  11821. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  11822. function () {
  11823. var owner = this.getAttribute('owner');
  11824. var videoType = this.getAttribute('video-type');
  11825. self.ssrcOwners[ssrc] = owner;
  11826. self.ssrcVideoTypes[ssrc] = videoType;
  11827. }
  11828. );
  11829. });
  11830. });
  11831. };
  11832. JingleSession.prototype.getSsrcOwner = function (ssrc) {
  11833. return this.ssrcOwners[ssrc];
  11834. };
  11835. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11836. //console.log('setting remote description... ', desctype);
  11837. this.remoteSDP = new SDP('');
  11838. this.remoteSDP.fromJingle(elem);
  11839. this.readSsrcInfo($(elem).find(">content"));
  11840. if (this.peerconnection.remoteDescription !== null) {
  11841. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11842. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11843. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11844. for (var i = 0; i < pranswer.media.length; i++) {
  11845. // make sure we have ice ufrag and pwd
  11846. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11847. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11848. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11849. } else {
  11850. console.warn('no ice ufrag?');
  11851. }
  11852. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11853. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11854. } else {
  11855. console.warn('no ice pwd?');
  11856. }
  11857. }
  11858. // copy over candidates
  11859. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11860. for (var j = 0; j < lines.length; j++) {
  11861. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11862. }
  11863. }
  11864. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11865. }
  11866. }
  11867. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11868. this.peerconnection.setRemoteDescription(remotedesc,
  11869. function () {
  11870. //console.log('setRemoteDescription success');
  11871. },
  11872. function (e) {
  11873. console.error('setRemoteDescription error', e);
  11874. JingleSession.onJingleFatalError(self, e);
  11875. }
  11876. );
  11877. };
  11878. JingleSession.prototype.addIceCandidate = function (elem) {
  11879. var self = this;
  11880. if (this.peerconnection.signalingState == 'closed') {
  11881. return;
  11882. }
  11883. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11884. console.log('trickle ice candidate arriving before session accept...');
  11885. // create a PRANSWER for setRemoteDescription
  11886. if (!this.remoteSDP) {
  11887. var cobbled = 'v=0\r\n' +
  11888. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11889. 's=-\r\n' +
  11890. 't=0 0\r\n';
  11891. // first, take some things from the local description
  11892. for (var i = 0; i < this.localSDP.media.length; i++) {
  11893. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11894. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11895. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11896. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11897. }
  11898. cobbled += 'a=inactive\r\n';
  11899. }
  11900. this.remoteSDP = new SDP(cobbled);
  11901. }
  11902. // then add things like ice and dtls from remote candidate
  11903. elem.each(function () {
  11904. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11905. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11906. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11907. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11908. var tmp = $(this).find('transport');
  11909. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11910. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11911. tmp = $(this).find('transport>fingerprint');
  11912. if (tmp.length) {
  11913. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11914. } else {
  11915. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11916. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11917. }
  11918. break;
  11919. }
  11920. }
  11921. }
  11922. });
  11923. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11924. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11925. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11926. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11927. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11928. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11929. }).length == this.remoteSDP.media.length;
  11930. if (iscomplete) {
  11931. console.log('setting pranswer');
  11932. try {
  11933. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11934. function() {
  11935. },
  11936. function(e) {
  11937. console.log('setRemoteDescription pranswer failed', e.toString());
  11938. });
  11939. } catch (e) {
  11940. console.error('setting pranswer failed', e);
  11941. }
  11942. } else {
  11943. //console.log('not yet setting pranswer');
  11944. }
  11945. }
  11946. // operate on each content element
  11947. elem.each(function () {
  11948. // would love to deactivate this, but firefox still requires it
  11949. var idx = -1;
  11950. var i;
  11951. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11952. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11953. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11954. idx = i;
  11955. break;
  11956. }
  11957. }
  11958. if (idx == -1) { // fall back to localdescription
  11959. for (i = 0; i < self.localSDP.media.length; i++) {
  11960. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11961. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11962. idx = i;
  11963. break;
  11964. }
  11965. }
  11966. }
  11967. var name = $(this).attr('name');
  11968. // TODO: check ice-pwd and ice-ufrag?
  11969. $(this).find('transport>candidate').each(function () {
  11970. var line, candidate;
  11971. line = SDPUtil.candidateFromJingle(this);
  11972. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11973. sdpMid: name,
  11974. candidate: line});
  11975. try {
  11976. self.peerconnection.addIceCandidate(candidate);
  11977. } catch (e) {
  11978. console.error('addIceCandidate failed', e.toString(), line);
  11979. }
  11980. });
  11981. });
  11982. };
  11983. JingleSession.prototype.sendAnswer = function (provisional) {
  11984. //console.log('createAnswer', provisional);
  11985. var self = this;
  11986. this.peerconnection.createAnswer(
  11987. function (sdp) {
  11988. self.createdAnswer(sdp, provisional);
  11989. },
  11990. function (e) {
  11991. console.error('createAnswer failed', e);
  11992. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11993. },
  11994. this.media_constraints
  11995. );
  11996. };
  11997. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11998. //console.log('createAnswer callback');
  11999. var self = this;
  12000. this.localSDP = new SDP(sdp.sdp);
  12001. //this.localSDP.mangle();
  12002. this.usepranswer = provisional === true;
  12003. if (this.usetrickle) {
  12004. if (this.usepranswer) {
  12005. sdp.type = 'pranswer';
  12006. for (var i = 0; i < this.localSDP.media.length; i++) {
  12007. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12008. }
  12009. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12010. }
  12011. }
  12012. var self = this;
  12013. var sendJingle = function (ssrcs) {
  12014. // FIXME why do we generate session-accept in 3 different places ?
  12015. var accept = $iq({to: self.peerjid,
  12016. type: 'set'})
  12017. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12018. action: 'session-accept',
  12019. initiator: self.initiator,
  12020. responder: self.responder,
  12021. sid: self.sid });
  12022. self.localSDP.toJingle(
  12023. accept,
  12024. self.initiator == self.me ? 'initiator' : 'responder',
  12025. ssrcs,
  12026. self.getVideoType());
  12027. self.connection.sendIQ(accept,
  12028. function () {
  12029. var ack = {};
  12030. ack.source = 'answer';
  12031. $(document).trigger('ack.jingle', [self.sid, ack]);
  12032. },
  12033. function (stanza) {
  12034. var error = ($(stanza).find('error').length) ? {
  12035. code: $(stanza).find('error').attr('code'),
  12036. reason: $(stanza).find('error :first')[0].tagName,
  12037. }:{};
  12038. error.source = 'answer';
  12039. JingleSession.onJingleError(self.sid, error);
  12040. },
  12041. 10000);
  12042. }
  12043. sdp.sdp = this.localSDP.raw;
  12044. this.peerconnection.setLocalDescription(sdp,
  12045. function () {
  12046. //console.log('setLocalDescription success');
  12047. if (self.usetrickle && !self.usepranswer) {
  12048. sendJingle();
  12049. }
  12050. self.setLocalDescription();
  12051. },
  12052. function (e) {
  12053. console.error('setLocalDescription failed', e);
  12054. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12055. }
  12056. );
  12057. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12058. for (var j = 0; j < cands.length; j++) {
  12059. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12060. if (cand.type == 'srflx') {
  12061. this.hadstuncandidate = true;
  12062. } else if (cand.type == 'relay') {
  12063. this.hadturncandidate = true;
  12064. }
  12065. }
  12066. };
  12067. JingleSession.prototype.sendTerminate = function (reason, text) {
  12068. var self = this,
  12069. term = $iq({to: this.peerjid,
  12070. type: 'set'})
  12071. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12072. action: 'session-terminate',
  12073. initiator: this.initiator,
  12074. sid: this.sid})
  12075. .c('reason')
  12076. .c(reason || 'success');
  12077. if (text) {
  12078. term.up().c('text').t(text);
  12079. }
  12080. this.connection.sendIQ(term,
  12081. function () {
  12082. self.peerconnection.close();
  12083. self.peerconnection = null;
  12084. self.terminate();
  12085. var ack = {};
  12086. ack.source = 'terminate';
  12087. $(document).trigger('ack.jingle', [self.sid, ack]);
  12088. },
  12089. function (stanza) {
  12090. var error = ($(stanza).find('error').length) ? {
  12091. code: $(stanza).find('error').attr('code'),
  12092. reason: $(stanza).find('error :first')[0].tagName,
  12093. }:{};
  12094. $(document).trigger('ack.jingle', [self.sid, error]);
  12095. },
  12096. 10000);
  12097. if (this.statsinterval !== null) {
  12098. window.clearInterval(this.statsinterval);
  12099. this.statsinterval = null;
  12100. }
  12101. };
  12102. JingleSession.prototype.addSource = function (elem, fromJid) {
  12103. var self = this;
  12104. // FIXME: dirty waiting
  12105. if (!this.peerconnection.localDescription)
  12106. {
  12107. console.warn("addSource - localDescription not ready yet")
  12108. setTimeout(function()
  12109. {
  12110. self.addSource(elem, fromJid);
  12111. },
  12112. 200
  12113. );
  12114. return;
  12115. }
  12116. console.log('addssrc', new Date().getTime());
  12117. console.log('ice', this.peerconnection.iceConnectionState);
  12118. this.readSsrcInfo(elem);
  12119. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12120. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12121. $(elem).each(function (idx, content) {
  12122. var name = $(content).attr('name');
  12123. var lines = '';
  12124. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12125. var semantics = this.getAttribute('semantics');
  12126. var ssrcs = $(this).find('>source').map(function () {
  12127. return this.getAttribute('ssrc');
  12128. }).get();
  12129. if (ssrcs.length != 0) {
  12130. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12131. }
  12132. });
  12133. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12134. tmp.each(function () {
  12135. var ssrc = $(this).attr('ssrc');
  12136. if(mySdp.containsSSRC(ssrc)){
  12137. /**
  12138. * This happens when multiple participants change their streams at the same time and
  12139. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12140. * addssrc are scheduled for update IQ. See
  12141. */
  12142. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12143. return;
  12144. }
  12145. $(this).find('>parameter').each(function () {
  12146. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12147. if ($(this).attr('value') && $(this).attr('value').length)
  12148. lines += ':' + $(this).attr('value');
  12149. lines += '\r\n';
  12150. });
  12151. });
  12152. sdp.media.forEach(function(media, idx) {
  12153. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12154. return;
  12155. sdp.media[idx] += lines;
  12156. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12157. self.addssrc[idx] += lines;
  12158. });
  12159. sdp.raw = sdp.session + sdp.media.join('');
  12160. });
  12161. this.modifySourcesQueue.push(function() {
  12162. // When a source is added and if this is FF, a new channel is allocated
  12163. // for receiving the added source. We need to diffuse the SSRC of this
  12164. // new recvonly channel to the rest of the peers.
  12165. console.log('modify sources done');
  12166. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12167. console.log("SDPs", mySdp, newSdp);
  12168. self.notifyMySSRCUpdate(mySdp, newSdp);
  12169. });
  12170. };
  12171. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12172. var self = this;
  12173. // FIXME: dirty waiting
  12174. if (!this.peerconnection.localDescription)
  12175. {
  12176. console.warn("removeSource - localDescription not ready yet")
  12177. setTimeout(function()
  12178. {
  12179. self.removeSource(elem, fromJid);
  12180. },
  12181. 200
  12182. );
  12183. return;
  12184. }
  12185. console.log('removessrc', new Date().getTime());
  12186. console.log('ice', this.peerconnection.iceConnectionState);
  12187. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12188. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12189. $(elem).each(function (idx, content) {
  12190. var name = $(content).attr('name');
  12191. var lines = '';
  12192. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12193. var semantics = this.getAttribute('semantics');
  12194. var ssrcs = $(this).find('>source').map(function () {
  12195. return this.getAttribute('ssrc');
  12196. }).get();
  12197. if (ssrcs.length != 0) {
  12198. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12199. }
  12200. });
  12201. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12202. tmp.each(function () {
  12203. var ssrc = $(this).attr('ssrc');
  12204. // This should never happen, but can be useful for bug detection
  12205. if(mySdp.containsSSRC(ssrc)){
  12206. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12207. return;
  12208. }
  12209. $(this).find('>parameter').each(function () {
  12210. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12211. if ($(this).attr('value') && $(this).attr('value').length)
  12212. lines += ':' + $(this).attr('value');
  12213. lines += '\r\n';
  12214. });
  12215. });
  12216. sdp.media.forEach(function(media, idx) {
  12217. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12218. return;
  12219. sdp.media[idx] += lines;
  12220. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12221. self.removessrc[idx] += lines;
  12222. });
  12223. sdp.raw = sdp.session + sdp.media.join('');
  12224. });
  12225. this.modifySourcesQueue.push(function() {
  12226. // When a source is removed and if this is FF, the recvonly channel that
  12227. // receives the remote stream is deactivated . We need to diffuse the
  12228. // recvonly SSRC removal to the rest of the peers.
  12229. console.log('modify sources done');
  12230. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12231. console.log("SDPs", mySdp, newSdp);
  12232. self.notifyMySSRCUpdate(mySdp, newSdp);
  12233. });
  12234. };
  12235. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12236. var self = this;
  12237. if (this.peerconnection.signalingState == 'closed') return;
  12238. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12239. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12240. this.setLocalDescription();
  12241. if(successCallback){
  12242. successCallback();
  12243. }
  12244. queueCallback();
  12245. return;
  12246. }
  12247. // Reset switch streams flag
  12248. this.switchstreams = false;
  12249. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12250. // add sources
  12251. this.addssrc.forEach(function(lines, idx) {
  12252. sdp.media[idx] += lines;
  12253. });
  12254. this.addssrc = [];
  12255. // remove sources
  12256. this.removessrc.forEach(function(lines, idx) {
  12257. lines = lines.split('\r\n');
  12258. lines.pop(); // remove empty last element;
  12259. lines.forEach(function(line) {
  12260. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12261. });
  12262. });
  12263. this.removessrc = [];
  12264. sdp.raw = sdp.session + sdp.media.join('');
  12265. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12266. function() {
  12267. if(self.signalingState == 'closed') {
  12268. console.error("createAnswer attempt on closed state");
  12269. queueCallback("createAnswer attempt on closed state");
  12270. return;
  12271. }
  12272. self.peerconnection.createAnswer(
  12273. function(modifiedAnswer) {
  12274. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12275. if (self.pendingop !== null) {
  12276. var sdp = new SDP(modifiedAnswer.sdp);
  12277. if (sdp.media.length > 1) {
  12278. switch(self.pendingop) {
  12279. case 'mute':
  12280. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12281. break;
  12282. case 'unmute':
  12283. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12284. break;
  12285. }
  12286. sdp.raw = sdp.session + sdp.media.join('');
  12287. modifiedAnswer.sdp = sdp.raw;
  12288. }
  12289. self.pendingop = null;
  12290. }
  12291. // FIXME: pushing down an answer while ice connection state
  12292. // is still checking is bad...
  12293. //console.log(self.peerconnection.iceConnectionState);
  12294. // trying to work around another chrome bug
  12295. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12296. self.peerconnection.setLocalDescription(modifiedAnswer,
  12297. function() {
  12298. //console.log('modified setLocalDescription ok');
  12299. self.setLocalDescription();
  12300. if(successCallback){
  12301. successCallback();
  12302. }
  12303. queueCallback();
  12304. },
  12305. function(error) {
  12306. console.error('modified setLocalDescription failed', error);
  12307. queueCallback(error);
  12308. }
  12309. );
  12310. },
  12311. function(error) {
  12312. console.error('modified answer failed', error);
  12313. queueCallback(error);
  12314. }
  12315. );
  12316. },
  12317. function(error) {
  12318. console.error('modify failed', error);
  12319. queueCallback(error);
  12320. }
  12321. );
  12322. };
  12323. /**
  12324. * Switches video streams.
  12325. * @param new_stream new stream that will be used as video of this session.
  12326. * @param oldStream old video stream of this session.
  12327. * @param success_callback callback executed after successful stream switch.
  12328. */
  12329. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12330. var self = this;
  12331. // Remember SDP to figure out added/removed SSRCs
  12332. var oldSdp = null;
  12333. if(self.peerconnection) {
  12334. if(self.peerconnection.localDescription) {
  12335. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12336. }
  12337. self.peerconnection.removeStream(oldStream, true);
  12338. if(new_stream)
  12339. self.peerconnection.addStream(new_stream);
  12340. }
  12341. // Conference is not active
  12342. if(!oldSdp || !self.peerconnection) {
  12343. success_callback();
  12344. return;
  12345. }
  12346. self.switchstreams = true;
  12347. self.modifySourcesQueue.push(function() {
  12348. console.log('modify sources done');
  12349. success_callback();
  12350. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12351. console.log("SDPs", oldSdp, newSdp);
  12352. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12353. });
  12354. };
  12355. /**
  12356. * Figures out added/removed ssrcs and send update IQs.
  12357. * @param old_sdp SDP object for old description.
  12358. * @param new_sdp SDP object for new description.
  12359. */
  12360. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12361. if (!(this.peerconnection.signalingState == 'stable' &&
  12362. this.peerconnection.iceConnectionState == 'connected')){
  12363. console.log("Too early to send updates");
  12364. return;
  12365. }
  12366. // send source-remove IQ.
  12367. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12368. var remove = $iq({to: this.peerjid, type: 'set'})
  12369. .c('jingle', {
  12370. xmlns: 'urn:xmpp:jingle:1',
  12371. action: 'source-remove',
  12372. initiator: this.initiator,
  12373. sid: this.sid
  12374. }
  12375. );
  12376. var removed = sdpDiffer.toJingle(remove);
  12377. if (removed) {
  12378. this.connection.sendIQ(remove,
  12379. function (res) {
  12380. console.info('got remove result', res);
  12381. },
  12382. function (err) {
  12383. console.error('got remove error', err);
  12384. }
  12385. );
  12386. } else {
  12387. console.log('removal not necessary');
  12388. }
  12389. // send source-add IQ.
  12390. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12391. var add = $iq({to: this.peerjid, type: 'set'})
  12392. .c('jingle', {
  12393. xmlns: 'urn:xmpp:jingle:1',
  12394. action: 'source-add',
  12395. initiator: this.initiator,
  12396. sid: this.sid
  12397. }
  12398. );
  12399. var added = sdpDiffer.toJingle(add, this.getVideoType());
  12400. if (added) {
  12401. this.connection.sendIQ(add,
  12402. function (res) {
  12403. console.info('got add result', res);
  12404. },
  12405. function (err) {
  12406. console.error('got add error', err);
  12407. }
  12408. );
  12409. } else {
  12410. console.log('addition not necessary');
  12411. }
  12412. };
  12413. /**
  12414. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12415. *
  12416. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12417. * tracks; otherwise, <tt>false</tt>
  12418. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12419. * tracks have been enabled/disabled. The function may, optionally, return
  12420. * another function which is to be invoked after the whole mute/unmute operation
  12421. * has completed successfully.
  12422. * @param options an object which specifies optional arguments such as the
  12423. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12424. * specifies whether the method was initiated in response to a user command (in
  12425. * contrast to an automatic decision made by the application logic)
  12426. */
  12427. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12428. var byUser;
  12429. if (options) {
  12430. byUser = options.byUser;
  12431. if (typeof byUser === 'undefined') {
  12432. byUser = true;
  12433. }
  12434. } else {
  12435. byUser = true;
  12436. }
  12437. // The user's command to mute the (local) video takes precedence over any
  12438. // automatic decision made by the application logic.
  12439. if (byUser) {
  12440. this.videoMuteByUser = mute;
  12441. } else if (this.videoMuteByUser) {
  12442. return;
  12443. }
  12444. this.hardMuteVideo(mute);
  12445. var self = this;
  12446. var oldSdp = null;
  12447. if(self.peerconnection) {
  12448. if(self.peerconnection.localDescription) {
  12449. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12450. }
  12451. }
  12452. this.modifySourcesQueue.push(function() {
  12453. console.log('modify sources done');
  12454. callback(mute);
  12455. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12456. console.log("SDPs", oldSdp, newSdp);
  12457. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12458. });
  12459. };
  12460. JingleSession.prototype.hardMuteVideo = function (muted) {
  12461. this.pendingop = muted ? 'mute' : 'unmute';
  12462. };
  12463. JingleSession.prototype.sendMute = function (muted, content) {
  12464. var info = $iq({to: this.peerjid,
  12465. type: 'set'})
  12466. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12467. action: 'session-info',
  12468. initiator: this.initiator,
  12469. sid: this.sid });
  12470. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12471. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12472. if (content) {
  12473. info.attrs({'name': content});
  12474. }
  12475. this.connection.send(info);
  12476. };
  12477. JingleSession.prototype.sendRinging = function () {
  12478. var info = $iq({to: this.peerjid,
  12479. type: 'set'})
  12480. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12481. action: 'session-info',
  12482. initiator: this.initiator,
  12483. sid: this.sid });
  12484. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12485. this.connection.send(info);
  12486. };
  12487. JingleSession.prototype.getStats = function (interval) {
  12488. var self = this;
  12489. var recv = {audio: 0, video: 0};
  12490. var lost = {audio: 0, video: 0};
  12491. var lastrecv = {audio: 0, video: 0};
  12492. var lastlost = {audio: 0, video: 0};
  12493. var loss = {audio: 0, video: 0};
  12494. var delta = {audio: 0, video: 0};
  12495. this.statsinterval = window.setInterval(function () {
  12496. if (self && self.peerconnection && self.peerconnection.getStats) {
  12497. self.peerconnection.getStats(function (stats) {
  12498. var results = stats.result();
  12499. // TODO: there are so much statistics you can get from this..
  12500. for (var i = 0; i < results.length; ++i) {
  12501. if (results[i].type == 'ssrc') {
  12502. var packetsrecv = results[i].stat('packetsReceived');
  12503. var packetslost = results[i].stat('packetsLost');
  12504. if (packetsrecv && packetslost) {
  12505. packetsrecv = parseInt(packetsrecv, 10);
  12506. packetslost = parseInt(packetslost, 10);
  12507. if (results[i].stat('googFrameRateReceived')) {
  12508. lastlost.video = lost.video;
  12509. lastrecv.video = recv.video;
  12510. recv.video = packetsrecv;
  12511. lost.video = packetslost;
  12512. } else {
  12513. lastlost.audio = lost.audio;
  12514. lastrecv.audio = recv.audio;
  12515. recv.audio = packetsrecv;
  12516. lost.audio = packetslost;
  12517. }
  12518. }
  12519. }
  12520. }
  12521. delta.audio = recv.audio - lastrecv.audio;
  12522. delta.video = recv.video - lastrecv.video;
  12523. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12524. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12525. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12526. });
  12527. }
  12528. }, interval || 3000);
  12529. return this.statsinterval;
  12530. };
  12531. JingleSession.onJingleError = function (session, error)
  12532. {
  12533. console.error("Jingle error", error);
  12534. }
  12535. JingleSession.onJingleFatalError = function (session, error)
  12536. {
  12537. this.service.sessionTerminated = true;
  12538. this.connection.emuc.doLeave();
  12539. APP.UI.messageHandler.showError("dialog.sorry",
  12540. "dialog.internalError");
  12541. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12542. }
  12543. JingleSession.prototype.setLocalDescription = function () {
  12544. var self = this;
  12545. var newssrcs = [];
  12546. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12547. session.media.forEach(function (media) {
  12548. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12549. // TODO(gp) maybe exclude FID streams?
  12550. media.ssrcs.forEach(function (ssrc) {
  12551. if (ssrc.attribute !== 'cname') {
  12552. return;
  12553. }
  12554. newssrcs.push({
  12555. 'ssrc': ssrc.id,
  12556. 'type': media.type
  12557. });
  12558. });
  12559. }
  12560. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12561. {
  12562. newssrcs.push({
  12563. 'ssrc': self.localStreamsSSRC[media.type],
  12564. 'type': media.type
  12565. });
  12566. }
  12567. });
  12568. console.log('new ssrcs', newssrcs);
  12569. // Bind us as local SSRCs owner
  12570. if (newssrcs.length > 0) {
  12571. for (var i = 1; i <= newssrcs.length; i ++) {
  12572. var ssrc = newssrcs[i-1].ssrc;
  12573. var myJid = self.connection.emuc.myroomjid;
  12574. self.ssrcOwners[ssrc] = myJid;
  12575. if (newssrcs[i-1].type === 'video'){
  12576. self.ssrcVideoTypes[ssrc] = self.getVideoType();
  12577. }
  12578. }
  12579. }
  12580. }
  12581. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12582. function sendKeyframe(pc) {
  12583. console.log('sendkeyframe', pc.iceConnectionState);
  12584. if (pc.iceConnectionState !== 'connected') return; // safe...
  12585. var self = this;
  12586. pc.setRemoteDescription(
  12587. pc.remoteDescription,
  12588. function () {
  12589. pc.createAnswer(
  12590. function (modifiedAnswer) {
  12591. pc.setLocalDescription(
  12592. modifiedAnswer,
  12593. function () {
  12594. // noop
  12595. },
  12596. function (error) {
  12597. console.log('triggerKeyframe setLocalDescription failed', error);
  12598. APP.UI.messageHandler.showError();
  12599. }
  12600. );
  12601. },
  12602. function (error) {
  12603. console.log('triggerKeyframe createAnswer failed', error);
  12604. APP.UI.messageHandler.showError();
  12605. }
  12606. );
  12607. },
  12608. function (error) {
  12609. console.log('triggerKeyframe setRemoteDescription failed', error);
  12610. APP.UI.messageHandler.showError();
  12611. }
  12612. );
  12613. }
  12614. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12615. var self = this;
  12616. var thessrc;
  12617. var streamId = APP.RTC.getStreamID(data.stream);
  12618. // look up an associated JID for a stream id
  12619. if (!streamId) {
  12620. console.error("No stream ID for", data.stream);
  12621. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12622. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12623. var ssrclines
  12624. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12625. ssrclines = ssrclines.filter(function (line) {
  12626. // NOTE(gp) previously we filtered on the mslabel, but that property
  12627. // is not always present.
  12628. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12629. if (RTCBrowserType.isTemasysPluginUsed()) {
  12630. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12631. } else {
  12632. return ((line.indexOf('msid:' + streamId) !== -1));
  12633. }
  12634. });
  12635. if (ssrclines.length) {
  12636. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12637. if (!self.ssrcOwners[thessrc]) {
  12638. console.error("No SSRC owner known for: " + thessrc);
  12639. return;
  12640. }
  12641. data.peerjid = self.ssrcOwners[thessrc];
  12642. data.videoType = self.ssrcVideoTypes[thessrc]
  12643. console.log('associated jid', self.ssrcOwners[thessrc],
  12644. thessrc, data.videoType);
  12645. } else {
  12646. console.error("No SSRC lines for ", streamId);
  12647. }
  12648. }
  12649. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12650. var isVideo = data.stream.getVideoTracks().length > 0;
  12651. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12652. if (isVideo &&
  12653. data.peerjid && this.peerjid === data.peerjid &&
  12654. data.stream.getVideoTracks().length === 0 &&
  12655. APP.RTC.localVideo.getTracks().length > 0) {
  12656. window.setTimeout(function () {
  12657. sendKeyframe(self.peerconnection);
  12658. }, 3000);
  12659. }
  12660. }
  12661. module.exports = JingleSession;
  12662. },{"../../service/xmpp/XMPPEvents":108,"../RTC/RTCBrowserType":8,"./SDP":54,"./SDPDiffer":55,"./SDPUtil":56,"./TraceablePeerConnection":57,"async":67,"sdp-transform":95}],54:[function(require,module,exports){
  12663. /* jshint -W117 */
  12664. var SDPUtil = require("./SDPUtil");
  12665. // SDP STUFF
  12666. function SDP(sdp) {
  12667. this.media = sdp.split('\r\nm=');
  12668. for (var i = 1; i < this.media.length; i++) {
  12669. this.media[i] = 'm=' + this.media[i];
  12670. if (i != this.media.length - 1) {
  12671. this.media[i] += '\r\n';
  12672. }
  12673. }
  12674. this.session = this.media.shift() + '\r\n';
  12675. this.raw = this.session + this.media.join('');
  12676. }
  12677. /**
  12678. * Returns map of MediaChannel mapped per channel idx.
  12679. */
  12680. SDP.prototype.getMediaSsrcMap = function() {
  12681. var self = this;
  12682. var media_ssrcs = {};
  12683. var tmp;
  12684. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12685. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12686. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12687. var media = {
  12688. mediaindex: mediaindex,
  12689. mid: mid,
  12690. ssrcs: {},
  12691. ssrcGroups: []
  12692. };
  12693. media_ssrcs[mediaindex] = media;
  12694. tmp.forEach(function (line) {
  12695. var linessrc = line.substring(7).split(' ')[0];
  12696. // allocate new ChannelSsrc
  12697. if(!media.ssrcs[linessrc]) {
  12698. media.ssrcs[linessrc] = {
  12699. ssrc: linessrc,
  12700. lines: []
  12701. };
  12702. }
  12703. media.ssrcs[linessrc].lines.push(line);
  12704. });
  12705. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12706. tmp.forEach(function(line){
  12707. var semantics = line.substr(0, idx).substr(13);
  12708. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12709. if (ssrcs.length != 0) {
  12710. media.ssrcGroups.push({
  12711. semantics: semantics,
  12712. ssrcs: ssrcs
  12713. });
  12714. }
  12715. });
  12716. }
  12717. return media_ssrcs;
  12718. };
  12719. /**
  12720. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12721. * @param ssrc the ssrc to check.
  12722. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12723. */
  12724. SDP.prototype.containsSSRC = function(ssrc) {
  12725. var medias = this.getMediaSsrcMap();
  12726. var contains = false;
  12727. Object.keys(medias).forEach(function(mediaindex){
  12728. var media = medias[mediaindex];
  12729. //console.log("Check", channel, ssrc);
  12730. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12731. contains = true;
  12732. }
  12733. });
  12734. return contains;
  12735. };
  12736. // remove iSAC and CN from SDP
  12737. SDP.prototype.mangle = function () {
  12738. var i, j, mline, lines, rtpmap, newdesc;
  12739. for (i = 0; i < this.media.length; i++) {
  12740. lines = this.media[i].split('\r\n');
  12741. lines.pop(); // remove empty last element
  12742. mline = SDPUtil.parse_mline(lines.shift());
  12743. if (mline.media != 'audio')
  12744. continue;
  12745. newdesc = '';
  12746. mline.fmt.length = 0;
  12747. for (j = 0; j < lines.length; j++) {
  12748. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12749. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12750. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12751. continue;
  12752. mline.fmt.push(rtpmap.id);
  12753. newdesc += lines[j] + '\r\n';
  12754. } else {
  12755. newdesc += lines[j] + '\r\n';
  12756. }
  12757. }
  12758. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12759. this.media[i] += newdesc;
  12760. }
  12761. this.raw = this.session + this.media.join('');
  12762. };
  12763. // remove lines matching prefix from session section
  12764. SDP.prototype.removeSessionLines = function(prefix) {
  12765. var self = this;
  12766. var lines = SDPUtil.find_lines(this.session, prefix);
  12767. lines.forEach(function(line) {
  12768. self.session = self.session.replace(line + '\r\n', '');
  12769. });
  12770. this.raw = this.session + this.media.join('');
  12771. return lines;
  12772. }
  12773. // remove lines matching prefix from a media section specified by mediaindex
  12774. // TODO: non-numeric mediaindex could match mid
  12775. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12776. var self = this;
  12777. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12778. lines.forEach(function(line) {
  12779. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12780. });
  12781. this.raw = this.session + this.media.join('');
  12782. return lines;
  12783. }
  12784. // add content's to a jingle element
  12785. SDP.prototype.toJingle = function (elem, thecreator, ssrcs, videoType) {
  12786. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12787. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12788. var self = this;
  12789. // new bundle plan
  12790. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12791. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12792. for (i = 0; i < lines.length; i++) {
  12793. tmp = lines[i].split(' ');
  12794. var semantics = tmp.shift().substr(8);
  12795. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12796. for (j = 0; j < tmp.length; j++) {
  12797. elem.c('content', {name: tmp[j]}).up();
  12798. }
  12799. elem.up();
  12800. }
  12801. }
  12802. for (i = 0; i < this.media.length; i++) {
  12803. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12804. if (!(mline.media === 'audio' ||
  12805. mline.media === 'video' ||
  12806. mline.media === 'application'))
  12807. {
  12808. continue;
  12809. }
  12810. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12811. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12812. } else {
  12813. if(ssrcs && ssrcs[mline.media])
  12814. {
  12815. ssrc = ssrcs[mline.media];
  12816. }
  12817. else
  12818. ssrc = false;
  12819. }
  12820. elem.c('content', {creator: thecreator, name: mline.media});
  12821. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12822. // prefer identifier from a=mid if present
  12823. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12824. elem.attrs({ name: mid });
  12825. }
  12826. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12827. {
  12828. elem.c('description',
  12829. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12830. media: mline.media });
  12831. if (ssrc) {
  12832. elem.attrs({ssrc: ssrc});
  12833. }
  12834. for (j = 0; j < mline.fmt.length; j++) {
  12835. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12836. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12837. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12838. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12839. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12840. for (k = 0; k < tmp.length; k++) {
  12841. elem.c('parameter', tmp[k]).up();
  12842. }
  12843. }
  12844. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12845. elem.up();
  12846. }
  12847. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12848. elem.c('encryption', {required: 1});
  12849. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12850. crypto.forEach(function(line) {
  12851. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12852. });
  12853. elem.up(); // end of encryption
  12854. }
  12855. if (ssrc) {
  12856. // new style mapping
  12857. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12858. // FIXME: group by ssrc and support multiple different ssrcs
  12859. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12860. if(ssrclines.length > 0) {
  12861. ssrclines.forEach(function (line) {
  12862. idx = line.indexOf(' ');
  12863. var linessrc = line.substr(0, idx).substr(7);
  12864. if (linessrc != ssrc) {
  12865. elem.up();
  12866. ssrc = linessrc;
  12867. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12868. }
  12869. var kv = line.substr(idx + 1);
  12870. elem.c('parameter');
  12871. if (kv.indexOf(':') == -1) {
  12872. elem.attrs({ name: kv });
  12873. } else {
  12874. var k = kv.split(':', 2)[0];
  12875. elem.attrs({ name: k });
  12876. var v = kv.split(':', 2)[1];
  12877. v = SDPUtil.filter_special_chars(v);
  12878. elem.attrs({ value: v });
  12879. }
  12880. elem.up();
  12881. });
  12882. }
  12883. else
  12884. {
  12885. elem.up();
  12886. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12887. elem.c('parameter');
  12888. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12889. elem.up();
  12890. var msid = null;
  12891. if(mline.media == "audio")
  12892. {
  12893. msid = APP.RTC.localAudio.getId();
  12894. }
  12895. else
  12896. {
  12897. msid = APP.RTC.localVideo.getId();
  12898. }
  12899. if(msid != null)
  12900. {
  12901. msid = SDPUtil.filter_special_chars(msid);
  12902. elem.c('parameter');
  12903. elem.attrs({name: "msid", value:msid});
  12904. elem.up();
  12905. elem.c('parameter');
  12906. elem.attrs({name: "mslabel", value:msid});
  12907. elem.up();
  12908. elem.c('parameter');
  12909. elem.attrs({name: "label", value:msid});
  12910. elem.up();
  12911. }
  12912. }
  12913. // Video type
  12914. if (videoType && mline.media == "video") {
  12915. elem.c('ssrc-info',
  12916. {
  12917. xmlns: 'http://jitsi.org/jitmeet',
  12918. 'video-type': videoType
  12919. }).up();
  12920. }
  12921. elem.up();
  12922. // XEP-0339 handle ssrc-group attributes
  12923. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12924. ssrc_group_lines.forEach(function(line) {
  12925. idx = line.indexOf(' ');
  12926. var semantics = line.substr(0, idx).substr(13);
  12927. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12928. if (ssrcs.length != 0) {
  12929. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12930. ssrcs.forEach(function(ssrc) {
  12931. elem.c('source', { ssrc: ssrc })
  12932. .up();
  12933. });
  12934. elem.up();
  12935. }
  12936. });
  12937. }
  12938. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12939. elem.c('rtcp-mux').up();
  12940. }
  12941. // XEP-0293 -- map a=rtcp-fb:*
  12942. this.RtcpFbToJingle(i, elem, '*');
  12943. // XEP-0294
  12944. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12945. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12946. for (j = 0; j < lines.length; j++) {
  12947. tmp = SDPUtil.parse_extmap(lines[j]);
  12948. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12949. uri: tmp.uri,
  12950. id: tmp.value });
  12951. if (tmp.hasOwnProperty('direction')) {
  12952. switch (tmp.direction) {
  12953. case 'sendonly':
  12954. elem.attrs({senders: 'responder'});
  12955. break;
  12956. case 'recvonly':
  12957. elem.attrs({senders: 'initiator'});
  12958. break;
  12959. case 'sendrecv':
  12960. elem.attrs({senders: 'both'});
  12961. break;
  12962. case 'inactive':
  12963. elem.attrs({senders: 'none'});
  12964. break;
  12965. }
  12966. }
  12967. // TODO: handle params
  12968. elem.up();
  12969. }
  12970. }
  12971. elem.up(); // end of description
  12972. }
  12973. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12974. this.TransportToJingle(i, elem);
  12975. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12976. elem.attrs({senders: 'both'});
  12977. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12978. elem.attrs({senders: 'initiator'});
  12979. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12980. elem.attrs({senders: 'responder'});
  12981. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12982. elem.attrs({senders: 'none'});
  12983. }
  12984. if (mline.port == '0') {
  12985. // estos hack to reject an m-line
  12986. elem.attrs({senders: 'rejected'});
  12987. }
  12988. elem.up(); // end of content
  12989. }
  12990. elem.up();
  12991. return elem;
  12992. };
  12993. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12994. var i = mediaindex;
  12995. var tmp;
  12996. var self = this;
  12997. elem.c('transport');
  12998. // XEP-0343 DTLS/SCTP
  12999. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13000. {
  13001. var sctpmap = SDPUtil.find_line(
  13002. this.media[i], 'a=sctpmap:', self.session);
  13003. if (sctpmap)
  13004. {
  13005. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13006. elem.c('sctpmap',
  13007. {
  13008. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13009. number: sctpAttrs[0], /* SCTP port */
  13010. protocol: sctpAttrs[1], /* protocol */
  13011. });
  13012. // Optional stream count attribute
  13013. if (sctpAttrs.length > 2)
  13014. elem.attrs({ streams: sctpAttrs[2]});
  13015. elem.up();
  13016. }
  13017. }
  13018. // XEP-0320
  13019. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13020. fingerprints.forEach(function(line) {
  13021. tmp = SDPUtil.parse_fingerprint(line);
  13022. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13023. elem.c('fingerprint').t(tmp.fingerprint);
  13024. delete tmp.fingerprint;
  13025. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13026. if (line) {
  13027. tmp.setup = line.substr(8);
  13028. }
  13029. elem.attrs(tmp);
  13030. elem.up(); // end of fingerprint
  13031. });
  13032. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13033. if (tmp) {
  13034. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13035. elem.attrs(tmp);
  13036. // XEP-0176
  13037. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13038. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13039. lines.forEach(function (line) {
  13040. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13041. });
  13042. }
  13043. }
  13044. elem.up(); // end of transport
  13045. }
  13046. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13047. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13048. lines.forEach(function (line) {
  13049. var tmp = SDPUtil.parse_rtcpfb(line);
  13050. if (tmp.type == 'trr-int') {
  13051. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13052. elem.up();
  13053. } else {
  13054. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13055. if (tmp.params.length > 0) {
  13056. elem.attrs({'subtype': tmp.params[0]});
  13057. }
  13058. elem.up();
  13059. }
  13060. });
  13061. };
  13062. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13063. var media = '';
  13064. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13065. if (tmp.length) {
  13066. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13067. if (tmp.attr('value')) {
  13068. media += tmp.attr('value');
  13069. } else {
  13070. media += '0';
  13071. }
  13072. media += '\r\n';
  13073. }
  13074. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13075. tmp.each(function () {
  13076. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13077. if ($(this).attr('subtype')) {
  13078. media += ' ' + $(this).attr('subtype');
  13079. }
  13080. media += '\r\n';
  13081. });
  13082. return media;
  13083. };
  13084. // construct an SDP from a jingle stanza
  13085. SDP.prototype.fromJingle = function (jingle) {
  13086. var self = this;
  13087. this.raw = 'v=0\r\n' +
  13088. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13089. 's=-\r\n' +
  13090. 't=0 0\r\n';
  13091. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13092. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13093. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13094. var contents = $(group).find('>content').map(function (idx, content) {
  13095. return content.getAttribute('name');
  13096. }).get();
  13097. if (contents.length > 0) {
  13098. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13099. }
  13100. });
  13101. }
  13102. this.session = this.raw;
  13103. jingle.find('>content').each(function () {
  13104. var m = self.jingle2media($(this));
  13105. self.media.push(m);
  13106. });
  13107. // reconstruct msid-semantic -- apparently not necessary
  13108. /*
  13109. var msid = SDPUtil.parse_ssrc(this.raw);
  13110. if (msid.hasOwnProperty('mslabel')) {
  13111. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13112. }
  13113. */
  13114. this.raw = this.session + this.media.join('');
  13115. };
  13116. // translate a jingle content element into an an SDP media part
  13117. SDP.prototype.jingle2media = function (content) {
  13118. var media = '',
  13119. desc = content.find('description'),
  13120. ssrc = desc.attr('ssrc'),
  13121. self = this,
  13122. tmp;
  13123. var sctp = content.find(
  13124. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13125. tmp = { media: desc.attr('media') };
  13126. tmp.port = '1';
  13127. if (content.attr('senders') == 'rejected') {
  13128. // estos hack to reject an m-line.
  13129. tmp.port = '0';
  13130. }
  13131. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13132. if (sctp.length)
  13133. tmp.proto = 'DTLS/SCTP';
  13134. else
  13135. tmp.proto = 'RTP/SAVPF';
  13136. } else {
  13137. tmp.proto = 'RTP/AVPF';
  13138. }
  13139. if (!sctp.length)
  13140. {
  13141. tmp.fmt = desc.find('payload-type').map(
  13142. function () { return this.getAttribute('id'); }).get();
  13143. media += SDPUtil.build_mline(tmp) + '\r\n';
  13144. }
  13145. else
  13146. {
  13147. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13148. media += 'a=sctpmap:' + sctp.attr('number') +
  13149. ' ' + sctp.attr('protocol');
  13150. var streamCount = sctp.attr('streams');
  13151. if (streamCount)
  13152. media += ' ' + streamCount + '\r\n';
  13153. else
  13154. media += '\r\n';
  13155. }
  13156. media += 'c=IN IP4 0.0.0.0\r\n';
  13157. if (!sctp.length)
  13158. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13159. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13160. if (tmp.length) {
  13161. if (tmp.attr('ufrag')) {
  13162. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13163. }
  13164. if (tmp.attr('pwd')) {
  13165. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13166. }
  13167. tmp.find('>fingerprint').each(function () {
  13168. // FIXME: check namespace at some point
  13169. media += 'a=fingerprint:' + this.getAttribute('hash');
  13170. media += ' ' + $(this).text();
  13171. media += '\r\n';
  13172. if (this.getAttribute('setup')) {
  13173. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13174. }
  13175. });
  13176. }
  13177. switch (content.attr('senders')) {
  13178. case 'initiator':
  13179. media += 'a=sendonly\r\n';
  13180. break;
  13181. case 'responder':
  13182. media += 'a=recvonly\r\n';
  13183. break;
  13184. case 'none':
  13185. media += 'a=inactive\r\n';
  13186. break;
  13187. case 'both':
  13188. media += 'a=sendrecv\r\n';
  13189. break;
  13190. }
  13191. media += 'a=mid:' + content.attr('name') + '\r\n';
  13192. // <description><rtcp-mux/></description>
  13193. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13194. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13195. if (desc.find('rtcp-mux').length) {
  13196. media += 'a=rtcp-mux\r\n';
  13197. }
  13198. if (desc.find('encryption').length) {
  13199. desc.find('encryption>crypto').each(function () {
  13200. media += 'a=crypto:' + this.getAttribute('tag');
  13201. media += ' ' + this.getAttribute('crypto-suite');
  13202. media += ' ' + this.getAttribute('key-params');
  13203. if (this.getAttribute('session-params')) {
  13204. media += ' ' + this.getAttribute('session-params');
  13205. }
  13206. media += '\r\n';
  13207. });
  13208. }
  13209. desc.find('payload-type').each(function () {
  13210. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13211. if ($(this).find('>parameter').length) {
  13212. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13213. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13214. media += '\r\n';
  13215. }
  13216. // xep-0293
  13217. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13218. });
  13219. // xep-0293
  13220. media += self.RtcpFbFromJingle(desc, '*');
  13221. // xep-0294
  13222. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13223. tmp.each(function () {
  13224. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13225. });
  13226. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13227. media += SDPUtil.candidateFromJingle(this);
  13228. });
  13229. // XEP-0339 handle ssrc-group attributes
  13230. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13231. var semantics = this.getAttribute('semantics');
  13232. var ssrcs = $(this).find('>source').map(function() {
  13233. return this.getAttribute('ssrc');
  13234. }).get();
  13235. if (ssrcs.length != 0) {
  13236. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13237. }
  13238. });
  13239. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13240. tmp.each(function () {
  13241. var ssrc = this.getAttribute('ssrc');
  13242. $(this).find('>parameter').each(function () {
  13243. var name = this.getAttribute('name');
  13244. var value = this.getAttribute('value');
  13245. value = SDPUtil.filter_special_chars(value);
  13246. media += 'a=ssrc:' + ssrc + ' ' + name;
  13247. if (value && value.length)
  13248. media += ':' + value;
  13249. media += '\r\n';
  13250. });
  13251. });
  13252. return media;
  13253. };
  13254. module.exports = SDP;
  13255. },{"./SDPUtil":56}],55:[function(require,module,exports){
  13256. var SDPUtil = require("./SDPUtil");
  13257. function SDPDiffer(mySDP, otherSDP) {
  13258. this.mySDP = mySDP;
  13259. this.otherSDP = otherSDP;
  13260. }
  13261. /**
  13262. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13263. * @param otherSdp the other SDP to check ssrc with.
  13264. */
  13265. SDPDiffer.prototype.getNewMedia = function() {
  13266. // this could be useful in Array.prototype.
  13267. function arrayEquals(array) {
  13268. // if the other array is a falsy value, return
  13269. if (!array)
  13270. return false;
  13271. // compare lengths - can save a lot of time
  13272. if (this.length != array.length)
  13273. return false;
  13274. for (var i = 0, l=this.length; i < l; i++) {
  13275. // Check if we have nested arrays
  13276. if (this[i] instanceof Array && array[i] instanceof Array) {
  13277. // recurse into the nested arrays
  13278. if (!this[i].equals(array[i]))
  13279. return false;
  13280. }
  13281. else if (this[i] != array[i]) {
  13282. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13283. return false;
  13284. }
  13285. }
  13286. return true;
  13287. }
  13288. var myMedias = this.mySDP.getMediaSsrcMap();
  13289. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13290. var newMedia = {};
  13291. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13292. var myMedia = myMedias[othersMediaIdx];
  13293. var othersMedia = othersMedias[othersMediaIdx];
  13294. if(!myMedia && othersMedia) {
  13295. // Add whole channel
  13296. newMedia[othersMediaIdx] = othersMedia;
  13297. return;
  13298. }
  13299. // Look for new ssrcs accross the channel
  13300. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13301. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13302. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13303. if(!newMedia[othersMediaIdx]){
  13304. newMedia[othersMediaIdx] = {
  13305. mediaindex: othersMedia.mediaindex,
  13306. mid: othersMedia.mid,
  13307. ssrcs: {},
  13308. ssrcGroups: []
  13309. };
  13310. }
  13311. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13312. }
  13313. });
  13314. // Look for new ssrc groups across the channels
  13315. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13316. // try to match the other ssrc-group with an ssrc-group of ours
  13317. var matched = false;
  13318. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13319. var mySsrcGroup = myMedia.ssrcGroups[i];
  13320. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13321. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13322. matched = true;
  13323. break;
  13324. }
  13325. }
  13326. if (!matched) {
  13327. // Allocate channel if we've found an ssrc-group that doesn't
  13328. // exist in our channel
  13329. if(!newMedia[othersMediaIdx]){
  13330. newMedia[othersMediaIdx] = {
  13331. mediaindex: othersMedia.mediaindex,
  13332. mid: othersMedia.mid,
  13333. ssrcs: {},
  13334. ssrcGroups: []
  13335. };
  13336. }
  13337. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13338. }
  13339. });
  13340. });
  13341. return newMedia;
  13342. };
  13343. /**
  13344. * Sends SSRC update IQ.
  13345. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13346. * @param sid session identifier that will be put into the IQ.
  13347. * @param initiator initiator identifier.
  13348. * @param toJid destination Jid
  13349. * @param isAdd indicates if this is remove or add operation.
  13350. */
  13351. SDPDiffer.prototype.toJingle = function(modify, videoType) {
  13352. var sdpMediaSsrcs = this.getNewMedia();
  13353. var self = this;
  13354. // FIXME: only announce video ssrcs since we mix audio and dont need
  13355. // the audio ssrcs therefore
  13356. var modified = false;
  13357. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13358. modified = true;
  13359. var media = sdpMediaSsrcs[mediaindex];
  13360. modify.c('content', {name: media.mid});
  13361. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13362. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13363. // generate sources from lines
  13364. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13365. var mediaSsrc = media.ssrcs[ssrcNum];
  13366. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13367. modify.attrs({ssrc: mediaSsrc.ssrc});
  13368. // iterate over ssrc lines
  13369. mediaSsrc.lines.forEach(function (line) {
  13370. var idx = line.indexOf(' ');
  13371. var kv = line.substr(idx + 1);
  13372. modify.c('parameter');
  13373. if (kv.indexOf(':') == -1) {
  13374. modify.attrs({ name: kv });
  13375. } else {
  13376. var nv = kv.split(':', 2);
  13377. var name = nv[0];
  13378. var value = SDPUtil.filter_special_chars(nv[1]);
  13379. modify.attrs({ name: name });
  13380. modify.attrs({ value: value });
  13381. }
  13382. modify.up(); // end of parameter
  13383. });
  13384. // indicate video type
  13385. if (videoType && media.mid == 'video') {
  13386. modify.c('ssrc-info',
  13387. {
  13388. xmlns: 'http://jitsi.org/jitmeet',
  13389. 'video-type': videoType
  13390. })
  13391. .up();
  13392. }
  13393. modify.up(); // end of source
  13394. });
  13395. // generate source groups from lines
  13396. media.ssrcGroups.forEach(function(ssrcGroup) {
  13397. if (ssrcGroup.ssrcs.length != 0) {
  13398. modify.c('ssrc-group', {
  13399. semantics: ssrcGroup.semantics,
  13400. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13401. });
  13402. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13403. modify.c('source', { ssrc: ssrc })
  13404. .up(); // end of source
  13405. });
  13406. modify.up(); // end of ssrc-group
  13407. }
  13408. });
  13409. modify.up(); // end of description
  13410. modify.up(); // end of content
  13411. });
  13412. return modified;
  13413. };
  13414. module.exports = SDPDiffer;
  13415. },{"./SDPUtil":56}],56:[function(require,module,exports){
  13416. SDPUtil = {
  13417. filter_special_chars: function (text) {
  13418. return text.replace(/[\\\/\{,\}\+]/g, "");
  13419. },
  13420. iceparams: function (mediadesc, sessiondesc) {
  13421. var data = null;
  13422. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13423. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13424. data = {
  13425. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13426. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13427. };
  13428. }
  13429. return data;
  13430. },
  13431. parse_iceufrag: function (line) {
  13432. return line.substring(12);
  13433. },
  13434. build_iceufrag: function (frag) {
  13435. return 'a=ice-ufrag:' + frag;
  13436. },
  13437. parse_icepwd: function (line) {
  13438. return line.substring(10);
  13439. },
  13440. build_icepwd: function (pwd) {
  13441. return 'a=ice-pwd:' + pwd;
  13442. },
  13443. parse_mid: function (line) {
  13444. return line.substring(6);
  13445. },
  13446. parse_mline: function (line) {
  13447. var parts = line.substring(2).split(' '),
  13448. data = {};
  13449. data.media = parts.shift();
  13450. data.port = parts.shift();
  13451. data.proto = parts.shift();
  13452. if (parts[parts.length - 1] === '') { // trailing whitespace
  13453. parts.pop();
  13454. }
  13455. data.fmt = parts;
  13456. return data;
  13457. },
  13458. build_mline: function (mline) {
  13459. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13460. },
  13461. parse_rtpmap: function (line) {
  13462. var parts = line.substring(9).split(' '),
  13463. data = {};
  13464. data.id = parts.shift();
  13465. parts = parts[0].split('/');
  13466. data.name = parts.shift();
  13467. data.clockrate = parts.shift();
  13468. data.channels = parts.length ? parts.shift() : '1';
  13469. return data;
  13470. },
  13471. /**
  13472. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13473. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13474. * @returns [SCTP port number, protocol, streams]
  13475. */
  13476. parse_sctpmap: function (line)
  13477. {
  13478. var parts = line.substring(10).split(' ');
  13479. var sctpPort = parts[0];
  13480. var protocol = parts[1];
  13481. // Stream count is optional
  13482. var streamCount = parts.length > 2 ? parts[2] : null;
  13483. return [sctpPort, protocol, streamCount];// SCTP port
  13484. },
  13485. build_rtpmap: function (el) {
  13486. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13487. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13488. line += '/' + el.getAttribute('channels');
  13489. }
  13490. return line;
  13491. },
  13492. parse_crypto: function (line) {
  13493. var parts = line.substring(9).split(' '),
  13494. data = {};
  13495. data.tag = parts.shift();
  13496. data['crypto-suite'] = parts.shift();
  13497. data['key-params'] = parts.shift();
  13498. if (parts.length) {
  13499. data['session-params'] = parts.join(' ');
  13500. }
  13501. return data;
  13502. },
  13503. parse_fingerprint: function (line) { // RFC 4572
  13504. var parts = line.substring(14).split(' '),
  13505. data = {};
  13506. data.hash = parts.shift();
  13507. data.fingerprint = parts.shift();
  13508. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13509. return data;
  13510. },
  13511. parse_fmtp: function (line) {
  13512. var parts = line.split(' '),
  13513. i, key, value,
  13514. data = [];
  13515. parts.shift();
  13516. parts = parts.join(' ').split(';');
  13517. for (i = 0; i < parts.length; i++) {
  13518. key = parts[i].split('=')[0];
  13519. while (key.length && key[0] == ' ') {
  13520. key = key.substring(1);
  13521. }
  13522. value = parts[i].split('=')[1];
  13523. if (key && value) {
  13524. data.push({name: key, value: value});
  13525. } else if (key) {
  13526. // rfc 4733 (DTMF) style stuff
  13527. data.push({name: '', value: key});
  13528. }
  13529. }
  13530. return data;
  13531. },
  13532. parse_icecandidate: function (line) {
  13533. var candidate = {},
  13534. elems = line.split(' ');
  13535. candidate.foundation = elems[0].substring(12);
  13536. candidate.component = elems[1];
  13537. candidate.protocol = elems[2].toLowerCase();
  13538. candidate.priority = elems[3];
  13539. candidate.ip = elems[4];
  13540. candidate.port = elems[5];
  13541. // elems[6] => "typ"
  13542. candidate.type = elems[7];
  13543. candidate.generation = 0; // default value, may be overwritten below
  13544. for (var i = 8; i < elems.length; i += 2) {
  13545. switch (elems[i]) {
  13546. case 'raddr':
  13547. candidate['rel-addr'] = elems[i + 1];
  13548. break;
  13549. case 'rport':
  13550. candidate['rel-port'] = elems[i + 1];
  13551. break;
  13552. case 'generation':
  13553. candidate.generation = elems[i + 1];
  13554. break;
  13555. case 'tcptype':
  13556. candidate.tcptype = elems[i + 1];
  13557. break;
  13558. default: // TODO
  13559. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13560. }
  13561. }
  13562. candidate.network = '1';
  13563. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13564. return candidate;
  13565. },
  13566. build_icecandidate: function (cand) {
  13567. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13568. line += ' ';
  13569. switch (cand.type) {
  13570. case 'srflx':
  13571. case 'prflx':
  13572. case 'relay':
  13573. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13574. line += 'raddr';
  13575. line += ' ';
  13576. line += cand['rel-addr'];
  13577. line += ' ';
  13578. line += 'rport';
  13579. line += ' ';
  13580. line += cand['rel-port'];
  13581. line += ' ';
  13582. }
  13583. break;
  13584. }
  13585. if (cand.hasOwnAttribute('tcptype')) {
  13586. line += 'tcptype';
  13587. line += ' ';
  13588. line += cand.tcptype;
  13589. line += ' ';
  13590. }
  13591. line += 'generation';
  13592. line += ' ';
  13593. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13594. return line;
  13595. },
  13596. parse_ssrc: function (desc) {
  13597. // proprietary mapping of a=ssrc lines
  13598. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13599. // and parse according to that
  13600. var lines = desc.split('\r\n'),
  13601. data = {};
  13602. for (var i = 0; i < lines.length; i++) {
  13603. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13604. var idx = lines[i].indexOf(' ');
  13605. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13606. }
  13607. }
  13608. return data;
  13609. },
  13610. parse_rtcpfb: function (line) {
  13611. var parts = line.substr(10).split(' ');
  13612. var data = {};
  13613. data.pt = parts.shift();
  13614. data.type = parts.shift();
  13615. data.params = parts;
  13616. return data;
  13617. },
  13618. parse_extmap: function (line) {
  13619. var parts = line.substr(9).split(' ');
  13620. var data = {};
  13621. data.value = parts.shift();
  13622. if (data.value.indexOf('/') != -1) {
  13623. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13624. data.value = data.value.substr(0, data.value.indexOf('/'));
  13625. } else {
  13626. data.direction = 'both';
  13627. }
  13628. data.uri = parts.shift();
  13629. data.params = parts;
  13630. return data;
  13631. },
  13632. find_line: function (haystack, needle, sessionpart) {
  13633. var lines = haystack.split('\r\n');
  13634. for (var i = 0; i < lines.length; i++) {
  13635. if (lines[i].substring(0, needle.length) == needle) {
  13636. return lines[i];
  13637. }
  13638. }
  13639. if (!sessionpart) {
  13640. return false;
  13641. }
  13642. // search session part
  13643. lines = sessionpart.split('\r\n');
  13644. for (var j = 0; j < lines.length; j++) {
  13645. if (lines[j].substring(0, needle.length) == needle) {
  13646. return lines[j];
  13647. }
  13648. }
  13649. return false;
  13650. },
  13651. find_lines: function (haystack, needle, sessionpart) {
  13652. var lines = haystack.split('\r\n'),
  13653. needles = [];
  13654. for (var i = 0; i < lines.length; i++) {
  13655. if (lines[i].substring(0, needle.length) == needle)
  13656. needles.push(lines[i]);
  13657. }
  13658. if (needles.length || !sessionpart) {
  13659. return needles;
  13660. }
  13661. // search session part
  13662. lines = sessionpart.split('\r\n');
  13663. for (var j = 0; j < lines.length; j++) {
  13664. if (lines[j].substring(0, needle.length) == needle) {
  13665. needles.push(lines[j]);
  13666. }
  13667. }
  13668. return needles;
  13669. },
  13670. candidateToJingle: function (line) {
  13671. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13672. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13673. if (line.indexOf('candidate:') === 0) {
  13674. line = 'a=' + line;
  13675. } else if (line.substring(0, 12) != 'a=candidate:') {
  13676. console.log('parseCandidate called with a line that is not a candidate line');
  13677. console.log(line);
  13678. return null;
  13679. }
  13680. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13681. line = line.substring(0, line.length - 2);
  13682. var candidate = {},
  13683. elems = line.split(' '),
  13684. i;
  13685. if (elems[6] != 'typ') {
  13686. console.log('did not find typ in the right place');
  13687. console.log(line);
  13688. return null;
  13689. }
  13690. candidate.foundation = elems[0].substring(12);
  13691. candidate.component = elems[1];
  13692. candidate.protocol = elems[2].toLowerCase();
  13693. candidate.priority = elems[3];
  13694. candidate.ip = elems[4];
  13695. candidate.port = elems[5];
  13696. // elems[6] => "typ"
  13697. candidate.type = elems[7];
  13698. candidate.generation = '0'; // default, may be overwritten below
  13699. for (i = 8; i < elems.length; i += 2) {
  13700. switch (elems[i]) {
  13701. case 'raddr':
  13702. candidate['rel-addr'] = elems[i + 1];
  13703. break;
  13704. case 'rport':
  13705. candidate['rel-port'] = elems[i + 1];
  13706. break;
  13707. case 'generation':
  13708. candidate.generation = elems[i + 1];
  13709. break;
  13710. case 'tcptype':
  13711. candidate.tcptype = elems[i + 1];
  13712. break;
  13713. default: // TODO
  13714. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13715. }
  13716. }
  13717. candidate.network = '1';
  13718. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13719. return candidate;
  13720. },
  13721. candidateFromJingle: function (cand) {
  13722. var line = 'a=candidate:';
  13723. line += cand.getAttribute('foundation');
  13724. line += ' ';
  13725. line += cand.getAttribute('component');
  13726. line += ' ';
  13727. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13728. line += ' ';
  13729. line += cand.getAttribute('priority');
  13730. line += ' ';
  13731. line += cand.getAttribute('ip');
  13732. line += ' ';
  13733. line += cand.getAttribute('port');
  13734. line += ' ';
  13735. line += 'typ';
  13736. line += ' ' + cand.getAttribute('type');
  13737. line += ' ';
  13738. switch (cand.getAttribute('type')) {
  13739. case 'srflx':
  13740. case 'prflx':
  13741. case 'relay':
  13742. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13743. line += 'raddr';
  13744. line += ' ';
  13745. line += cand.getAttribute('rel-addr');
  13746. line += ' ';
  13747. line += 'rport';
  13748. line += ' ';
  13749. line += cand.getAttribute('rel-port');
  13750. line += ' ';
  13751. }
  13752. break;
  13753. }
  13754. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13755. line += 'tcptype';
  13756. line += ' ';
  13757. line += cand.getAttribute('tcptype');
  13758. line += ' ';
  13759. }
  13760. line += 'generation';
  13761. line += ' ';
  13762. line += cand.getAttribute('generation') || '0';
  13763. return line + '\r\n';
  13764. }
  13765. };
  13766. module.exports = SDPUtil;
  13767. },{}],57:[function(require,module,exports){
  13768. var RTC = require('../RTC/RTC');
  13769. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  13770. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13771. function TraceablePeerConnection(ice_config, constraints, session) {
  13772. var self = this;
  13773. var RTCPeerconnectionType = null;
  13774. if (RTCBrowserType.isFirefox()) {
  13775. RTCPeerconnectionType = mozRTCPeerConnection;
  13776. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  13777. RTCPeerconnectionType = RTCPeerConnection;
  13778. } else {
  13779. RTCPeerconnectionType = webkitRTCPeerConnection;
  13780. }
  13781. this.peerconnection = new RTCPeerconnectionType(ice_config, constraints);
  13782. this.updateLog = [];
  13783. this.stats = {};
  13784. this.statsinterval = null;
  13785. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13786. var Interop = require('sdp-interop').Interop;
  13787. this.interop = new Interop();
  13788. var Simulcast = require('sdp-simulcast');
  13789. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  13790. // override as desired
  13791. this.trace = function (what, info) {
  13792. /*console.warn('WTRACE', what, info);
  13793. if (info && RTCBrowserType.isIExplorer()) {
  13794. if (info.length > 1024) {
  13795. console.warn('WTRACE', what, info.substr(1024));
  13796. }
  13797. if (info.length > 2048) {
  13798. console.warn('WTRACE', what, info.substr(2048));
  13799. }
  13800. }*/
  13801. self.updateLog.push({
  13802. time: new Date(),
  13803. type: what,
  13804. value: info || ""
  13805. });
  13806. };
  13807. this.onicecandidate = null;
  13808. this.peerconnection.onicecandidate = function (event) {
  13809. // FIXME: this causes stack overflow with Temasys Plugin
  13810. if (!RTCBrowserType.isTemasysPluginUsed())
  13811. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13812. if (self.onicecandidate !== null) {
  13813. self.onicecandidate(event);
  13814. }
  13815. };
  13816. this.onaddstream = null;
  13817. this.peerconnection.onaddstream = function (event) {
  13818. self.trace('onaddstream', event.stream.id);
  13819. if (self.onaddstream !== null) {
  13820. self.onaddstream(event);
  13821. }
  13822. };
  13823. this.onremovestream = null;
  13824. this.peerconnection.onremovestream = function (event) {
  13825. self.trace('onremovestream', event.stream.id);
  13826. if (self.onremovestream !== null) {
  13827. self.onremovestream(event);
  13828. }
  13829. };
  13830. this.onsignalingstatechange = null;
  13831. this.peerconnection.onsignalingstatechange = function (event) {
  13832. self.trace('onsignalingstatechange', self.signalingState);
  13833. if (self.onsignalingstatechange !== null) {
  13834. self.onsignalingstatechange(event);
  13835. }
  13836. };
  13837. this.oniceconnectionstatechange = null;
  13838. this.peerconnection.oniceconnectionstatechange = function (event) {
  13839. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13840. if (self.oniceconnectionstatechange !== null) {
  13841. self.oniceconnectionstatechange(event);
  13842. }
  13843. };
  13844. this.onnegotiationneeded = null;
  13845. this.peerconnection.onnegotiationneeded = function (event) {
  13846. self.trace('onnegotiationneeded');
  13847. if (self.onnegotiationneeded !== null) {
  13848. self.onnegotiationneeded(event);
  13849. }
  13850. };
  13851. self.ondatachannel = null;
  13852. this.peerconnection.ondatachannel = function (event) {
  13853. self.trace('ondatachannel', event);
  13854. if (self.ondatachannel !== null) {
  13855. self.ondatachannel(event);
  13856. }
  13857. };
  13858. // XXX: do all non-firefox browsers which we support also support this?
  13859. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  13860. this.statsinterval = window.setInterval(function() {
  13861. self.peerconnection.getStats(function(stats) {
  13862. var results = stats.result();
  13863. for (var i = 0; i < results.length; ++i) {
  13864. //console.log(results[i].type, results[i].id, results[i].names())
  13865. var now = new Date();
  13866. results[i].names().forEach(function (name) {
  13867. var id = results[i].id + '-' + name;
  13868. if (!self.stats[id]) {
  13869. self.stats[id] = {
  13870. startTime: now,
  13871. endTime: now,
  13872. values: [],
  13873. times: []
  13874. };
  13875. }
  13876. self.stats[id].values.push(results[i].stat(name));
  13877. self.stats[id].times.push(now.getTime());
  13878. if (self.stats[id].values.length > self.maxstats) {
  13879. self.stats[id].values.shift();
  13880. self.stats[id].times.shift();
  13881. }
  13882. self.stats[id].endTime = now;
  13883. });
  13884. }
  13885. });
  13886. }, 1000);
  13887. }
  13888. };
  13889. dumpSDP = function(description) {
  13890. if (typeof description === 'undefined' || description == null) {
  13891. return '';
  13892. }
  13893. return 'type: ' + description.type + '\r\n' + description.sdp;
  13894. };
  13895. /**
  13896. * Takes a SessionDescription object and returns a "normalized" version.
  13897. * Currently it only takes care of ordering the a=ssrc lines.
  13898. */
  13899. normalizePlanB = function(desc) {
  13900. if (typeof desc !== 'object' || desc === null ||
  13901. typeof desc.sdp !== 'string') {
  13902. console.warn('An empty description was passed as an argument.');
  13903. return desc;
  13904. }
  13905. var transform = require('sdp-transform');
  13906. var session = transform.parse(desc.sdp);
  13907. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  13908. Array.isArray(session.media)) {
  13909. session.media.forEach(function (mLine) {
  13910. // Chrome appears to be picky about the order in which a=ssrc lines
  13911. // are listed in an m-line when rtx is enabled (and thus there are
  13912. // a=ssrc-group lines with FID semantics). Specifically if we have
  13913. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  13914. // the "a=ssrc:S1" lines, SRD fails.
  13915. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  13916. // first.
  13917. var firstSsrcs = [];
  13918. var newSsrcLines = [];
  13919. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  13920. mLine.ssrcGroups.forEach(function (group) {
  13921. if (typeof group.semantics !== 'undefined' &&
  13922. group.semantics === 'FID') {
  13923. if (typeof group.ssrcs !== 'undefined') {
  13924. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  13925. }
  13926. }
  13927. });
  13928. }
  13929. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  13930. for (var i = 0; i<mLine.ssrcs.length; i++){
  13931. if (typeof mLine.ssrcs[i] === 'object'
  13932. && typeof mLine.ssrcs[i].id !== 'undefined'
  13933. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  13934. newSsrcLines.push(mLine.ssrcs[i]);
  13935. delete mLine.ssrcs[i];
  13936. }
  13937. }
  13938. for (var i = 0; i<mLine.ssrcs.length; i++){
  13939. if (typeof mLine.ssrcs[i] !== 'undefined') {
  13940. newSsrcLines.push(mLine.ssrcs[i]);
  13941. }
  13942. }
  13943. mLine.ssrcs = newSsrcLines;
  13944. }
  13945. });
  13946. }
  13947. var resStr = transform.write(session);
  13948. return new RTCSessionDescription({
  13949. type: desc.type,
  13950. sdp: resStr
  13951. });
  13952. };
  13953. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  13954. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  13955. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  13956. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  13957. var desc = this.peerconnection.localDescription;
  13958. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  13959. // if we're running on FF, transform to Plan B first.
  13960. if (RTCBrowserType.usesUnifiedPlan()) {
  13961. desc = this.interop.toPlanB(desc);
  13962. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  13963. }
  13964. return desc;
  13965. });
  13966. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13967. var desc = this.peerconnection.remoteDescription;
  13968. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  13969. // if we're running on FF, transform to Plan B first.
  13970. if (RTCBrowserType.usesUnifiedPlan()) {
  13971. desc = this.interop.toPlanB(desc);
  13972. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13973. }
  13974. return desc;
  13975. });
  13976. }
  13977. TraceablePeerConnection.prototype.addStream = function (stream) {
  13978. this.trace('addStream', stream.id);
  13979. try
  13980. {
  13981. this.peerconnection.addStream(stream);
  13982. }
  13983. catch (e)
  13984. {
  13985. console.error(e);
  13986. return;
  13987. }
  13988. };
  13989. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13990. this.trace('removeStream', stream.id);
  13991. if(stopStreams) {
  13992. stream.getAudioTracks().forEach(function (track) {
  13993. // stop() not supported with IE
  13994. if (track.stop) {
  13995. track.stop();
  13996. }
  13997. });
  13998. stream.getVideoTracks().forEach(function (track) {
  13999. // stop() not supported with IE
  14000. if (track.stop) {
  14001. track.stop();
  14002. }
  14003. });
  14004. if (stream.stop) {
  14005. stream.stop();
  14006. }
  14007. }
  14008. try {
  14009. // FF doesn't support this yet.
  14010. if (this.peerconnection.removeStream)
  14011. this.peerconnection.removeStream(stream);
  14012. } catch (e) {
  14013. console.error(e);
  14014. }
  14015. };
  14016. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14017. this.trace('createDataChannel', label, opts);
  14018. return this.peerconnection.createDataChannel(label, opts);
  14019. };
  14020. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  14021. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14022. // if we're running on FF, transform to Plan A first.
  14023. if (RTCBrowserType.usesUnifiedPlan()) {
  14024. description = this.interop.toUnifiedPlan(description);
  14025. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14026. }
  14027. var self = this;
  14028. this.peerconnection.setLocalDescription(description,
  14029. function () {
  14030. self.trace('setLocalDescriptionOnSuccess');
  14031. successCallback();
  14032. },
  14033. function (err) {
  14034. self.trace('setLocalDescriptionOnFailure', err);
  14035. failureCallback(err);
  14036. }
  14037. );
  14038. /*
  14039. if (this.statsinterval === null && this.maxstats > 0) {
  14040. // start gathering stats
  14041. }
  14042. */
  14043. };
  14044. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  14045. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14046. // TODO the focus should squeze or explode the remote simulcast
  14047. description = this.simulcast.mungeRemoteDescription(description);
  14048. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14049. // if we're running on FF, transform to Plan A first.
  14050. if (RTCBrowserType.usesUnifiedPlan()) {
  14051. description = this.interop.toUnifiedPlan(description);
  14052. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14053. }
  14054. if (RTCBrowserType.usesPlanB()) {
  14055. description = normalizePlanB(description);
  14056. }
  14057. var self = this;
  14058. this.peerconnection.setRemoteDescription(description,
  14059. function () {
  14060. self.trace('setRemoteDescriptionOnSuccess');
  14061. successCallback();
  14062. },
  14063. function (err) {
  14064. self.trace('setRemoteDescriptionOnFailure', err);
  14065. failureCallback(err);
  14066. }
  14067. );
  14068. /*
  14069. if (this.statsinterval === null && this.maxstats > 0) {
  14070. // start gathering stats
  14071. }
  14072. */
  14073. };
  14074. TraceablePeerConnection.prototype.close = function () {
  14075. this.trace('stop');
  14076. if (this.statsinterval !== null) {
  14077. window.clearInterval(this.statsinterval);
  14078. this.statsinterval = null;
  14079. }
  14080. this.peerconnection.close();
  14081. };
  14082. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  14083. var self = this;
  14084. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14085. this.peerconnection.createOffer(
  14086. function (offer) {
  14087. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14088. // if we're running on FF, transform to Plan B first.
  14089. // NOTE this is not tested because in meet the focus generates the
  14090. // offer.
  14091. if (RTCBrowserType.usesUnifiedPlan()) {
  14092. offer = self.interop.toPlanB(offer);
  14093. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14094. }
  14095. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14096. offer = self.simulcast.mungeLocalDescription(offer);
  14097. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14098. }
  14099. successCallback(offer);
  14100. },
  14101. function(err) {
  14102. self.trace('createOfferOnFailure', err);
  14103. failureCallback(err);
  14104. },
  14105. constraints
  14106. );
  14107. };
  14108. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  14109. var self = this;
  14110. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14111. this.peerconnection.createAnswer(
  14112. function (answer) {
  14113. self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
  14114. // if we're running on FF, transform to Plan A first.
  14115. if (RTCBrowserType.usesUnifiedPlan()) {
  14116. answer = self.interop.toPlanB(answer);
  14117. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  14118. }
  14119. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14120. answer = self.simulcast.mungeLocalDescription(answer);
  14121. self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
  14122. }
  14123. successCallback(answer);
  14124. },
  14125. function(err) {
  14126. self.trace('createAnswerOnFailure', err);
  14127. failureCallback(err);
  14128. },
  14129. constraints
  14130. );
  14131. };
  14132. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  14133. var self = this;
  14134. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14135. this.peerconnection.addIceCandidate(candidate);
  14136. /* maybe later
  14137. this.peerconnection.addIceCandidate(candidate,
  14138. function () {
  14139. self.trace('addIceCandidateOnSuccess');
  14140. successCallback();
  14141. },
  14142. function (err) {
  14143. self.trace('addIceCandidateOnFailure', err);
  14144. failureCallback(err);
  14145. }
  14146. );
  14147. */
  14148. };
  14149. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14150. // TODO: Is this the correct way to handle Opera, Temasys?
  14151. if (RTCBrowserType.isFirefox()) {
  14152. // ignore for now...
  14153. if(!errback)
  14154. errback = function () {};
  14155. this.peerconnection.getStats(null,callback,errback);
  14156. } else {
  14157. this.peerconnection.getStats(callback);
  14158. }
  14159. };
  14160. module.exports = TraceablePeerConnection;
  14161. },{"../../service/xmpp/XMPPEvents":108,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"sdp-interop":89,"sdp-simulcast":92,"sdp-transform":95}],58:[function(require,module,exports){
  14162. /* global $, $iq, APP, config, connection, UI, messageHandler,
  14163. roomName, sessionTerminated, Strophe, Util */
  14164. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14165. var Settings = require("../settings/Settings");
  14166. var AuthenticationEvents
  14167. = require("../../service/authentication/AuthenticationEvents");
  14168. /**
  14169. * Contains logic responsible for enabling/disabling functionality available
  14170. * only to moderator users.
  14171. */
  14172. var connection = null;
  14173. var focusUserJid;
  14174. function createExpBackoffTimer(step) {
  14175. var count = 1;
  14176. return function (reset) {
  14177. // Reset call
  14178. if (reset) {
  14179. count = 1;
  14180. return;
  14181. }
  14182. // Calculate next timeout
  14183. var timeout = Math.pow(2, count - 1);
  14184. count += 1;
  14185. return timeout * step;
  14186. };
  14187. }
  14188. var getNextTimeout = createExpBackoffTimer(1000);
  14189. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14190. // External authentication stuff
  14191. var externalAuthEnabled = false;
  14192. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14193. // it will be enabled automatically if focus detects the component through
  14194. // service discovery.
  14195. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14196. var eventEmitter = null;
  14197. var Moderator = {
  14198. isModerator: function () {
  14199. return connection && connection.emuc.isModerator();
  14200. },
  14201. isPeerModerator: function (peerJid) {
  14202. return connection &&
  14203. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14204. },
  14205. isExternalAuthEnabled: function () {
  14206. return externalAuthEnabled;
  14207. },
  14208. isSipGatewayEnabled: function () {
  14209. return sipGatewayEnabled;
  14210. },
  14211. setConnection: function (con) {
  14212. connection = con;
  14213. },
  14214. init: function (xmpp, emitter) {
  14215. this.xmppService = xmpp;
  14216. eventEmitter = emitter;
  14217. // Message listener that talks to POPUP window
  14218. function listener(event) {
  14219. if (event.data && event.data.sessionId) {
  14220. if (event.origin !== window.location.origin) {
  14221. console.warn(
  14222. "Ignoring sessionId from different origin: " + event.origin);
  14223. return;
  14224. }
  14225. localStorage.setItem('sessionId', event.data.sessionId);
  14226. // After popup is closed we will authenticate
  14227. }
  14228. }
  14229. // Register
  14230. if (window.addEventListener) {
  14231. window.addEventListener("message", listener, false);
  14232. } else {
  14233. window.attachEvent("onmessage", listener);
  14234. }
  14235. },
  14236. onMucMemberLeft: function (jid) {
  14237. console.info("Someone left is it focus ? " + jid);
  14238. var resource = Strophe.getResourceFromJid(jid);
  14239. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14240. console.info(
  14241. "Focus has left the room - leaving conference");
  14242. //hangUp();
  14243. // We'd rather reload to have everything re-initialized
  14244. // FIXME: show some message before reload
  14245. location.reload();
  14246. }
  14247. },
  14248. setFocusUserJid: function (focusJid) {
  14249. if (!focusUserJid) {
  14250. focusUserJid = focusJid;
  14251. console.info("Focus jid set to: " + focusUserJid);
  14252. }
  14253. },
  14254. getFocusUserJid: function () {
  14255. return focusUserJid;
  14256. },
  14257. getFocusComponent: function () {
  14258. // Get focus component address
  14259. var focusComponent = config.hosts.focus;
  14260. // If not specified use default: 'focus.domain'
  14261. if (!focusComponent) {
  14262. focusComponent = 'focus.' + config.hosts.domain;
  14263. }
  14264. return focusComponent;
  14265. },
  14266. createConferenceIq: function (roomName) {
  14267. // Generate create conference IQ
  14268. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14269. // Session Id used for authentication
  14270. var sessionId = localStorage.getItem('sessionId');
  14271. var machineUID = Settings.getSettings().uid;
  14272. console.info(
  14273. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14274. elem.c('conference', {
  14275. xmlns: 'http://jitsi.org/protocol/focus',
  14276. room: roomName,
  14277. 'machine-uid': machineUID
  14278. });
  14279. if (sessionId) {
  14280. elem.attrs({ 'session-id': sessionId});
  14281. }
  14282. if (config.hosts.bridge !== undefined) {
  14283. elem.c(
  14284. 'property',
  14285. { name: 'bridge', value: config.hosts.bridge})
  14286. .up();
  14287. }
  14288. // Tell the focus we have Jigasi configured
  14289. if (config.hosts.call_control !== undefined) {
  14290. elem.c(
  14291. 'property',
  14292. { name: 'call_control', value: config.hosts.call_control})
  14293. .up();
  14294. }
  14295. if (config.channelLastN !== undefined) {
  14296. elem.c(
  14297. 'property',
  14298. { name: 'channelLastN', value: config.channelLastN})
  14299. .up();
  14300. }
  14301. if (config.adaptiveLastN !== undefined) {
  14302. elem.c(
  14303. 'property',
  14304. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14305. .up();
  14306. }
  14307. if (config.adaptiveSimulcast !== undefined) {
  14308. elem.c(
  14309. 'property',
  14310. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14311. .up();
  14312. }
  14313. if (config.openSctp !== undefined) {
  14314. elem.c(
  14315. 'property',
  14316. { name: 'openSctp', value: config.openSctp})
  14317. .up();
  14318. }
  14319. if(config.startAudioMuted !== undefined)
  14320. {
  14321. elem.c(
  14322. 'property',
  14323. { name: 'startAudioMuted', value: config.startAudioMuted})
  14324. .up();
  14325. }
  14326. if(config.startVideoMuted !== undefined)
  14327. {
  14328. elem.c(
  14329. 'property',
  14330. { name: 'startVideoMuted', value: config.startVideoMuted})
  14331. .up();
  14332. }
  14333. elem.c(
  14334. 'property',
  14335. { name: 'simulcastMode', value: 'rewriting'})
  14336. .up();
  14337. elem.up();
  14338. return elem;
  14339. },
  14340. parseSessionId: function (resultIq) {
  14341. var sessionId = $(resultIq).find('conference').attr('session-id');
  14342. if (sessionId) {
  14343. console.info('Received sessionId: ' + sessionId);
  14344. localStorage.setItem('sessionId', sessionId);
  14345. }
  14346. },
  14347. parseConfigOptions: function (resultIq) {
  14348. Moderator.setFocusUserJid(
  14349. $(resultIq).find('conference').attr('focusjid'));
  14350. var authenticationEnabled
  14351. = $(resultIq).find(
  14352. '>conference>property' +
  14353. '[name=\'authentication\'][value=\'true\']').length > 0;
  14354. console.info("Authentication enabled: " + authenticationEnabled);
  14355. externalAuthEnabled
  14356. = $(resultIq).find(
  14357. '>conference>property' +
  14358. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14359. console.info('External authentication enabled: ' + externalAuthEnabled);
  14360. if (!externalAuthEnabled) {
  14361. // We expect to receive sessionId in 'internal' authentication mode
  14362. Moderator.parseSessionId(resultIq);
  14363. }
  14364. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14365. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14366. authenticationEnabled, authIdentity);
  14367. // Check if focus has auto-detected Jigasi component(this will be also
  14368. // included if we have passed our host from the config)
  14369. if ($(resultIq).find(
  14370. '>conference>property' +
  14371. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14372. sipGatewayEnabled = true;
  14373. }
  14374. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14375. },
  14376. // FIXME: we need to show the fact that we're waiting for the focus
  14377. // to the user(or that focus is not available)
  14378. allocateConferenceFocus: function (roomName, callback) {
  14379. // Try to use focus user JID from the config
  14380. Moderator.setFocusUserJid(config.focusUserJid);
  14381. // Send create conference IQ
  14382. var iq = Moderator.createConferenceIq(roomName);
  14383. var self = this;
  14384. connection.sendIQ(
  14385. iq,
  14386. function (result) {
  14387. // Setup config options
  14388. Moderator.parseConfigOptions(result);
  14389. if ('true' === $(result).find('conference').attr('ready')) {
  14390. // Reset both timers
  14391. getNextTimeout(true);
  14392. getNextErrorTimeout(true);
  14393. // Exec callback
  14394. callback();
  14395. } else {
  14396. var waitMs = getNextTimeout();
  14397. console.info("Waiting for the focus... " + waitMs);
  14398. // Reset error timeout
  14399. getNextErrorTimeout(true);
  14400. window.setTimeout(
  14401. function () {
  14402. Moderator.allocateConferenceFocus(
  14403. roomName, callback);
  14404. }, waitMs);
  14405. }
  14406. },
  14407. function (error) {
  14408. // Invalid session ? remove and try again
  14409. // without session ID to get a new one
  14410. var invalidSession
  14411. = $(error).find('>error>session-invalid').length;
  14412. if (invalidSession) {
  14413. console.info("Session expired! - removing");
  14414. localStorage.removeItem("sessionId");
  14415. }
  14416. if ($(error).find('>error>graceful-shutdown').length) {
  14417. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14418. return;
  14419. }
  14420. // Check for error returned by the reservation system
  14421. var reservationErr = $(error).find('>error>reservation-error');
  14422. if (reservationErr.length) {
  14423. // Trigger error event
  14424. var errorCode = reservationErr.attr('error-code');
  14425. var errorMsg;
  14426. if ($(error).find('>error>text')) {
  14427. errorMsg = $(error).find('>error>text').text();
  14428. }
  14429. eventEmitter.emit(
  14430. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14431. return;
  14432. }
  14433. // Not authorized to create new room
  14434. if ($(error).find('>error>not-authorized').length) {
  14435. console.warn("Unauthorized to start the conference", error);
  14436. var toDomain
  14437. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14438. if (toDomain !== config.hosts.anonymousdomain) {
  14439. // FIXME: "is external" should come either from
  14440. // the focus or config.js
  14441. externalAuthEnabled = true;
  14442. }
  14443. eventEmitter.emit(
  14444. XMPPEvents.AUTHENTICATION_REQUIRED,
  14445. function () {
  14446. Moderator.allocateConferenceFocus(
  14447. roomName, callback);
  14448. });
  14449. return;
  14450. }
  14451. var waitMs = getNextErrorTimeout();
  14452. console.error("Focus error, retry after " + waitMs, error);
  14453. // Show message
  14454. var focusComponent = Moderator.getFocusComponent();
  14455. var retrySec = waitMs / 1000;
  14456. // FIXME: message is duplicated ?
  14457. // Do not show in case of session invalid
  14458. // which means just a retry
  14459. if (!invalidSession) {
  14460. APP.UI.messageHandler.notify(
  14461. null, "notify.focus",
  14462. 'disconnected', "notify.focusFail",
  14463. {component: focusComponent, ms: retrySec});
  14464. }
  14465. // Reset response timeout
  14466. getNextTimeout(true);
  14467. window.setTimeout(
  14468. function () {
  14469. Moderator.allocateConferenceFocus(roomName, callback);
  14470. }, waitMs);
  14471. }
  14472. );
  14473. },
  14474. getLoginUrl: function (roomName, urlCallback) {
  14475. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14476. iq.c('login-url', {
  14477. xmlns: 'http://jitsi.org/protocol/focus',
  14478. room: roomName,
  14479. 'machine-uid': Settings.getSettings().uid
  14480. });
  14481. connection.sendIQ(
  14482. iq,
  14483. function (result) {
  14484. var url = $(result).find('login-url').attr('url');
  14485. url = url = decodeURIComponent(url);
  14486. if (url) {
  14487. console.info("Got auth url: " + url);
  14488. urlCallback(url);
  14489. } else {
  14490. console.error(
  14491. "Failed to get auth url from the focus", result);
  14492. }
  14493. },
  14494. function (error) {
  14495. console.error("Get auth url error", error);
  14496. }
  14497. );
  14498. },
  14499. getPopupLoginUrl: function (roomName, urlCallback) {
  14500. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14501. iq.c('login-url', {
  14502. xmlns: 'http://jitsi.org/protocol/focus',
  14503. room: roomName,
  14504. 'machine-uid': Settings.getSettings().uid,
  14505. popup: true
  14506. });
  14507. connection.sendIQ(
  14508. iq,
  14509. function (result) {
  14510. var url = $(result).find('login-url').attr('url');
  14511. url = url = decodeURIComponent(url);
  14512. if (url) {
  14513. console.info("Got POPUP auth url: " + url);
  14514. urlCallback(url);
  14515. } else {
  14516. console.error(
  14517. "Failed to get POPUP auth url from the focus", result);
  14518. }
  14519. },
  14520. function (error) {
  14521. console.error('Get POPUP auth url error', error);
  14522. }
  14523. );
  14524. },
  14525. logout: function (callback) {
  14526. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14527. var sessionId = localStorage.getItem('sessionId');
  14528. if (!sessionId) {
  14529. callback();
  14530. return;
  14531. }
  14532. iq.c('logout', {
  14533. xmlns: 'http://jitsi.org/protocol/focus',
  14534. 'session-id': sessionId
  14535. });
  14536. connection.sendIQ(
  14537. iq,
  14538. function (result) {
  14539. var logoutUrl = $(result).find('logout').attr('logout-url');
  14540. if (logoutUrl) {
  14541. logoutUrl = decodeURIComponent(logoutUrl);
  14542. }
  14543. console.info("Log out OK, url: " + logoutUrl, result);
  14544. localStorage.removeItem('sessionId');
  14545. callback(logoutUrl);
  14546. },
  14547. function (error) {
  14548. console.error("Logout error", error);
  14549. }
  14550. );
  14551. }
  14552. };
  14553. module.exports = Moderator;
  14554. },{"../../service/authentication/AuthenticationEvents":103,"../../service/xmpp/XMPPEvents":108,"../settings/Settings":47}],59:[function(require,module,exports){
  14555. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  14556. Toolbar, Util */
  14557. var Moderator = require("./moderator");
  14558. var recordingToken = null;
  14559. var recordingEnabled;
  14560. /**
  14561. * Whether to use a jirecon component for recording, or use the videobridge
  14562. * through COLIBRI.
  14563. */
  14564. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14565. /**
  14566. * The ID of the jirecon recording session. Jirecon generates it when we
  14567. * initially start recording, and it needs to be used in subsequent requests
  14568. * to jirecon.
  14569. */
  14570. var jireconRid = null;
  14571. function setRecordingToken(token) {
  14572. recordingToken = token;
  14573. }
  14574. function setRecording(state, token, callback, connection) {
  14575. if (useJirecon){
  14576. setRecordingJirecon(state, token, callback, connection);
  14577. } else {
  14578. setRecordingColibri(state, token, callback, connection);
  14579. }
  14580. }
  14581. function setRecordingJirecon(state, token, callback, connection) {
  14582. if (state == recordingEnabled){
  14583. return;
  14584. }
  14585. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14586. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14587. action: state ? 'start' : 'stop',
  14588. mucjid: connection.emuc.roomjid});
  14589. if (!state){
  14590. iq.attrs({rid: jireconRid});
  14591. }
  14592. console.log('Start recording');
  14593. connection.sendIQ(
  14594. iq,
  14595. function (result) {
  14596. // TODO wait for an IQ with the real status, since this is
  14597. // provisional?
  14598. jireconRid = $(result).find('recording').attr('rid');
  14599. console.log('Recording ' + (state ? 'started' : 'stopped') +
  14600. '(jirecon)' + result);
  14601. recordingEnabled = state;
  14602. if (!state){
  14603. jireconRid = null;
  14604. }
  14605. callback(state);
  14606. },
  14607. function (error) {
  14608. console.log('Failed to start recording, error: ', error);
  14609. callback(recordingEnabled);
  14610. });
  14611. }
  14612. // Sends a COLIBRI message which enables or disables (according to 'state')
  14613. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14614. // with the new recording state, according to the IQ.
  14615. function setRecordingColibri(state, token, callback, connection) {
  14616. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14617. elem.c('conference', {
  14618. xmlns: 'http://jitsi.org/protocol/colibri'
  14619. });
  14620. elem.c('recording', {state: state, token: token});
  14621. connection.sendIQ(elem,
  14622. function (result) {
  14623. console.log('Set recording "', state, '". Result:', result);
  14624. var recordingElem = $(result).find('>conference>recording');
  14625. var newState = ('true' === recordingElem.attr('state'));
  14626. recordingEnabled = newState;
  14627. callback(newState);
  14628. },
  14629. function (error) {
  14630. console.warn(error);
  14631. callback(recordingEnabled);
  14632. }
  14633. );
  14634. }
  14635. var Recording = {
  14636. toggleRecording: function (tokenEmptyCallback,
  14637. startingCallback, startedCallback, connection) {
  14638. if (!Moderator.isModerator()) {
  14639. console.log(
  14640. 'non-focus, or conference not yet organized:' +
  14641. ' not enabling recording');
  14642. return;
  14643. }
  14644. var self = this;
  14645. // Jirecon does not (currently) support a token.
  14646. if (!recordingToken && !useJirecon) {
  14647. tokenEmptyCallback(function (value) {
  14648. setRecordingToken(value);
  14649. self.toggleRecording(tokenEmptyCallback,
  14650. startingCallback, startedCallback, connection);
  14651. });
  14652. return;
  14653. }
  14654. var oldState = recordingEnabled;
  14655. startingCallback(!oldState);
  14656. setRecording(!oldState,
  14657. recordingToken,
  14658. function (state) {
  14659. console.log("New recording state: ", state);
  14660. if (state === oldState) {
  14661. // FIXME: new focus:
  14662. // this will not work when moderator changes
  14663. // during active session. Then it will assume that
  14664. // recording status has changed to true, but it might have
  14665. // been already true(and we only received actual status from
  14666. // the focus).
  14667. //
  14668. // SO we start with status null, so that it is initialized
  14669. // here and will fail only after second click, so if invalid
  14670. // token was used we have to press the button twice before
  14671. // current status will be fetched and token will be reset.
  14672. //
  14673. // Reliable way would be to return authentication error.
  14674. // Or status update when moderator connects.
  14675. // Or we have to stop recording session when current
  14676. // moderator leaves the room.
  14677. // Failed to change, reset the token because it might
  14678. // have been wrong
  14679. setRecordingToken(null);
  14680. }
  14681. startedCallback(state);
  14682. },
  14683. connection
  14684. );
  14685. }
  14686. }
  14687. module.exports = Recording;
  14688. },{"./moderator":58}],60:[function(require,module,exports){
  14689. /* jshint -W117 */
  14690. /* a simple MUC connection plugin
  14691. * can only handle a single MUC room
  14692. */
  14693. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14694. var Moderator = require("./moderator");
  14695. var JingleSession = require("./JingleSession");
  14696. var bridgeIsDown = false;
  14697. module.exports = function(XMPP, eventEmitter) {
  14698. Strophe.addConnectionPlugin('emuc', {
  14699. connection: null,
  14700. roomjid: null,
  14701. myroomjid: null,
  14702. members: {},
  14703. list_members: [], // so we can elect a new focus
  14704. presMap: {},
  14705. preziMap: {},
  14706. joined: false,
  14707. isOwner: false,
  14708. role: null,
  14709. focusMucJid: null,
  14710. init: function (conn) {
  14711. this.connection = conn;
  14712. },
  14713. initPresenceMap: function (myroomjid) {
  14714. this.presMap['to'] = myroomjid;
  14715. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14716. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted())
  14717. {
  14718. this.addAudioInfoToPresence(true);
  14719. }
  14720. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted())
  14721. {
  14722. this.addVideoInfoToPresence(true);
  14723. }
  14724. },
  14725. doJoin: function (jid, password) {
  14726. this.myroomjid = jid;
  14727. console.info("Joined MUC as " + this.myroomjid);
  14728. this.initPresenceMap(this.myroomjid);
  14729. if (!this.roomjid) {
  14730. this.roomjid = Strophe.getBareJidFromJid(jid);
  14731. // add handlers (just once)
  14732. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14733. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14734. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14735. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14736. }
  14737. if (password !== undefined) {
  14738. this.presMap['password'] = password;
  14739. }
  14740. this.sendPresence();
  14741. },
  14742. doLeave: function () {
  14743. console.log("do leave", this.myroomjid);
  14744. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14745. this.presMap.length = 0;
  14746. this.connection.send(pres);
  14747. },
  14748. createNonAnonymousRoom: function () {
  14749. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  14750. var getForm = $iq({type: 'get', to: this.roomjid})
  14751. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  14752. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14753. var self = this;
  14754. this.connection.sendIQ(getForm, function (form) {
  14755. if (!$(form).find(
  14756. '>query>x[xmlns="jabber:x:data"]' +
  14757. '>field[var="muc#roomconfig_whois"]').length) {
  14758. console.error('non-anonymous rooms not supported');
  14759. return;
  14760. }
  14761. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  14762. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14763. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14764. formSubmit.c('field', {'var': 'FORM_TYPE'})
  14765. .c('value')
  14766. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14767. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  14768. .c('value').t('anyone').up().up();
  14769. self.connection.sendIQ(formSubmit);
  14770. }, function (error) {
  14771. console.error("Error getting room configuration form");
  14772. });
  14773. },
  14774. onPresence: function (pres) {
  14775. var from = pres.getAttribute('from');
  14776. // What is this for? A workaround for something?
  14777. if (pres.getAttribute('type')) {
  14778. return true;
  14779. }
  14780. // Parse etherpad tag.
  14781. var etherpad = $(pres).find('>etherpad');
  14782. if (etherpad.length) {
  14783. if (config.etherpad_base) {
  14784. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  14785. }
  14786. }
  14787. // Parse prezi tag.
  14788. var presentation = $(pres).find('>prezi');
  14789. if (presentation.length) {
  14790. var url = presentation.attr('url');
  14791. var current = presentation.find('>current').text();
  14792. console.log('presentation info received from', from, url);
  14793. if (this.preziMap[from] == null) {
  14794. this.preziMap[from] = url;
  14795. $(document).trigger('presentationadded.muc', [from, url, current]);
  14796. }
  14797. else {
  14798. $(document).trigger('gotoslide.muc', [from, url, current]);
  14799. }
  14800. }
  14801. else if (this.preziMap[from] != null) {
  14802. var url = this.preziMap[from];
  14803. delete this.preziMap[from];
  14804. $(document).trigger('presentationremoved.muc', [from, url]);
  14805. }
  14806. // Parse audio info tag.
  14807. var audioMuted = $(pres).find('>audiomuted');
  14808. if (audioMuted.length) {
  14809. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  14810. from, (audioMuted.text() === "true"));
  14811. }
  14812. // Parse video info tag.
  14813. var videoMuted = $(pres).find('>videomuted');
  14814. if (videoMuted.length) {
  14815. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  14816. from, (videoMuted.text() === "true"));
  14817. }
  14818. var startMuted = $(pres).find('>startmuted');
  14819. if (startMuted.length)
  14820. {
  14821. eventEmitter.emit(XMPPEvents.START_MUTED,
  14822. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  14823. }
  14824. var devices = $(pres).find('>devices');
  14825. if(devices.length)
  14826. {
  14827. var audio = devices.find('>audio');
  14828. var video = devices.find('>video');
  14829. var devicesValues = {audio: false, video: false};
  14830. if(audio.length && audio.text() === "true")
  14831. {
  14832. devicesValues.audio = true;
  14833. }
  14834. if(video.length && video.text() === "true")
  14835. {
  14836. devicesValues.video = true;
  14837. }
  14838. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  14839. Strophe.getResourceFromJid(from), devicesValues);
  14840. }
  14841. var stats = $(pres).find('>stats');
  14842. if (stats.length) {
  14843. var statsObj = {};
  14844. Strophe.forEachChild(stats[0], "stat", function (el) {
  14845. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  14846. });
  14847. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  14848. }
  14849. // Parse status.
  14850. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  14851. this.isOwner = true;
  14852. this.createNonAnonymousRoom();
  14853. }
  14854. // Parse roles.
  14855. var member = {};
  14856. member.show = $(pres).find('>show').text();
  14857. member.status = $(pres).find('>status').text();
  14858. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  14859. member.affiliation = tmp.attr('affiliation');
  14860. member.role = tmp.attr('role');
  14861. // Focus recognition
  14862. member.jid = tmp.attr('jid');
  14863. member.isFocus = false;
  14864. if (member.jid
  14865. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  14866. member.isFocus = true;
  14867. }
  14868. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  14869. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  14870. if (from == this.myroomjid) {
  14871. if (member.affiliation == 'owner') this.isOwner = true;
  14872. if (this.role !== member.role) {
  14873. this.role = member.role;
  14874. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  14875. from, member, pres, Moderator.isModerator());
  14876. }
  14877. if (!this.joined) {
  14878. this.joined = true;
  14879. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  14880. this.list_members.push(from);
  14881. }
  14882. } else if (this.members[from] === undefined) {
  14883. // new participant
  14884. this.members[from] = member;
  14885. this.list_members.push(from);
  14886. console.log('entered', from, member);
  14887. if (member.isFocus) {
  14888. this.focusMucJid = from;
  14889. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  14890. }
  14891. else {
  14892. var id = $(pres).find('>userId').text();
  14893. var email = $(pres).find('>email');
  14894. if (email.length > 0) {
  14895. id = email.text();
  14896. }
  14897. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  14898. }
  14899. } else {
  14900. // Presence update for existing participant
  14901. // Watch role change:
  14902. if (this.members[from].role != member.role) {
  14903. this.members[from].role = member.role;
  14904. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  14905. member.role, member.displayName);
  14906. }
  14907. }
  14908. // Always trigger presence to update bindings
  14909. this.parsePresence(from, member, pres);
  14910. // Trigger status message update
  14911. if (member.status) {
  14912. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  14913. }
  14914. return true;
  14915. },
  14916. onPresenceUnavailable: function (pres) {
  14917. var from = pres.getAttribute('from');
  14918. // room destroyed ?
  14919. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14920. '>destroy').length) {
  14921. var reason;
  14922. var reasonSelect = $(pres).find(
  14923. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14924. '>destroy>reason');
  14925. if (reasonSelect.length) {
  14926. reason = reasonSelect.text();
  14927. }
  14928. XMPP.disposeConference(false);
  14929. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  14930. return true;
  14931. }
  14932. // Status code 110 indicates that this notification is "self-presence".
  14933. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  14934. delete this.members[from];
  14935. this.list_members.splice(this.list_members.indexOf(from), 1);
  14936. this.onParticipantLeft(from);
  14937. }
  14938. // If the status code is 110 this means we're leaving and we would like
  14939. // to remove everyone else from our view, so we trigger the event.
  14940. else if (this.list_members.length > 1) {
  14941. for (var i = 0; i < this.list_members.length; i++) {
  14942. var member = this.list_members[i];
  14943. delete this.members[i];
  14944. this.list_members.splice(i, 1);
  14945. this.onParticipantLeft(member);
  14946. }
  14947. }
  14948. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  14949. $(document).trigger('kicked.muc', [from]);
  14950. if (this.myroomjid === from) {
  14951. XMPP.disposeConference(false);
  14952. eventEmitter.emit(XMPPEvents.KICKED);
  14953. }
  14954. }
  14955. return true;
  14956. },
  14957. onPresenceError: function (pres) {
  14958. var from = pres.getAttribute('from');
  14959. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14960. console.log('on password required', from);
  14961. var self = this;
  14962. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  14963. self.doJoin(from, value);
  14964. });
  14965. } else if ($(pres).find(
  14966. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14967. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  14968. if (toDomain === config.hosts.anonymousdomain) {
  14969. // enter the room by replying with 'not-authorized'. This would
  14970. // result in reconnection from authorized domain.
  14971. // We're either missing Jicofo/Prosody config for anonymous
  14972. // domains or something is wrong.
  14973. // XMPP.promptLogin();
  14974. APP.UI.messageHandler.openReportDialog(null,
  14975. "dialog.joinError", pres);
  14976. } else {
  14977. console.warn('onPresError ', pres);
  14978. APP.UI.messageHandler.openReportDialog(null,
  14979. "dialog.connectError",
  14980. pres);
  14981. }
  14982. } else {
  14983. console.warn('onPresError ', pres);
  14984. APP.UI.messageHandler.openReportDialog(null,
  14985. "dialog.connectError",
  14986. pres);
  14987. }
  14988. return true;
  14989. },
  14990. sendMessage: function (body, nickname) {
  14991. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14992. msg.c('body', body).up();
  14993. if (nickname) {
  14994. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  14995. }
  14996. this.connection.send(msg);
  14997. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  14998. },
  14999. setSubject: function (subject) {
  15000. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15001. msg.c('subject', subject);
  15002. this.connection.send(msg);
  15003. console.log("topic changed to " + subject);
  15004. },
  15005. onMessage: function (msg) {
  15006. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15007. var from = msg.getAttribute('from');
  15008. var nick =
  15009. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15010. .text() ||
  15011. Strophe.getResourceFromJid(from);
  15012. var txt = $(msg).find('>body').text();
  15013. var type = msg.getAttribute("type");
  15014. if (type == "error") {
  15015. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15016. $(msg).find('>text').text(), txt);
  15017. return true;
  15018. }
  15019. var subject = $(msg).find('>subject');
  15020. if (subject.length) {
  15021. var subjectText = subject.text();
  15022. if (subjectText || subjectText == "") {
  15023. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15024. console.log("Subject is changed to " + subjectText);
  15025. }
  15026. }
  15027. // xep-0203 delay
  15028. var stamp = $(msg).find('>delay').attr('stamp');
  15029. if (!stamp) {
  15030. // or xep-0091 delay, UTC timestamp
  15031. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15032. if (stamp) {
  15033. // the format is CCYYMMDDThh:mm:ss
  15034. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15035. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15036. }
  15037. }
  15038. if (txt) {
  15039. console.log('chat', nick, txt);
  15040. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15041. from, nick, txt, this.myroomjid, stamp);
  15042. }
  15043. return true;
  15044. },
  15045. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15046. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15047. var ob = this;
  15048. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15049. function (res) {
  15050. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15051. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15052. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15053. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15054. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15055. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15056. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15057. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15058. ob.connection.sendIQ(formsubmit,
  15059. onSuccess,
  15060. onError);
  15061. } else {
  15062. onNotSupported();
  15063. }
  15064. }, onError);
  15065. },
  15066. kick: function (jid) {
  15067. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15068. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15069. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15070. .c('reason').t('You have been kicked.').up().up().up();
  15071. this.connection.sendIQ(
  15072. kickIQ,
  15073. function (result) {
  15074. console.log('Kick participant with jid: ', jid, result);
  15075. },
  15076. function (error) {
  15077. console.log('Kick participant error: ', error);
  15078. });
  15079. },
  15080. sendPresence: function () {
  15081. if (!this.presMap['to']) {
  15082. // Too early to send presence - not initialized
  15083. return;
  15084. }
  15085. var pres = $pres({to: this.presMap['to'] });
  15086. pres.c('x', {xmlns: this.presMap['xns']});
  15087. if (this.presMap['password']) {
  15088. pres.c('password').t(this.presMap['password']).up();
  15089. }
  15090. pres.up();
  15091. // Send XEP-0115 'c' stanza that contains our capabilities info
  15092. if (this.connection.caps) {
  15093. this.connection.caps.node = config.clientNode;
  15094. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15095. }
  15096. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15097. .t(navigator.userAgent).up();
  15098. if (this.presMap['bridgeIsDown']) {
  15099. pres.c('bridgeIsDown').up();
  15100. }
  15101. if (this.presMap['email']) {
  15102. pres.c('email').t(this.presMap['email']).up();
  15103. }
  15104. if (this.presMap['userId']) {
  15105. pres.c('userId').t(this.presMap['userId']).up();
  15106. }
  15107. if (this.presMap['displayName']) {
  15108. // XEP-0172
  15109. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15110. .t(this.presMap['displayName']).up();
  15111. }
  15112. if(this.presMap["devices"])
  15113. {
  15114. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15115. .c('video').t(this.presMap['devices'].video).up().up();
  15116. }
  15117. if (this.presMap['audions']) {
  15118. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15119. .t(this.presMap['audiomuted']).up();
  15120. }
  15121. if (this.presMap['videons']) {
  15122. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15123. .t(this.presMap['videomuted']).up();
  15124. }
  15125. if (this.presMap['statsns']) {
  15126. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15127. for (var stat in this.presMap["stats"])
  15128. if (this.presMap["stats"][stat] != null)
  15129. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15130. pres.up();
  15131. }
  15132. if (this.presMap['prezins']) {
  15133. pres.c('prezi',
  15134. {xmlns: this.presMap['prezins'],
  15135. 'url': this.presMap['preziurl']})
  15136. .c('current').t(this.presMap['prezicurrent']).up().up();
  15137. }
  15138. if(this.presMap["startMuted"] !== undefined)
  15139. {
  15140. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15141. video: this.presMap["startMuted"].video,
  15142. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15143. delete this.presMap["startMuted"];
  15144. }
  15145. pres.up();
  15146. this.connection.send(pres);
  15147. },
  15148. addDisplayNameToPresence: function (displayName) {
  15149. this.presMap['displayName'] = displayName;
  15150. },
  15151. addDevicesToPresence: function (devices) {
  15152. this.presMap['devices'] = devices;
  15153. },
  15154. addPreziToPresence: function (url, currentSlide) {
  15155. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15156. this.presMap['preziurl'] = url;
  15157. this.presMap['prezicurrent'] = currentSlide;
  15158. },
  15159. removePreziFromPresence: function () {
  15160. delete this.presMap['prezins'];
  15161. delete this.presMap['preziurl'];
  15162. delete this.presMap['prezicurrent'];
  15163. },
  15164. addCurrentSlideToPresence: function (currentSlide) {
  15165. this.presMap['prezicurrent'] = currentSlide;
  15166. },
  15167. getPrezi: function (roomjid) {
  15168. return this.preziMap[roomjid];
  15169. },
  15170. addAudioInfoToPresence: function (isMuted) {
  15171. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15172. this.presMap['audiomuted'] = isMuted.toString();
  15173. },
  15174. addVideoInfoToPresence: function (isMuted) {
  15175. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15176. this.presMap['videomuted'] = isMuted.toString();
  15177. },
  15178. addConnectionInfoToPresence: function (stats) {
  15179. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15180. this.presMap['stats'] = stats;
  15181. },
  15182. findJidFromResource: function (resourceJid) {
  15183. if (resourceJid &&
  15184. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15185. return this.myroomjid;
  15186. }
  15187. var peerJid = null;
  15188. Object.keys(this.members).some(function (jid) {
  15189. peerJid = jid;
  15190. return Strophe.getResourceFromJid(jid) === resourceJid;
  15191. });
  15192. return peerJid;
  15193. },
  15194. addBridgeIsDownToPresence: function () {
  15195. this.presMap['bridgeIsDown'] = true;
  15196. },
  15197. addEmailToPresence: function (email) {
  15198. this.presMap['email'] = email;
  15199. },
  15200. addUserIdToPresence: function (userId) {
  15201. this.presMap['userId'] = userId;
  15202. },
  15203. addStartMutedToPresence: function (audio, video) {
  15204. this.presMap["startMuted"] = {audio: audio, video: video};
  15205. },
  15206. isModerator: function () {
  15207. return this.role === 'moderator';
  15208. },
  15209. getMemberRole: function (peerJid) {
  15210. if (this.members[peerJid]) {
  15211. return this.members[peerJid].role;
  15212. }
  15213. return null;
  15214. },
  15215. onParticipantLeft: function (jid) {
  15216. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15217. this.connection.jingle.terminateByJid(jid);
  15218. if (this.getPrezi(jid)) {
  15219. $(document).trigger('presentationremoved.muc',
  15220. [jid, this.getPrezi(jid)]);
  15221. }
  15222. Moderator.onMucMemberLeft(jid);
  15223. },
  15224. parsePresence: function (from, memeber, pres) {
  15225. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  15226. bridgeIsDown = true;
  15227. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15228. }
  15229. if(memeber.isFocus)
  15230. return;
  15231. var displayName = !config.displayJids
  15232. ? memeber.displayName : Strophe.getResourceFromJid(from);
  15233. if (displayName && displayName.length > 0)
  15234. {
  15235. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15236. }
  15237. var id = $(pres).find('>userID').text();
  15238. var email = $(pres).find('>email');
  15239. if(email.length > 0) {
  15240. id = email.text();
  15241. }
  15242. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15243. }
  15244. });
  15245. };
  15246. },{"../../service/xmpp/XMPPEvents":108,"./JingleSession":53,"./moderator":58}],61:[function(require,module,exports){
  15247. /* jshint -W117 */
  15248. var JingleSession = require("./JingleSession");
  15249. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15250. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15251. module.exports = function(XMPP, eventEmitter)
  15252. {
  15253. function CallIncomingJingle(sid, connection) {
  15254. var sess = connection.jingle.sessions[sid];
  15255. // TODO: do we check activecall == null?
  15256. connection.jingle.activecall = sess;
  15257. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15258. // TODO: check affiliation and/or role
  15259. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15260. sess.usedrip = true; // not-so-naive trickle ice
  15261. sess.sendAnswer();
  15262. sess.accept();
  15263. };
  15264. Strophe.addConnectionPlugin('jingle', {
  15265. connection: null,
  15266. sessions: {},
  15267. jid2session: {},
  15268. ice_config: {iceServers: []},
  15269. pc_constraints: {},
  15270. activecall: null,
  15271. media_constraints: {
  15272. mandatory: {
  15273. 'OfferToReceiveAudio': true,
  15274. 'OfferToReceiveVideo': true
  15275. }
  15276. // MozDontOfferDataChannel: true when this is firefox
  15277. },
  15278. init: function (conn) {
  15279. this.connection = conn;
  15280. if (this.connection.disco) {
  15281. // http://xmpp.org/extensions/xep-0167.html#support
  15282. // http://xmpp.org/extensions/xep-0176.html#support
  15283. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15284. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15285. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15286. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15287. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15288. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15289. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15290. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15291. || RTCBrowserType.isTemasysPluginUsed()) {
  15292. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15293. }
  15294. // this is dealt with by SDP O/A so we don't need to annouce this
  15295. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15296. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15297. if (config.useRtcpMux) {
  15298. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15299. }
  15300. if (config.useBundle) {
  15301. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15302. }
  15303. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15304. }
  15305. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15306. },
  15307. onJingle: function (iq) {
  15308. var sid = $(iq).find('jingle').attr('sid');
  15309. var action = $(iq).find('jingle').attr('action');
  15310. var fromJid = iq.getAttribute('from');
  15311. // send ack first
  15312. var ack = $iq({type: 'result',
  15313. to: fromJid,
  15314. id: iq.getAttribute('id')
  15315. });
  15316. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15317. var sess = this.sessions[sid];
  15318. if ('session-initiate' != action) {
  15319. if (sess === null) {
  15320. ack.type = 'error';
  15321. ack.c('error', {type: 'cancel'})
  15322. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15323. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15324. this.connection.send(ack);
  15325. return true;
  15326. }
  15327. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  15328. // local jid is not checked
  15329. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  15330. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15331. ack.type = 'error';
  15332. ack.c('error', {type: 'cancel'})
  15333. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15334. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15335. this.connection.send(ack);
  15336. return true;
  15337. }
  15338. } else if (sess !== undefined) {
  15339. // existing session with same session id
  15340. // this might be out-of-order if the sess.peerjid is the same as from
  15341. ack.type = 'error';
  15342. ack.c('error', {type: 'cancel'})
  15343. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15344. console.warn('duplicate session id', sid);
  15345. this.connection.send(ack);
  15346. return true;
  15347. }
  15348. // FIXME: check for a defined action
  15349. this.connection.send(ack);
  15350. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15351. switch (action) {
  15352. case 'session-initiate':
  15353. var startMuted = $(iq).find('jingle>startmuted');
  15354. if(startMuted && startMuted.length > 0)
  15355. {
  15356. var audioMuted = startMuted.attr("audio");
  15357. var videoMuted = startMuted.attr("video");
  15358. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  15359. (videoMuted === "true"));
  15360. }
  15361. sess = new JingleSession(
  15362. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15363. this.connection, XMPP, eventEmitter);
  15364. // configure session
  15365. sess.media_constraints = this.media_constraints;
  15366. sess.pc_constraints = this.pc_constraints;
  15367. sess.ice_config = this.ice_config;
  15368. sess.initiate(fromJid, false);
  15369. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15370. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15371. this.sessions[sess.sid] = sess;
  15372. this.jid2session[sess.peerjid] = sess;
  15373. // the callback should either
  15374. // .sendAnswer and .accept
  15375. // or .sendTerminate -- not necessarily synchronus
  15376. CallIncomingJingle(sess.sid, this.connection);
  15377. break;
  15378. case 'session-accept':
  15379. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15380. sess.accept();
  15381. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15382. break;
  15383. case 'session-terminate':
  15384. // If this is not the focus sending the terminate, we have
  15385. // nothing more to do here.
  15386. if (Object.keys(this.sessions).length < 1
  15387. || !(this.sessions[Object.keys(this.sessions)[0]]
  15388. instanceof JingleSession))
  15389. {
  15390. break;
  15391. }
  15392. console.log('terminating...', sess.sid);
  15393. sess.terminate();
  15394. this.terminate(sess.sid);
  15395. if ($(iq).find('>jingle>reason').length) {
  15396. $(document).trigger('callterminated.jingle', [
  15397. sess.sid,
  15398. sess.peerjid,
  15399. $(iq).find('>jingle>reason>:first')[0].tagName,
  15400. $(iq).find('>jingle>reason>text').text()
  15401. ]);
  15402. } else {
  15403. $(document).trigger('callterminated.jingle',
  15404. [sess.sid, sess.peerjid]);
  15405. }
  15406. break;
  15407. case 'transport-info':
  15408. sess.addIceCandidate($(iq).find('>jingle>content'));
  15409. break;
  15410. case 'session-info':
  15411. var affected;
  15412. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15413. $(document).trigger('ringing.jingle', [sess.sid]);
  15414. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15415. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15416. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15417. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15418. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15419. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15420. }
  15421. break;
  15422. case 'addsource': // FIXME: proprietary, un-jingleish
  15423. case 'source-add': // FIXME: proprietary
  15424. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15425. break;
  15426. case 'removesource': // FIXME: proprietary, un-jingleish
  15427. case 'source-remove': // FIXME: proprietary
  15428. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15429. break;
  15430. default:
  15431. console.warn('jingle action not implemented', action);
  15432. break;
  15433. }
  15434. return true;
  15435. },
  15436. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15437. var sess = new JingleSession(myjid || this.connection.jid,
  15438. Math.random().toString(36).substr(2, 12), // random string
  15439. this.connection, XMPP, eventEmitter);
  15440. // configure session
  15441. sess.media_constraints = this.media_constraints;
  15442. sess.pc_constraints = this.pc_constraints;
  15443. sess.ice_config = this.ice_config;
  15444. sess.initiate(peerjid, true);
  15445. this.sessions[sess.sid] = sess;
  15446. this.jid2session[sess.peerjid] = sess;
  15447. sess.sendOffer();
  15448. return sess;
  15449. },
  15450. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15451. if (sid === null || sid === undefined) {
  15452. for (sid in this.sessions) {
  15453. if (this.sessions[sid].state != 'ended') {
  15454. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15455. this.sessions[sid].terminate();
  15456. }
  15457. delete this.jid2session[this.sessions[sid].peerjid];
  15458. delete this.sessions[sid];
  15459. }
  15460. } else if (this.sessions.hasOwnProperty(sid)) {
  15461. if (this.sessions[sid].state != 'ended') {
  15462. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15463. this.sessions[sid].terminate();
  15464. }
  15465. delete this.jid2session[this.sessions[sid].peerjid];
  15466. delete this.sessions[sid];
  15467. }
  15468. },
  15469. // Used to terminate a session when an unavailable presence is received.
  15470. terminateByJid: function (jid) {
  15471. if (this.jid2session.hasOwnProperty(jid)) {
  15472. var sess = this.jid2session[jid];
  15473. if (sess) {
  15474. sess.terminate();
  15475. console.log('peer went away silently', jid);
  15476. delete this.sessions[sess.sid];
  15477. delete this.jid2session[jid];
  15478. $(document).trigger('callterminated.jingle',
  15479. [sess.sid, jid], 'gone');
  15480. }
  15481. }
  15482. },
  15483. terminateRemoteByJid: function (jid, reason) {
  15484. if (this.jid2session.hasOwnProperty(jid)) {
  15485. var sess = this.jid2session[jid];
  15486. if (sess) {
  15487. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15488. sess.terminate();
  15489. console.log('terminate peer with jid', sess.sid, jid);
  15490. delete this.sessions[sess.sid];
  15491. delete this.jid2session[jid];
  15492. $(document).trigger('callterminated.jingle',
  15493. [sess.sid, jid, 'kicked']);
  15494. }
  15495. }
  15496. },
  15497. getStunAndTurnCredentials: function () {
  15498. // get stun and turn configuration from server via xep-0215
  15499. // uses time-limited credentials as described in
  15500. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15501. //
  15502. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15503. // for a prosody module which implements this
  15504. //
  15505. // currently, this doesn't work with updateIce and therefore credentials with a long
  15506. // validity have to be fetched before creating the peerconnection
  15507. // TODO: implement refresh via updateIce as described in
  15508. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15509. var self = this;
  15510. this.connection.sendIQ(
  15511. $iq({type: 'get', to: this.connection.domain})
  15512. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15513. function (res) {
  15514. var iceservers = [];
  15515. $(res).find('>services>service').each(function (idx, el) {
  15516. el = $(el);
  15517. var dict = {};
  15518. var type = el.attr('type');
  15519. switch (type) {
  15520. case 'stun':
  15521. dict.url = 'stun:' + el.attr('host');
  15522. if (el.attr('port')) {
  15523. dict.url += ':' + el.attr('port');
  15524. }
  15525. iceservers.push(dict);
  15526. break;
  15527. case 'turn':
  15528. case 'turns':
  15529. dict.url = type + ':';
  15530. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15531. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15532. dict.url += el.attr('username') + '@';
  15533. } else {
  15534. dict.username = el.attr('username'); // only works in M28
  15535. }
  15536. }
  15537. dict.url += el.attr('host');
  15538. if (el.attr('port') && el.attr('port') != '3478') {
  15539. dict.url += ':' + el.attr('port');
  15540. }
  15541. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15542. dict.url += '?transport=' + el.attr('transport');
  15543. }
  15544. if (el.attr('password')) {
  15545. dict.credential = el.attr('password');
  15546. }
  15547. iceservers.push(dict);
  15548. break;
  15549. }
  15550. });
  15551. self.ice_config.iceServers = iceservers;
  15552. },
  15553. function (err) {
  15554. console.warn('getting turn credentials failed', err);
  15555. console.warn('is mod_turncredentials or similar installed?');
  15556. }
  15557. );
  15558. // implement push?
  15559. },
  15560. /**
  15561. * Populates the log data
  15562. */
  15563. populateData: function () {
  15564. var data = {};
  15565. var self = this;
  15566. Object.keys(this.sessions).forEach(function (sid) {
  15567. var session = self.sessions[sid];
  15568. if (session.peerconnection && session.peerconnection.updateLog) {
  15569. // FIXME: should probably be a .dump call
  15570. data["jingle_" + session.sid] = {
  15571. updateLog: session.peerconnection.updateLog,
  15572. stats: session.peerconnection.stats,
  15573. url: window.location.href
  15574. };
  15575. }
  15576. });
  15577. return data;
  15578. }
  15579. });
  15580. };
  15581. },{"../../service/xmpp/XMPPEvents":108,"../RTC/RTCBrowserType":8,"./JingleSession":53}],62:[function(require,module,exports){
  15582. /* global Strophe */
  15583. module.exports = function () {
  15584. Strophe.addConnectionPlugin('logger', {
  15585. // logs raw stanzas and makes them available for download as JSON
  15586. connection: null,
  15587. log: [],
  15588. init: function (conn) {
  15589. this.connection = conn;
  15590. this.connection.rawInput = this.log_incoming.bind(this);
  15591. this.connection.rawOutput = this.log_outgoing.bind(this);
  15592. },
  15593. log_incoming: function (stanza) {
  15594. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15595. },
  15596. log_outgoing: function (stanza) {
  15597. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15598. }
  15599. });
  15600. };
  15601. },{}],63:[function(require,module,exports){
  15602. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15603. setAudioMuted, Strophe */
  15604. /**
  15605. * Moderate connection plugin.
  15606. */
  15607. module.exports = function (XMPP) {
  15608. Strophe.addConnectionPlugin('moderate', {
  15609. connection: null,
  15610. init: function (conn) {
  15611. this.connection = conn;
  15612. this.connection.addHandler(this.onMute.bind(this),
  15613. 'http://jitsi.org/jitmeet/audio',
  15614. 'iq',
  15615. 'set',
  15616. null,
  15617. null);
  15618. },
  15619. setMute: function (jid, mute) {
  15620. console.info("set mute", mute);
  15621. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15622. .c('mute', {
  15623. xmlns: 'http://jitsi.org/jitmeet/audio',
  15624. jid: jid
  15625. })
  15626. .t(mute.toString())
  15627. .up();
  15628. this.connection.sendIQ(
  15629. iqToFocus,
  15630. function (result) {
  15631. console.log('set mute', result);
  15632. },
  15633. function (error) {
  15634. console.log('set mute error', error);
  15635. });
  15636. },
  15637. onMute: function (iq) {
  15638. var from = iq.getAttribute('from');
  15639. if (from !== this.connection.emuc.focusMucJid) {
  15640. console.warn("Ignored mute from non focus peer");
  15641. return false;
  15642. }
  15643. var mute = $(iq).find('mute');
  15644. if (mute.length) {
  15645. var doMuteAudio = mute.text() === "true";
  15646. APP.UI.setAudioMuted(doMuteAudio);
  15647. XMPP.forceMuted = doMuteAudio;
  15648. }
  15649. return true;
  15650. },
  15651. eject: function (jid) {
  15652. // We're not the focus, so can't terminate
  15653. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15654. this.connection.emuc.kick(jid);
  15655. }
  15656. });
  15657. }
  15658. },{}],64:[function(require,module,exports){
  15659. /* jshint -W117 */
  15660. module.exports = function() {
  15661. Strophe.addConnectionPlugin('rayo',
  15662. {
  15663. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15664. connection: null,
  15665. init: function (conn) {
  15666. this.connection = conn;
  15667. if (this.connection.disco) {
  15668. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15669. }
  15670. this.connection.addHandler(
  15671. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15672. },
  15673. onRayo: function (iq) {
  15674. console.info("Rayo IQ", iq);
  15675. },
  15676. dial: function (to, from, roomName, roomPass) {
  15677. var self = this;
  15678. var req = $iq(
  15679. {
  15680. type: 'set',
  15681. to: this.connection.emuc.focusMucJid
  15682. }
  15683. );
  15684. req.c('dial',
  15685. {
  15686. xmlns: this.RAYO_XMLNS,
  15687. to: to,
  15688. from: from
  15689. });
  15690. req.c('header',
  15691. {
  15692. name: 'JvbRoomName',
  15693. value: roomName
  15694. }).up();
  15695. if (roomPass !== null && roomPass.length) {
  15696. req.c('header',
  15697. {
  15698. name: 'JvbRoomPassword',
  15699. value: roomPass
  15700. }).up();
  15701. }
  15702. this.connection.sendIQ(
  15703. req,
  15704. function (result) {
  15705. console.info('Dial result ', result);
  15706. var resource = $(result).find('ref').attr('uri');
  15707. this.call_resource = resource.substr('xmpp:'.length);
  15708. console.info(
  15709. "Received call resource: " + this.call_resource);
  15710. },
  15711. function (error) {
  15712. console.info('Dial error ', error);
  15713. }
  15714. );
  15715. },
  15716. hang_up: function () {
  15717. if (!this.call_resource) {
  15718. console.warn("No call in progress");
  15719. return;
  15720. }
  15721. var self = this;
  15722. var req = $iq(
  15723. {
  15724. type: 'set',
  15725. to: this.call_resource
  15726. }
  15727. );
  15728. req.c('hangup',
  15729. {
  15730. xmlns: this.RAYO_XMLNS
  15731. });
  15732. this.connection.sendIQ(
  15733. req,
  15734. function (result) {
  15735. console.info('Hangup result ', result);
  15736. self.call_resource = null;
  15737. },
  15738. function (error) {
  15739. console.info('Hangup error ', error);
  15740. self.call_resource = null;
  15741. }
  15742. );
  15743. }
  15744. }
  15745. );
  15746. };
  15747. },{}],65:[function(require,module,exports){
  15748. /**
  15749. * Strophe logger implementation. Logs from level WARN and above.
  15750. */
  15751. module.exports = function () {
  15752. Strophe.log = function (level, msg) {
  15753. switch (level) {
  15754. case Strophe.LogLevel.WARN:
  15755. console.warn("Strophe: " + msg);
  15756. break;
  15757. case Strophe.LogLevel.ERROR:
  15758. case Strophe.LogLevel.FATAL:
  15759. console.error("Strophe: " + msg);
  15760. break;
  15761. }
  15762. };
  15763. Strophe.getStatusString = function (status) {
  15764. switch (status) {
  15765. case Strophe.Status.ERROR:
  15766. return "ERROR";
  15767. case Strophe.Status.CONNECTING:
  15768. return "CONNECTING";
  15769. case Strophe.Status.CONNFAIL:
  15770. return "CONNFAIL";
  15771. case Strophe.Status.AUTHENTICATING:
  15772. return "AUTHENTICATING";
  15773. case Strophe.Status.AUTHFAIL:
  15774. return "AUTHFAIL";
  15775. case Strophe.Status.CONNECTED:
  15776. return "CONNECTED";
  15777. case Strophe.Status.DISCONNECTED:
  15778. return "DISCONNECTED";
  15779. case Strophe.Status.DISCONNECTING:
  15780. return "DISCONNECTING";
  15781. case Strophe.Status.ATTACHED:
  15782. return "ATTACHED";
  15783. default:
  15784. return "unknown";
  15785. }
  15786. };
  15787. };
  15788. },{}],66:[function(require,module,exports){
  15789. /* global $, APP, config, Strophe*/
  15790. var Moderator = require("./moderator");
  15791. var EventEmitter = require("events");
  15792. var Recording = require("./recording");
  15793. var SDP = require("./SDP");
  15794. var Settings = require("../settings/Settings");
  15795. var Pako = require("pako");
  15796. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  15797. var RTCEvents = require("../../service/RTC/RTCEvents");
  15798. var UIEvents = require("../../service/UI/UIEvents");
  15799. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15800. var retry = require('retry');
  15801. var eventEmitter = new EventEmitter();
  15802. var connection = null;
  15803. var authenticatedUser = false;
  15804. function connect(jid, password) {
  15805. var faultTolerantConnect = retry.operation({
  15806. retries: 3
  15807. });
  15808. // fault tolerant connect
  15809. faultTolerantConnect.attempt(function () {
  15810. connection = XMPP.createConnection();
  15811. Moderator.setConnection(connection);
  15812. if (connection.disco) {
  15813. // for chrome, add multistream cap
  15814. }
  15815. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  15816. if (config.useIPv6) {
  15817. // https://code.google.com/p/webrtc/issues/detail?id=2828
  15818. if (!connection.jingle.pc_constraints.optional)
  15819. connection.jingle.pc_constraints.optional = [];
  15820. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  15821. }
  15822. // Include user info in MUC presence
  15823. var settings = Settings.getSettings();
  15824. if (settings.email) {
  15825. connection.emuc.addEmailToPresence(settings.email);
  15826. }
  15827. if (settings.uid) {
  15828. connection.emuc.addUserIdToPresence(settings.uid);
  15829. }
  15830. if (settings.displayName) {
  15831. connection.emuc.addDisplayNameToPresence(settings.displayName);
  15832. }
  15833. // connection.connect() starts the connection process.
  15834. //
  15835. // As the connection process proceeds, the user supplied callback will
  15836. // be triggered multiple times with status updates. The callback should
  15837. // take two arguments - the status code and the error condition.
  15838. //
  15839. // The status code will be one of the values in the Strophe.Status
  15840. // constants. The error condition will be one of the conditions defined
  15841. // in RFC 3920 or the condition ‘strophe-parsererror’.
  15842. //
  15843. // The Parameters wait, hold and route are optional and only relevant
  15844. // for BOSH connections. Please see XEP 124 for a more detailed
  15845. // explanation of the optional parameters.
  15846. //
  15847. // Connection status constants for use by the connection handler
  15848. // callback.
  15849. //
  15850. // Status.ERROR - An error has occurred (websockets specific)
  15851. // Status.CONNECTING - The connection is currently being made
  15852. // Status.CONNFAIL - The connection attempt failed
  15853. // Status.AUTHENTICATING - The connection is authenticating
  15854. // Status.AUTHFAIL - The authentication attempt failed
  15855. // Status.CONNECTED - The connection has succeeded
  15856. // Status.DISCONNECTED - The connection has been terminated
  15857. // Status.DISCONNECTING - The connection is currently being terminated
  15858. // Status.ATTACHED - The connection has been attached
  15859. var anonymousConnectionFailed = false;
  15860. var connectionFailed = false;
  15861. var lastErrorMsg;
  15862. connection.connect(jid, password, function (status, msg) {
  15863. console.log('Strophe status changed to',
  15864. Strophe.getStatusString(status), msg);
  15865. if (status === Strophe.Status.CONNECTED) {
  15866. if (config.useStunTurn) {
  15867. connection.jingle.getStunAndTurnCredentials();
  15868. }
  15869. console.info("My Jabber ID: " + connection.jid);
  15870. if (password)
  15871. authenticatedUser = true;
  15872. maybeDoJoin();
  15873. } else if (status === Strophe.Status.CONNFAIL) {
  15874. if (msg === 'x-strophe-bad-non-anon-jid') {
  15875. anonymousConnectionFailed = true;
  15876. } else {
  15877. connectionFailed = true;
  15878. }
  15879. lastErrorMsg = msg;
  15880. } else if (status === Strophe.Status.DISCONNECTED) {
  15881. if (anonymousConnectionFailed) {
  15882. // prompt user for username and password
  15883. XMPP.promptLogin();
  15884. } else {
  15885. // Strophe already has built-in HTTP/BOSH error handling and
  15886. // request retry logic. Requests are resent automatically
  15887. // until their error count reaches 5. Strophe.js disconnects
  15888. // if the error count is > 5. We are not replicating this
  15889. // here.
  15890. //
  15891. // The "problem" is that failed HTTP/BOSH requests don't
  15892. // trigger a callback with a status update, so when a
  15893. // callback with status Strophe.Status.DISCONNECTED arrives,
  15894. // we can't be sure if it's a graceful disconnect or if it's
  15895. // triggered by some HTTP/BOSH error.
  15896. //
  15897. // But that's a minor issue in Jitsi Meet as we never
  15898. // disconnect anyway, not even when the user closes the
  15899. // browser window (which is kind of wrong, but the point is
  15900. // that we should never ever get disconnected).
  15901. //
  15902. // On the other hand, failed connections due to XMPP layer
  15903. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  15904. //
  15905. // Here we implement retry logic for failed connections due
  15906. // to XMPP layer errors and we display an error to the user
  15907. // if we get disconnected from the XMPP server permanently.
  15908. // If the connection failed, retry.
  15909. if (connectionFailed
  15910. && faultTolerantConnect.retry("connection-failed")) {
  15911. return;
  15912. }
  15913. // If we failed to connect to the XMPP server, fire an event
  15914. // to let all the interested module now about it.
  15915. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  15916. msg ? msg : lastErrorMsg);
  15917. }
  15918. } else if (status === Strophe.Status.AUTHFAIL) {
  15919. // wrong password or username, prompt user
  15920. XMPP.promptLogin();
  15921. }
  15922. });
  15923. });
  15924. }
  15925. function maybeDoJoin() {
  15926. if (connection && connection.connected &&
  15927. Strophe.getResourceFromJid(connection.jid)
  15928. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15929. // .connected is true while connecting?
  15930. doJoin();
  15931. }
  15932. }
  15933. function doJoin() {
  15934. var roomName = APP.UI.generateRoomName();
  15935. Moderator.allocateConferenceFocus(
  15936. roomName, APP.UI.checkForNicknameAndJoin);
  15937. }
  15938. function initStrophePlugins()
  15939. {
  15940. require("./strophe.emuc")(XMPP, eventEmitter);
  15941. require("./strophe.jingle")(XMPP, eventEmitter);
  15942. require("./strophe.moderate")(XMPP);
  15943. require("./strophe.util")();
  15944. require("./strophe.rayo")();
  15945. require("./strophe.logger")();
  15946. }
  15947. function registerListeners() {
  15948. APP.RTC.addStreamListener(maybeDoJoin,
  15949. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  15950. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  15951. XMPP.addToPresence("devices", devices);
  15952. })
  15953. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  15954. XMPP.addToPresence("displayName", nickname);
  15955. });
  15956. }
  15957. var unload = (function () {
  15958. var unloaded = false;
  15959. return function () {
  15960. if (unloaded) { return; }
  15961. unloaded = true;
  15962. if (connection && connection.connected) {
  15963. // ensure signout
  15964. $.ajax({
  15965. type: 'POST',
  15966. url: config.bosh,
  15967. async: false,
  15968. cache: false,
  15969. contentType: 'application/xml',
  15970. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  15971. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  15972. (connection.sid || connection._proto.sid) +
  15973. "' type='terminate'>" +
  15974. "<presence xmlns='jabber:client' type='unavailable'/>" +
  15975. "</body>",
  15976. success: function (data) {
  15977. console.log('signed out');
  15978. console.log(data);
  15979. },
  15980. error: function (XMLHttpRequest, textStatus, errorThrown) {
  15981. console.log('signout error',
  15982. textStatus + ' (' + errorThrown + ')');
  15983. }
  15984. });
  15985. }
  15986. XMPP.disposeConference(true);
  15987. };
  15988. })();
  15989. function setupEvents() {
  15990. // In recent versions of FF the 'beforeunload' event is not fired when the
  15991. // window or the tab is closed. It is only fired when we leave the page
  15992. // (change URL). If this participant doesn't unload properly, then it
  15993. // becomes a ghost for the rest of the participants that stay in the
  15994. // conference. Thankfully handling the 'unload' event in addition to the
  15995. // 'beforeunload' event seems to garante the execution of the 'unload'
  15996. // method at least once.
  15997. //
  15998. // The 'unload' method can safely be run multiple times, it will actually do
  15999. // something only the first time that it's run, so we're don't have to worry
  16000. // about browsers that fire both events.
  16001. $(window).bind('beforeunload', unload);
  16002. $(window).bind('unload', unload);
  16003. }
  16004. var XMPP = {
  16005. getConnection: function(){ return connection; },
  16006. sessionTerminated: false,
  16007. /**
  16008. * XMPP connection status
  16009. */
  16010. Status: Strophe.Status,
  16011. /**
  16012. * Remembers if we were muted by the focus.
  16013. * @type {boolean}
  16014. */
  16015. forceMuted: false,
  16016. start: function () {
  16017. setupEvents();
  16018. initStrophePlugins();
  16019. registerListeners();
  16020. Moderator.init(this, eventEmitter);
  16021. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16022. // Force authenticated domain if room is appended with '?login=true'
  16023. if (config.hosts.anonymousdomain &&
  16024. window.location.search.indexOf("login=true") !== -1) {
  16025. configDomain = config.hosts.domain;
  16026. }
  16027. var jid = configDomain || window.location.hostname;
  16028. connect(jid, null);
  16029. },
  16030. createConnection: function () {
  16031. var bosh = config.bosh || '/http-bind';
  16032. return new Strophe.Connection(bosh);
  16033. },
  16034. getStatusString: function (status) {
  16035. return Strophe.getStatusString(status);
  16036. },
  16037. promptLogin: function () {
  16038. // FIXME: re-use LoginDialog which supports retries
  16039. APP.UI.showLoginPopup(connect);
  16040. },
  16041. joinRoom: function(roomName, useNicks, nick)
  16042. {
  16043. var roomjid;
  16044. roomjid = roomName;
  16045. if (useNicks) {
  16046. if (nick) {
  16047. roomjid += '/' + nick;
  16048. } else {
  16049. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16050. }
  16051. } else {
  16052. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16053. if(!authenticatedUser)
  16054. tmpJid = tmpJid.substr(0, 8);
  16055. roomjid += '/' + tmpJid;
  16056. }
  16057. connection.emuc.doJoin(roomjid);
  16058. },
  16059. myJid: function () {
  16060. if(!connection)
  16061. return null;
  16062. return connection.emuc.myroomjid;
  16063. },
  16064. myResource: function () {
  16065. if(!connection || ! connection.emuc.myroomjid)
  16066. return null;
  16067. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16068. },
  16069. disposeConference: function (onUnload) {
  16070. var handler = connection.jingle.activecall;
  16071. if (handler && handler.peerconnection) {
  16072. // FIXME: probably removing streams is not required and close() should
  16073. // be enough
  16074. if (APP.RTC.localAudio) {
  16075. handler.peerconnection.removeStream(
  16076. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16077. }
  16078. if (APP.RTC.localVideo) {
  16079. handler.peerconnection.removeStream(
  16080. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16081. }
  16082. handler.peerconnection.close();
  16083. }
  16084. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16085. connection.jingle.activecall = null;
  16086. if(!onUnload)
  16087. {
  16088. this.sessionTerminated = true;
  16089. connection.emuc.doLeave();
  16090. }
  16091. },
  16092. addListener: function(type, listener)
  16093. {
  16094. eventEmitter.on(type, listener);
  16095. },
  16096. removeListener: function (type, listener) {
  16097. eventEmitter.removeListener(type, listener);
  16098. },
  16099. allocateConferenceFocus: function(roomName, callback) {
  16100. Moderator.allocateConferenceFocus(roomName, callback);
  16101. },
  16102. getLoginUrl: function (roomName, callback) {
  16103. Moderator.getLoginUrl(roomName, callback);
  16104. },
  16105. getPopupLoginUrl: function (roomName, callback) {
  16106. Moderator.getPopupLoginUrl(roomName, callback);
  16107. },
  16108. isModerator: function () {
  16109. return Moderator.isModerator();
  16110. },
  16111. isSipGatewayEnabled: function () {
  16112. return Moderator.isSipGatewayEnabled();
  16113. },
  16114. isExternalAuthEnabled: function () {
  16115. return Moderator.isExternalAuthEnabled();
  16116. },
  16117. isConferenceInProgress: function () {
  16118. return connection && connection.jingle.activecall &&
  16119. connection.jingle.activecall.peerconnection;
  16120. },
  16121. switchStreams: function (stream, oldStream, callback, isAudio) {
  16122. if (this.isConferenceInProgress()) {
  16123. // FIXME: will block switchInProgress on true value in case of exception
  16124. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16125. } else {
  16126. // We are done immediately
  16127. console.warn("No conference handler or conference not started yet");
  16128. callback();
  16129. }
  16130. },
  16131. sendVideoInfoPresence: function (mute) {
  16132. if(!connection)
  16133. return;
  16134. connection.emuc.addVideoInfoToPresence(mute);
  16135. connection.emuc.sendPresence();
  16136. },
  16137. setVideoMute: function (mute, callback, options) {
  16138. if(!connection)
  16139. return;
  16140. var self = this;
  16141. var localCallback = function (mute) {
  16142. self.sendVideoInfoPresence(mute);
  16143. return callback(mute);
  16144. };
  16145. if(connection.jingle.activecall)
  16146. {
  16147. connection.jingle.activecall.setVideoMute(
  16148. mute, localCallback, options);
  16149. }
  16150. else {
  16151. localCallback(mute);
  16152. }
  16153. },
  16154. setAudioMute: function (mute, callback) {
  16155. if (!(connection && APP.RTC.localAudio)) {
  16156. return false;
  16157. }
  16158. if (this.forceMuted && !mute) {
  16159. console.info("Asking focus for unmute");
  16160. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16161. // FIXME: wait for result before resetting muted status
  16162. this.forceMuted = false;
  16163. }
  16164. if (mute == APP.RTC.localAudio.isMuted()) {
  16165. // Nothing to do
  16166. return true;
  16167. }
  16168. // It is not clear what is the right way to handle multiple tracks.
  16169. // So at least make sure that they are all muted or all unmuted and
  16170. // that we send presence just once.
  16171. APP.RTC.localAudio.setMute(!mute);
  16172. // isMuted is the opposite of audioEnabled
  16173. this.sendAudioInfoPresence(mute, callback);
  16174. return true;
  16175. },
  16176. sendAudioInfoPresence: function(mute, callback)
  16177. {
  16178. if(connection) {
  16179. connection.emuc.addAudioInfoToPresence(mute);
  16180. connection.emuc.sendPresence();
  16181. }
  16182. callback();
  16183. return true;
  16184. },
  16185. // Really mute video, i.e. dont even send black frames
  16186. muteVideo: function (pc, unmute) {
  16187. // FIXME: this probably needs another of those lovely state safeguards...
  16188. // which checks for iceconn == connected and sigstate == stable
  16189. pc.setRemoteDescription(pc.remoteDescription,
  16190. function () {
  16191. pc.createAnswer(
  16192. function (answer) {
  16193. var sdp = new SDP(answer.sdp);
  16194. if (sdp.media.length > 1) {
  16195. if (unmute)
  16196. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  16197. else
  16198. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  16199. sdp.raw = sdp.session + sdp.media.join('');
  16200. answer.sdp = sdp.raw;
  16201. }
  16202. pc.setLocalDescription(answer,
  16203. function () {
  16204. console.log('mute SLD ok');
  16205. },
  16206. function (error) {
  16207. console.log('mute SLD error');
  16208. APP.UI.messageHandler.showError("dialog.error",
  16209. "dialog.SLDFailure");
  16210. }
  16211. );
  16212. },
  16213. function (error) {
  16214. console.log(error);
  16215. APP.UI.messageHandler.showError();
  16216. }
  16217. );
  16218. },
  16219. function (error) {
  16220. console.log('muteVideo SRD error');
  16221. APP.UI.messageHandler.showError("dialog.error",
  16222. "dialog.SRDFailure");
  16223. }
  16224. );
  16225. },
  16226. toggleRecording: function (tokenEmptyCallback,
  16227. startingCallback, startedCallback) {
  16228. Recording.toggleRecording(tokenEmptyCallback,
  16229. startingCallback, startedCallback, connection);
  16230. },
  16231. addToPresence: function (name, value, dontSend) {
  16232. switch (name)
  16233. {
  16234. case "displayName":
  16235. connection.emuc.addDisplayNameToPresence(value);
  16236. break;
  16237. case "prezi":
  16238. connection.emuc.addPreziToPresence(value, 0);
  16239. break;
  16240. case "preziSlide":
  16241. connection.emuc.addCurrentSlideToPresence(value);
  16242. break;
  16243. case "connectionQuality":
  16244. connection.emuc.addConnectionInfoToPresence(value);
  16245. break;
  16246. case "email":
  16247. connection.emuc.addEmailToPresence(value);
  16248. break;
  16249. case "devices":
  16250. connection.emuc.addDevicesToPresence(value);
  16251. break;
  16252. case "startMuted":
  16253. if(!Moderator.isModerator())
  16254. return;
  16255. connection.emuc.addStartMutedToPresence(value[0],
  16256. value[1]);
  16257. break;
  16258. default :
  16259. console.log("Unknown tag for presence: " + name);
  16260. return;
  16261. }
  16262. if (!dontSend)
  16263. connection.emuc.sendPresence();
  16264. },
  16265. /**
  16266. * Sends 'data' as a log message to the focus. Returns true iff a message
  16267. * was sent.
  16268. * @param data
  16269. * @returns {boolean} true iff a message was sent.
  16270. */
  16271. sendLogs: function (data) {
  16272. if(!connection.emuc.focusMucJid)
  16273. return false;
  16274. var deflate = true;
  16275. var content = JSON.stringify(data);
  16276. if (deflate) {
  16277. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16278. }
  16279. content = Base64.encode(content);
  16280. // XEP-0337-ish
  16281. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16282. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16283. id: 'PeerConnectionStats'});
  16284. message.c('message').t(content).up();
  16285. if (deflate) {
  16286. message.c('tag', {name: "deflated", value: "true"}).up();
  16287. }
  16288. message.up();
  16289. connection.send(message);
  16290. return true;
  16291. },
  16292. populateData: function () {
  16293. var data = {};
  16294. if (connection.jingle) {
  16295. data = connection.jingle.populateData();
  16296. }
  16297. return data;
  16298. },
  16299. getLogger: function () {
  16300. if(connection.logger)
  16301. return connection.logger.log;
  16302. return null;
  16303. },
  16304. getPrezi: function () {
  16305. return connection.emuc.getPrezi(this.myJid());
  16306. },
  16307. removePreziFromPresence: function () {
  16308. connection.emuc.removePreziFromPresence();
  16309. connection.emuc.sendPresence();
  16310. },
  16311. sendChatMessage: function (message, nickname) {
  16312. connection.emuc.sendMessage(message, nickname);
  16313. },
  16314. setSubject: function (topic) {
  16315. connection.emuc.setSubject(topic);
  16316. },
  16317. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16318. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16319. },
  16320. dial: function (to, from, roomName,roomPass) {
  16321. connection.rayo.dial(to, from, roomName,roomPass);
  16322. },
  16323. setMute: function (jid, mute) {
  16324. connection.moderate.setMute(jid, mute);
  16325. },
  16326. eject: function (jid) {
  16327. connection.moderate.eject(jid);
  16328. },
  16329. logout: function (callback) {
  16330. Moderator.logout(callback);
  16331. },
  16332. findJidFromResource: function (resource) {
  16333. return connection.emuc.findJidFromResource(resource);
  16334. },
  16335. getMembers: function () {
  16336. return connection.emuc.members;
  16337. },
  16338. getJidFromSSRC: function (ssrc) {
  16339. if (!this.isConferenceInProgress())
  16340. return null;
  16341. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16342. },
  16343. getMUCJoined: function () {
  16344. return connection.emuc.joined;
  16345. },
  16346. getSessions: function () {
  16347. return connection.jingle.sessions;
  16348. },
  16349. removeStream: function (stream) {
  16350. if (!this.isConferenceInProgress())
  16351. return;
  16352. connection.jingle.activecall.peerconnection.removeStream(stream);
  16353. }
  16354. };
  16355. module.exports = XMPP;
  16356. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes":101,"../../service/UI/UIEvents":102,"../../service/xmpp/XMPPEvents":108,"../settings/Settings":47,"./SDP":54,"./moderator":58,"./recording":59,"./strophe.emuc":60,"./strophe.jingle":61,"./strophe.logger":62,"./strophe.moderate":63,"./strophe.rayo":64,"./strophe.util":65,"events":109,"pako":69,"retry":85}],67:[function(require,module,exports){
  16357. (function (process){
  16358. /*!
  16359. * async
  16360. * https://github.com/caolan/async
  16361. *
  16362. * Copyright 2010-2014 Caolan McMahon
  16363. * Released under the MIT license
  16364. */
  16365. /*jshint onevar: false, indent:4 */
  16366. /*global setImmediate: false, setTimeout: false, console: false */
  16367. (function () {
  16368. var async = {};
  16369. // global on the server, window in the browser
  16370. var root, previous_async;
  16371. root = this;
  16372. if (root != null) {
  16373. previous_async = root.async;
  16374. }
  16375. async.noConflict = function () {
  16376. root.async = previous_async;
  16377. return async;
  16378. };
  16379. function only_once(fn) {
  16380. var called = false;
  16381. return function() {
  16382. if (called) throw new Error("Callback was already called.");
  16383. called = true;
  16384. fn.apply(root, arguments);
  16385. }
  16386. }
  16387. //// cross-browser compatiblity functions ////
  16388. var _toString = Object.prototype.toString;
  16389. var _isArray = Array.isArray || function (obj) {
  16390. return _toString.call(obj) === '[object Array]';
  16391. };
  16392. var _each = function (arr, iterator) {
  16393. if (arr.forEach) {
  16394. return arr.forEach(iterator);
  16395. }
  16396. for (var i = 0; i < arr.length; i += 1) {
  16397. iterator(arr[i], i, arr);
  16398. }
  16399. };
  16400. var _map = function (arr, iterator) {
  16401. if (arr.map) {
  16402. return arr.map(iterator);
  16403. }
  16404. var results = [];
  16405. _each(arr, function (x, i, a) {
  16406. results.push(iterator(x, i, a));
  16407. });
  16408. return results;
  16409. };
  16410. var _reduce = function (arr, iterator, memo) {
  16411. if (arr.reduce) {
  16412. return arr.reduce(iterator, memo);
  16413. }
  16414. _each(arr, function (x, i, a) {
  16415. memo = iterator(memo, x, i, a);
  16416. });
  16417. return memo;
  16418. };
  16419. var _keys = function (obj) {
  16420. if (Object.keys) {
  16421. return Object.keys(obj);
  16422. }
  16423. var keys = [];
  16424. for (var k in obj) {
  16425. if (obj.hasOwnProperty(k)) {
  16426. keys.push(k);
  16427. }
  16428. }
  16429. return keys;
  16430. };
  16431. //// exported async module functions ////
  16432. //// nextTick implementation with browser-compatible fallback ////
  16433. if (typeof process === 'undefined' || !(process.nextTick)) {
  16434. if (typeof setImmediate === 'function') {
  16435. async.nextTick = function (fn) {
  16436. // not a direct alias for IE10 compatibility
  16437. setImmediate(fn);
  16438. };
  16439. async.setImmediate = async.nextTick;
  16440. }
  16441. else {
  16442. async.nextTick = function (fn) {
  16443. setTimeout(fn, 0);
  16444. };
  16445. async.setImmediate = async.nextTick;
  16446. }
  16447. }
  16448. else {
  16449. async.nextTick = process.nextTick;
  16450. if (typeof setImmediate !== 'undefined') {
  16451. async.setImmediate = function (fn) {
  16452. // not a direct alias for IE10 compatibility
  16453. setImmediate(fn);
  16454. };
  16455. }
  16456. else {
  16457. async.setImmediate = async.nextTick;
  16458. }
  16459. }
  16460. async.each = function (arr, iterator, callback) {
  16461. callback = callback || function () {};
  16462. if (!arr.length) {
  16463. return callback();
  16464. }
  16465. var completed = 0;
  16466. _each(arr, function (x) {
  16467. iterator(x, only_once(done) );
  16468. });
  16469. function done(err) {
  16470. if (err) {
  16471. callback(err);
  16472. callback = function () {};
  16473. }
  16474. else {
  16475. completed += 1;
  16476. if (completed >= arr.length) {
  16477. callback();
  16478. }
  16479. }
  16480. }
  16481. };
  16482. async.forEach = async.each;
  16483. async.eachSeries = function (arr, iterator, callback) {
  16484. callback = callback || function () {};
  16485. if (!arr.length) {
  16486. return callback();
  16487. }
  16488. var completed = 0;
  16489. var iterate = function () {
  16490. iterator(arr[completed], function (err) {
  16491. if (err) {
  16492. callback(err);
  16493. callback = function () {};
  16494. }
  16495. else {
  16496. completed += 1;
  16497. if (completed >= arr.length) {
  16498. callback();
  16499. }
  16500. else {
  16501. iterate();
  16502. }
  16503. }
  16504. });
  16505. };
  16506. iterate();
  16507. };
  16508. async.forEachSeries = async.eachSeries;
  16509. async.eachLimit = function (arr, limit, iterator, callback) {
  16510. var fn = _eachLimit(limit);
  16511. fn.apply(null, [arr, iterator, callback]);
  16512. };
  16513. async.forEachLimit = async.eachLimit;
  16514. var _eachLimit = function (limit) {
  16515. return function (arr, iterator, callback) {
  16516. callback = callback || function () {};
  16517. if (!arr.length || limit <= 0) {
  16518. return callback();
  16519. }
  16520. var completed = 0;
  16521. var started = 0;
  16522. var running = 0;
  16523. (function replenish () {
  16524. if (completed >= arr.length) {
  16525. return callback();
  16526. }
  16527. while (running < limit && started < arr.length) {
  16528. started += 1;
  16529. running += 1;
  16530. iterator(arr[started - 1], function (err) {
  16531. if (err) {
  16532. callback(err);
  16533. callback = function () {};
  16534. }
  16535. else {
  16536. completed += 1;
  16537. running -= 1;
  16538. if (completed >= arr.length) {
  16539. callback();
  16540. }
  16541. else {
  16542. replenish();
  16543. }
  16544. }
  16545. });
  16546. }
  16547. })();
  16548. };
  16549. };
  16550. var doParallel = function (fn) {
  16551. return function () {
  16552. var args = Array.prototype.slice.call(arguments);
  16553. return fn.apply(null, [async.each].concat(args));
  16554. };
  16555. };
  16556. var doParallelLimit = function(limit, fn) {
  16557. return function () {
  16558. var args = Array.prototype.slice.call(arguments);
  16559. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16560. };
  16561. };
  16562. var doSeries = function (fn) {
  16563. return function () {
  16564. var args = Array.prototype.slice.call(arguments);
  16565. return fn.apply(null, [async.eachSeries].concat(args));
  16566. };
  16567. };
  16568. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16569. arr = _map(arr, function (x, i) {
  16570. return {index: i, value: x};
  16571. });
  16572. if (!callback) {
  16573. eachfn(arr, function (x, callback) {
  16574. iterator(x.value, function (err) {
  16575. callback(err);
  16576. });
  16577. });
  16578. } else {
  16579. var results = [];
  16580. eachfn(arr, function (x, callback) {
  16581. iterator(x.value, function (err, v) {
  16582. results[x.index] = v;
  16583. callback(err);
  16584. });
  16585. }, function (err) {
  16586. callback(err, results);
  16587. });
  16588. }
  16589. };
  16590. async.map = doParallel(_asyncMap);
  16591. async.mapSeries = doSeries(_asyncMap);
  16592. async.mapLimit = function (arr, limit, iterator, callback) {
  16593. return _mapLimit(limit)(arr, iterator, callback);
  16594. };
  16595. var _mapLimit = function(limit) {
  16596. return doParallelLimit(limit, _asyncMap);
  16597. };
  16598. // reduce only has a series version, as doing reduce in parallel won't
  16599. // work in many situations.
  16600. async.reduce = function (arr, memo, iterator, callback) {
  16601. async.eachSeries(arr, function (x, callback) {
  16602. iterator(memo, x, function (err, v) {
  16603. memo = v;
  16604. callback(err);
  16605. });
  16606. }, function (err) {
  16607. callback(err, memo);
  16608. });
  16609. };
  16610. // inject alias
  16611. async.inject = async.reduce;
  16612. // foldl alias
  16613. async.foldl = async.reduce;
  16614. async.reduceRight = function (arr, memo, iterator, callback) {
  16615. var reversed = _map(arr, function (x) {
  16616. return x;
  16617. }).reverse();
  16618. async.reduce(reversed, memo, iterator, callback);
  16619. };
  16620. // foldr alias
  16621. async.foldr = async.reduceRight;
  16622. var _filter = function (eachfn, arr, iterator, callback) {
  16623. var results = [];
  16624. arr = _map(arr, function (x, i) {
  16625. return {index: i, value: x};
  16626. });
  16627. eachfn(arr, function (x, callback) {
  16628. iterator(x.value, function (v) {
  16629. if (v) {
  16630. results.push(x);
  16631. }
  16632. callback();
  16633. });
  16634. }, function (err) {
  16635. callback(_map(results.sort(function (a, b) {
  16636. return a.index - b.index;
  16637. }), function (x) {
  16638. return x.value;
  16639. }));
  16640. });
  16641. };
  16642. async.filter = doParallel(_filter);
  16643. async.filterSeries = doSeries(_filter);
  16644. // select alias
  16645. async.select = async.filter;
  16646. async.selectSeries = async.filterSeries;
  16647. var _reject = function (eachfn, arr, iterator, callback) {
  16648. var results = [];
  16649. arr = _map(arr, function (x, i) {
  16650. return {index: i, value: x};
  16651. });
  16652. eachfn(arr, function (x, callback) {
  16653. iterator(x.value, function (v) {
  16654. if (!v) {
  16655. results.push(x);
  16656. }
  16657. callback();
  16658. });
  16659. }, function (err) {
  16660. callback(_map(results.sort(function (a, b) {
  16661. return a.index - b.index;
  16662. }), function (x) {
  16663. return x.value;
  16664. }));
  16665. });
  16666. };
  16667. async.reject = doParallel(_reject);
  16668. async.rejectSeries = doSeries(_reject);
  16669. var _detect = function (eachfn, arr, iterator, main_callback) {
  16670. eachfn(arr, function (x, callback) {
  16671. iterator(x, function (result) {
  16672. if (result) {
  16673. main_callback(x);
  16674. main_callback = function () {};
  16675. }
  16676. else {
  16677. callback();
  16678. }
  16679. });
  16680. }, function (err) {
  16681. main_callback();
  16682. });
  16683. };
  16684. async.detect = doParallel(_detect);
  16685. async.detectSeries = doSeries(_detect);
  16686. async.some = function (arr, iterator, main_callback) {
  16687. async.each(arr, function (x, callback) {
  16688. iterator(x, function (v) {
  16689. if (v) {
  16690. main_callback(true);
  16691. main_callback = function () {};
  16692. }
  16693. callback();
  16694. });
  16695. }, function (err) {
  16696. main_callback(false);
  16697. });
  16698. };
  16699. // any alias
  16700. async.any = async.some;
  16701. async.every = function (arr, iterator, main_callback) {
  16702. async.each(arr, function (x, callback) {
  16703. iterator(x, function (v) {
  16704. if (!v) {
  16705. main_callback(false);
  16706. main_callback = function () {};
  16707. }
  16708. callback();
  16709. });
  16710. }, function (err) {
  16711. main_callback(true);
  16712. });
  16713. };
  16714. // all alias
  16715. async.all = async.every;
  16716. async.sortBy = function (arr, iterator, callback) {
  16717. async.map(arr, function (x, callback) {
  16718. iterator(x, function (err, criteria) {
  16719. if (err) {
  16720. callback(err);
  16721. }
  16722. else {
  16723. callback(null, {value: x, criteria: criteria});
  16724. }
  16725. });
  16726. }, function (err, results) {
  16727. if (err) {
  16728. return callback(err);
  16729. }
  16730. else {
  16731. var fn = function (left, right) {
  16732. var a = left.criteria, b = right.criteria;
  16733. return a < b ? -1 : a > b ? 1 : 0;
  16734. };
  16735. callback(null, _map(results.sort(fn), function (x) {
  16736. return x.value;
  16737. }));
  16738. }
  16739. });
  16740. };
  16741. async.auto = function (tasks, callback) {
  16742. callback = callback || function () {};
  16743. var keys = _keys(tasks);
  16744. var remainingTasks = keys.length
  16745. if (!remainingTasks) {
  16746. return callback();
  16747. }
  16748. var results = {};
  16749. var listeners = [];
  16750. var addListener = function (fn) {
  16751. listeners.unshift(fn);
  16752. };
  16753. var removeListener = function (fn) {
  16754. for (var i = 0; i < listeners.length; i += 1) {
  16755. if (listeners[i] === fn) {
  16756. listeners.splice(i, 1);
  16757. return;
  16758. }
  16759. }
  16760. };
  16761. var taskComplete = function () {
  16762. remainingTasks--
  16763. _each(listeners.slice(0), function (fn) {
  16764. fn();
  16765. });
  16766. };
  16767. addListener(function () {
  16768. if (!remainingTasks) {
  16769. var theCallback = callback;
  16770. // prevent final callback from calling itself if it errors
  16771. callback = function () {};
  16772. theCallback(null, results);
  16773. }
  16774. });
  16775. _each(keys, function (k) {
  16776. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  16777. var taskCallback = function (err) {
  16778. var args = Array.prototype.slice.call(arguments, 1);
  16779. if (args.length <= 1) {
  16780. args = args[0];
  16781. }
  16782. if (err) {
  16783. var safeResults = {};
  16784. _each(_keys(results), function(rkey) {
  16785. safeResults[rkey] = results[rkey];
  16786. });
  16787. safeResults[k] = args;
  16788. callback(err, safeResults);
  16789. // stop subsequent errors hitting callback multiple times
  16790. callback = function () {};
  16791. }
  16792. else {
  16793. results[k] = args;
  16794. async.setImmediate(taskComplete);
  16795. }
  16796. };
  16797. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  16798. var ready = function () {
  16799. return _reduce(requires, function (a, x) {
  16800. return (a && results.hasOwnProperty(x));
  16801. }, true) && !results.hasOwnProperty(k);
  16802. };
  16803. if (ready()) {
  16804. task[task.length - 1](taskCallback, results);
  16805. }
  16806. else {
  16807. var listener = function () {
  16808. if (ready()) {
  16809. removeListener(listener);
  16810. task[task.length - 1](taskCallback, results);
  16811. }
  16812. };
  16813. addListener(listener);
  16814. }
  16815. });
  16816. };
  16817. async.retry = function(times, task, callback) {
  16818. var DEFAULT_TIMES = 5;
  16819. var attempts = [];
  16820. // Use defaults if times not passed
  16821. if (typeof times === 'function') {
  16822. callback = task;
  16823. task = times;
  16824. times = DEFAULT_TIMES;
  16825. }
  16826. // Make sure times is a number
  16827. times = parseInt(times, 10) || DEFAULT_TIMES;
  16828. var wrappedTask = function(wrappedCallback, wrappedResults) {
  16829. var retryAttempt = function(task, finalAttempt) {
  16830. return function(seriesCallback) {
  16831. task(function(err, result){
  16832. seriesCallback(!err || finalAttempt, {err: err, result: result});
  16833. }, wrappedResults);
  16834. };
  16835. };
  16836. while (times) {
  16837. attempts.push(retryAttempt(task, !(times-=1)));
  16838. }
  16839. async.series(attempts, function(done, data){
  16840. data = data[data.length - 1];
  16841. (wrappedCallback || callback)(data.err, data.result);
  16842. });
  16843. }
  16844. // If a callback is passed, run this as a controll flow
  16845. return callback ? wrappedTask() : wrappedTask
  16846. };
  16847. async.waterfall = function (tasks, callback) {
  16848. callback = callback || function () {};
  16849. if (!_isArray(tasks)) {
  16850. var err = new Error('First argument to waterfall must be an array of functions');
  16851. return callback(err);
  16852. }
  16853. if (!tasks.length) {
  16854. return callback();
  16855. }
  16856. var wrapIterator = function (iterator) {
  16857. return function (err) {
  16858. if (err) {
  16859. callback.apply(null, arguments);
  16860. callback = function () {};
  16861. }
  16862. else {
  16863. var args = Array.prototype.slice.call(arguments, 1);
  16864. var next = iterator.next();
  16865. if (next) {
  16866. args.push(wrapIterator(next));
  16867. }
  16868. else {
  16869. args.push(callback);
  16870. }
  16871. async.setImmediate(function () {
  16872. iterator.apply(null, args);
  16873. });
  16874. }
  16875. };
  16876. };
  16877. wrapIterator(async.iterator(tasks))();
  16878. };
  16879. var _parallel = function(eachfn, tasks, callback) {
  16880. callback = callback || function () {};
  16881. if (_isArray(tasks)) {
  16882. eachfn.map(tasks, function (fn, callback) {
  16883. if (fn) {
  16884. fn(function (err) {
  16885. var args = Array.prototype.slice.call(arguments, 1);
  16886. if (args.length <= 1) {
  16887. args = args[0];
  16888. }
  16889. callback.call(null, err, args);
  16890. });
  16891. }
  16892. }, callback);
  16893. }
  16894. else {
  16895. var results = {};
  16896. eachfn.each(_keys(tasks), function (k, callback) {
  16897. tasks[k](function (err) {
  16898. var args = Array.prototype.slice.call(arguments, 1);
  16899. if (args.length <= 1) {
  16900. args = args[0];
  16901. }
  16902. results[k] = args;
  16903. callback(err);
  16904. });
  16905. }, function (err) {
  16906. callback(err, results);
  16907. });
  16908. }
  16909. };
  16910. async.parallel = function (tasks, callback) {
  16911. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16912. };
  16913. async.parallelLimit = function(tasks, limit, callback) {
  16914. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16915. };
  16916. async.series = function (tasks, callback) {
  16917. callback = callback || function () {};
  16918. if (_isArray(tasks)) {
  16919. async.mapSeries(tasks, function (fn, callback) {
  16920. if (fn) {
  16921. fn(function (err) {
  16922. var args = Array.prototype.slice.call(arguments, 1);
  16923. if (args.length <= 1) {
  16924. args = args[0];
  16925. }
  16926. callback.call(null, err, args);
  16927. });
  16928. }
  16929. }, callback);
  16930. }
  16931. else {
  16932. var results = {};
  16933. async.eachSeries(_keys(tasks), function (k, callback) {
  16934. tasks[k](function (err) {
  16935. var args = Array.prototype.slice.call(arguments, 1);
  16936. if (args.length <= 1) {
  16937. args = args[0];
  16938. }
  16939. results[k] = args;
  16940. callback(err);
  16941. });
  16942. }, function (err) {
  16943. callback(err, results);
  16944. });
  16945. }
  16946. };
  16947. async.iterator = function (tasks) {
  16948. var makeCallback = function (index) {
  16949. var fn = function () {
  16950. if (tasks.length) {
  16951. tasks[index].apply(null, arguments);
  16952. }
  16953. return fn.next();
  16954. };
  16955. fn.next = function () {
  16956. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  16957. };
  16958. return fn;
  16959. };
  16960. return makeCallback(0);
  16961. };
  16962. async.apply = function (fn) {
  16963. var args = Array.prototype.slice.call(arguments, 1);
  16964. return function () {
  16965. return fn.apply(
  16966. null, args.concat(Array.prototype.slice.call(arguments))
  16967. );
  16968. };
  16969. };
  16970. var _concat = function (eachfn, arr, fn, callback) {
  16971. var r = [];
  16972. eachfn(arr, function (x, cb) {
  16973. fn(x, function (err, y) {
  16974. r = r.concat(y || []);
  16975. cb(err);
  16976. });
  16977. }, function (err) {
  16978. callback(err, r);
  16979. });
  16980. };
  16981. async.concat = doParallel(_concat);
  16982. async.concatSeries = doSeries(_concat);
  16983. async.whilst = function (test, iterator, callback) {
  16984. if (test()) {
  16985. iterator(function (err) {
  16986. if (err) {
  16987. return callback(err);
  16988. }
  16989. async.whilst(test, iterator, callback);
  16990. });
  16991. }
  16992. else {
  16993. callback();
  16994. }
  16995. };
  16996. async.doWhilst = function (iterator, test, callback) {
  16997. iterator(function (err) {
  16998. if (err) {
  16999. return callback(err);
  17000. }
  17001. var args = Array.prototype.slice.call(arguments, 1);
  17002. if (test.apply(null, args)) {
  17003. async.doWhilst(iterator, test, callback);
  17004. }
  17005. else {
  17006. callback();
  17007. }
  17008. });
  17009. };
  17010. async.until = function (test, iterator, callback) {
  17011. if (!test()) {
  17012. iterator(function (err) {
  17013. if (err) {
  17014. return callback(err);
  17015. }
  17016. async.until(test, iterator, callback);
  17017. });
  17018. }
  17019. else {
  17020. callback();
  17021. }
  17022. };
  17023. async.doUntil = function (iterator, test, callback) {
  17024. iterator(function (err) {
  17025. if (err) {
  17026. return callback(err);
  17027. }
  17028. var args = Array.prototype.slice.call(arguments, 1);
  17029. if (!test.apply(null, args)) {
  17030. async.doUntil(iterator, test, callback);
  17031. }
  17032. else {
  17033. callback();
  17034. }
  17035. });
  17036. };
  17037. async.queue = function (worker, concurrency) {
  17038. if (concurrency === undefined) {
  17039. concurrency = 1;
  17040. }
  17041. function _insert(q, data, pos, callback) {
  17042. if (!q.started){
  17043. q.started = true;
  17044. }
  17045. if (!_isArray(data)) {
  17046. data = [data];
  17047. }
  17048. if(data.length == 0) {
  17049. // call drain immediately if there are no tasks
  17050. return async.setImmediate(function() {
  17051. if (q.drain) {
  17052. q.drain();
  17053. }
  17054. });
  17055. }
  17056. _each(data, function(task) {
  17057. var item = {
  17058. data: task,
  17059. callback: typeof callback === 'function' ? callback : null
  17060. };
  17061. if (pos) {
  17062. q.tasks.unshift(item);
  17063. } else {
  17064. q.tasks.push(item);
  17065. }
  17066. if (q.saturated && q.tasks.length === q.concurrency) {
  17067. q.saturated();
  17068. }
  17069. async.setImmediate(q.process);
  17070. });
  17071. }
  17072. var workers = 0;
  17073. var q = {
  17074. tasks: [],
  17075. concurrency: concurrency,
  17076. saturated: null,
  17077. empty: null,
  17078. drain: null,
  17079. started: false,
  17080. paused: false,
  17081. push: function (data, callback) {
  17082. _insert(q, data, false, callback);
  17083. },
  17084. kill: function () {
  17085. q.drain = null;
  17086. q.tasks = [];
  17087. },
  17088. unshift: function (data, callback) {
  17089. _insert(q, data, true, callback);
  17090. },
  17091. process: function () {
  17092. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17093. var task = q.tasks.shift();
  17094. if (q.empty && q.tasks.length === 0) {
  17095. q.empty();
  17096. }
  17097. workers += 1;
  17098. var next = function () {
  17099. workers -= 1;
  17100. if (task.callback) {
  17101. task.callback.apply(task, arguments);
  17102. }
  17103. if (q.drain && q.tasks.length + workers === 0) {
  17104. q.drain();
  17105. }
  17106. q.process();
  17107. };
  17108. var cb = only_once(next);
  17109. worker(task.data, cb);
  17110. }
  17111. },
  17112. length: function () {
  17113. return q.tasks.length;
  17114. },
  17115. running: function () {
  17116. return workers;
  17117. },
  17118. idle: function() {
  17119. return q.tasks.length + workers === 0;
  17120. },
  17121. pause: function () {
  17122. if (q.paused === true) { return; }
  17123. q.paused = true;
  17124. q.process();
  17125. },
  17126. resume: function () {
  17127. if (q.paused === false) { return; }
  17128. q.paused = false;
  17129. q.process();
  17130. }
  17131. };
  17132. return q;
  17133. };
  17134. async.priorityQueue = function (worker, concurrency) {
  17135. function _compareTasks(a, b){
  17136. return a.priority - b.priority;
  17137. };
  17138. function _binarySearch(sequence, item, compare) {
  17139. var beg = -1,
  17140. end = sequence.length - 1;
  17141. while (beg < end) {
  17142. var mid = beg + ((end - beg + 1) >>> 1);
  17143. if (compare(item, sequence[mid]) >= 0) {
  17144. beg = mid;
  17145. } else {
  17146. end = mid - 1;
  17147. }
  17148. }
  17149. return beg;
  17150. }
  17151. function _insert(q, data, priority, callback) {
  17152. if (!q.started){
  17153. q.started = true;
  17154. }
  17155. if (!_isArray(data)) {
  17156. data = [data];
  17157. }
  17158. if(data.length == 0) {
  17159. // call drain immediately if there are no tasks
  17160. return async.setImmediate(function() {
  17161. if (q.drain) {
  17162. q.drain();
  17163. }
  17164. });
  17165. }
  17166. _each(data, function(task) {
  17167. var item = {
  17168. data: task,
  17169. priority: priority,
  17170. callback: typeof callback === 'function' ? callback : null
  17171. };
  17172. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17173. if (q.saturated && q.tasks.length === q.concurrency) {
  17174. q.saturated();
  17175. }
  17176. async.setImmediate(q.process);
  17177. });
  17178. }
  17179. // Start with a normal queue
  17180. var q = async.queue(worker, concurrency);
  17181. // Override push to accept second parameter representing priority
  17182. q.push = function (data, priority, callback) {
  17183. _insert(q, data, priority, callback);
  17184. };
  17185. // Remove unshift function
  17186. delete q.unshift;
  17187. return q;
  17188. };
  17189. async.cargo = function (worker, payload) {
  17190. var working = false,
  17191. tasks = [];
  17192. var cargo = {
  17193. tasks: tasks,
  17194. payload: payload,
  17195. saturated: null,
  17196. empty: null,
  17197. drain: null,
  17198. drained: true,
  17199. push: function (data, callback) {
  17200. if (!_isArray(data)) {
  17201. data = [data];
  17202. }
  17203. _each(data, function(task) {
  17204. tasks.push({
  17205. data: task,
  17206. callback: typeof callback === 'function' ? callback : null
  17207. });
  17208. cargo.drained = false;
  17209. if (cargo.saturated && tasks.length === payload) {
  17210. cargo.saturated();
  17211. }
  17212. });
  17213. async.setImmediate(cargo.process);
  17214. },
  17215. process: function process() {
  17216. if (working) return;
  17217. if (tasks.length === 0) {
  17218. if(cargo.drain && !cargo.drained) cargo.drain();
  17219. cargo.drained = true;
  17220. return;
  17221. }
  17222. var ts = typeof payload === 'number'
  17223. ? tasks.splice(0, payload)
  17224. : tasks.splice(0, tasks.length);
  17225. var ds = _map(ts, function (task) {
  17226. return task.data;
  17227. });
  17228. if(cargo.empty) cargo.empty();
  17229. working = true;
  17230. worker(ds, function () {
  17231. working = false;
  17232. var args = arguments;
  17233. _each(ts, function (data) {
  17234. if (data.callback) {
  17235. data.callback.apply(null, args);
  17236. }
  17237. });
  17238. process();
  17239. });
  17240. },
  17241. length: function () {
  17242. return tasks.length;
  17243. },
  17244. running: function () {
  17245. return working;
  17246. }
  17247. };
  17248. return cargo;
  17249. };
  17250. var _console_fn = function (name) {
  17251. return function (fn) {
  17252. var args = Array.prototype.slice.call(arguments, 1);
  17253. fn.apply(null, args.concat([function (err) {
  17254. var args = Array.prototype.slice.call(arguments, 1);
  17255. if (typeof console !== 'undefined') {
  17256. if (err) {
  17257. if (console.error) {
  17258. console.error(err);
  17259. }
  17260. }
  17261. else if (console[name]) {
  17262. _each(args, function (x) {
  17263. console[name](x);
  17264. });
  17265. }
  17266. }
  17267. }]));
  17268. };
  17269. };
  17270. async.log = _console_fn('log');
  17271. async.dir = _console_fn('dir');
  17272. /*async.info = _console_fn('info');
  17273. async.warn = _console_fn('warn');
  17274. async.error = _console_fn('error');*/
  17275. async.memoize = function (fn, hasher) {
  17276. var memo = {};
  17277. var queues = {};
  17278. hasher = hasher || function (x) {
  17279. return x;
  17280. };
  17281. var memoized = function () {
  17282. var args = Array.prototype.slice.call(arguments);
  17283. var callback = args.pop();
  17284. var key = hasher.apply(null, args);
  17285. if (key in memo) {
  17286. async.nextTick(function () {
  17287. callback.apply(null, memo[key]);
  17288. });
  17289. }
  17290. else if (key in queues) {
  17291. queues[key].push(callback);
  17292. }
  17293. else {
  17294. queues[key] = [callback];
  17295. fn.apply(null, args.concat([function () {
  17296. memo[key] = arguments;
  17297. var q = queues[key];
  17298. delete queues[key];
  17299. for (var i = 0, l = q.length; i < l; i++) {
  17300. q[i].apply(null, arguments);
  17301. }
  17302. }]));
  17303. }
  17304. };
  17305. memoized.memo = memo;
  17306. memoized.unmemoized = fn;
  17307. return memoized;
  17308. };
  17309. async.unmemoize = function (fn) {
  17310. return function () {
  17311. return (fn.unmemoized || fn).apply(null, arguments);
  17312. };
  17313. };
  17314. async.times = function (count, iterator, callback) {
  17315. var counter = [];
  17316. for (var i = 0; i < count; i++) {
  17317. counter.push(i);
  17318. }
  17319. return async.map(counter, iterator, callback);
  17320. };
  17321. async.timesSeries = function (count, iterator, callback) {
  17322. var counter = [];
  17323. for (var i = 0; i < count; i++) {
  17324. counter.push(i);
  17325. }
  17326. return async.mapSeries(counter, iterator, callback);
  17327. };
  17328. async.seq = function (/* functions... */) {
  17329. var fns = arguments;
  17330. return function () {
  17331. var that = this;
  17332. var args = Array.prototype.slice.call(arguments);
  17333. var callback = args.pop();
  17334. async.reduce(fns, args, function (newargs, fn, cb) {
  17335. fn.apply(that, newargs.concat([function () {
  17336. var err = arguments[0];
  17337. var nextargs = Array.prototype.slice.call(arguments, 1);
  17338. cb(err, nextargs);
  17339. }]))
  17340. },
  17341. function (err, results) {
  17342. callback.apply(that, [err].concat(results));
  17343. });
  17344. };
  17345. };
  17346. async.compose = function (/* functions... */) {
  17347. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17348. };
  17349. var _applyEach = function (eachfn, fns /*args...*/) {
  17350. var go = function () {
  17351. var that = this;
  17352. var args = Array.prototype.slice.call(arguments);
  17353. var callback = args.pop();
  17354. return eachfn(fns, function (fn, cb) {
  17355. fn.apply(that, args.concat([cb]));
  17356. },
  17357. callback);
  17358. };
  17359. if (arguments.length > 2) {
  17360. var args = Array.prototype.slice.call(arguments, 2);
  17361. return go.apply(this, args);
  17362. }
  17363. else {
  17364. return go;
  17365. }
  17366. };
  17367. async.applyEach = doParallel(_applyEach);
  17368. async.applyEachSeries = doSeries(_applyEach);
  17369. async.forever = function (fn, callback) {
  17370. function next(err) {
  17371. if (err) {
  17372. if (callback) {
  17373. return callback(err);
  17374. }
  17375. throw err;
  17376. }
  17377. fn(next);
  17378. }
  17379. next();
  17380. };
  17381. // Node.js
  17382. if (typeof module !== 'undefined' && module.exports) {
  17383. module.exports = async;
  17384. }
  17385. // AMD / RequireJS
  17386. else if (typeof define !== 'undefined' && define.amd) {
  17387. define([], function () {
  17388. return async;
  17389. });
  17390. }
  17391. // included directly via <script> tag
  17392. else {
  17393. root.async = async;
  17394. }
  17395. }());
  17396. }).call(this,require('_process'))
  17397. },{"_process":110}],68:[function(require,module,exports){
  17398. // i18next, v1.7.7
  17399. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17400. // Distributed under MIT license
  17401. // http://i18next.com
  17402. (function() {
  17403. // add indexOf to non ECMA-262 standard compliant browsers
  17404. if (!Array.prototype.indexOf) {
  17405. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17406. "use strict";
  17407. if (this == null) {
  17408. throw new TypeError();
  17409. }
  17410. var t = Object(this);
  17411. var len = t.length >>> 0;
  17412. if (len === 0) {
  17413. return -1;
  17414. }
  17415. var n = 0;
  17416. if (arguments.length > 0) {
  17417. n = Number(arguments[1]);
  17418. if (n != n) { // shortcut for verifying if it's NaN
  17419. n = 0;
  17420. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17421. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17422. }
  17423. }
  17424. if (n >= len) {
  17425. return -1;
  17426. }
  17427. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17428. for (; k < len; k++) {
  17429. if (k in t && t[k] === searchElement) {
  17430. return k;
  17431. }
  17432. }
  17433. return -1;
  17434. }
  17435. }
  17436. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17437. if (!Array.prototype.lastIndexOf) {
  17438. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17439. "use strict";
  17440. if (this == null) {
  17441. throw new TypeError();
  17442. }
  17443. var t = Object(this);
  17444. var len = t.length >>> 0;
  17445. if (len === 0) {
  17446. return -1;
  17447. }
  17448. var n = len;
  17449. if (arguments.length > 1) {
  17450. n = Number(arguments[1]);
  17451. if (n != n) {
  17452. n = 0;
  17453. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17454. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17455. }
  17456. }
  17457. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17458. for (; k >= 0; k--) {
  17459. if (k in t && t[k] === searchElement) {
  17460. return k;
  17461. }
  17462. }
  17463. return -1;
  17464. };
  17465. }
  17466. // Add string trim for IE8.
  17467. if (typeof String.prototype.trim !== 'function') {
  17468. String.prototype.trim = function() {
  17469. return this.replace(/^\s+|\s+$/g, '');
  17470. }
  17471. }
  17472. var root = this
  17473. , $ = root.jQuery || root.Zepto
  17474. , i18n = {}
  17475. , resStore = {}
  17476. , currentLng
  17477. , replacementCounter = 0
  17478. , languages = []
  17479. , initialized = false
  17480. , sync = {};
  17481. // Export the i18next object for **CommonJS**.
  17482. // If we're not in CommonJS, add `i18n` to the
  17483. // global object or to jquery.
  17484. if (typeof module !== 'undefined' && module.exports) {
  17485. if (!$) {
  17486. try {
  17487. $ = require('jquery');
  17488. } catch(e) {
  17489. // just ignore
  17490. }
  17491. }
  17492. if ($) {
  17493. $.i18n = $.i18n || i18n;
  17494. }
  17495. module.exports = i18n;
  17496. } else {
  17497. if ($) {
  17498. $.i18n = $.i18n || i18n;
  17499. }
  17500. root.i18n = root.i18n || i18n;
  17501. }
  17502. sync = {
  17503. load: function(lngs, options, cb) {
  17504. if (options.useLocalStorage) {
  17505. sync._loadLocal(lngs, options, function(err, store) {
  17506. var missingLngs = [];
  17507. for (var i = 0, len = lngs.length; i < len; i++) {
  17508. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17509. }
  17510. if (missingLngs.length > 0) {
  17511. sync._fetch(missingLngs, options, function(err, fetched) {
  17512. f.extend(store, fetched);
  17513. sync._storeLocal(fetched);
  17514. cb(null, store);
  17515. });
  17516. } else {
  17517. cb(null, store);
  17518. }
  17519. });
  17520. } else {
  17521. sync._fetch(lngs, options, function(err, store){
  17522. cb(null, store);
  17523. });
  17524. }
  17525. },
  17526. _loadLocal: function(lngs, options, cb) {
  17527. var store = {}
  17528. , nowMS = new Date().getTime();
  17529. if(window.localStorage) {
  17530. var todo = lngs.length;
  17531. f.each(lngs, function(key, lng) {
  17532. var local = window.localStorage.getItem('res_' + lng);
  17533. if (local) {
  17534. local = JSON.parse(local);
  17535. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17536. store[lng] = local;
  17537. }
  17538. }
  17539. todo--; // wait for all done befor callback
  17540. if (todo === 0) cb(null, store);
  17541. });
  17542. }
  17543. },
  17544. _storeLocal: function(store) {
  17545. if(window.localStorage) {
  17546. for (var m in store) {
  17547. store[m].i18nStamp = new Date().getTime();
  17548. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17549. }
  17550. }
  17551. return;
  17552. },
  17553. _fetch: function(lngs, options, cb) {
  17554. var ns = options.ns
  17555. , store = {};
  17556. if (!options.dynamicLoad) {
  17557. var todo = ns.namespaces.length * lngs.length
  17558. , errors;
  17559. // load each file individual
  17560. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17561. f.each(lngs, function(lngIndex, lngValue) {
  17562. // Call this once our translation has returned.
  17563. var loadComplete = function(err, data) {
  17564. if (err) {
  17565. errors = errors || [];
  17566. errors.push(err);
  17567. }
  17568. store[lngValue] = store[lngValue] || {};
  17569. store[lngValue][nsValue] = data;
  17570. todo--; // wait for all done befor callback
  17571. if (todo === 0) cb(errors, store);
  17572. };
  17573. if(typeof options.customLoad == 'function'){
  17574. // Use the specified custom callback.
  17575. options.customLoad(lngValue, nsValue, options, loadComplete);
  17576. } else {
  17577. //~ // Use our inbuilt sync.
  17578. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17579. }
  17580. });
  17581. });
  17582. } else {
  17583. // Call this once our translation has returned.
  17584. var loadComplete = function(err, data) {
  17585. cb(null, data);
  17586. };
  17587. if(typeof options.customLoad == 'function'){
  17588. // Use the specified custom callback.
  17589. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17590. } else {
  17591. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17592. // load all needed stuff once
  17593. f.ajax({
  17594. url: url,
  17595. success: function(data, status, xhr) {
  17596. f.log('loaded: ' + url);
  17597. loadComplete(null, data);
  17598. },
  17599. error : function(xhr, status, error) {
  17600. f.log('failed loading: ' + url);
  17601. loadComplete('failed loading resource.json error: ' + error);
  17602. },
  17603. dataType: "json",
  17604. async : options.getAsync
  17605. });
  17606. }
  17607. }
  17608. },
  17609. _fetchOne: function(lng, ns, options, done) {
  17610. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17611. f.ajax({
  17612. url: url,
  17613. success: function(data, status, xhr) {
  17614. f.log('loaded: ' + url);
  17615. done(null, data);
  17616. },
  17617. error : function(xhr, status, error) {
  17618. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17619. // file loaded but invalid json, stop waste time !
  17620. f.error('There is a typo in: ' + url);
  17621. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17622. f.log('Does not exist: ' + url);
  17623. } else {
  17624. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17625. f.log(theStatus + ' when loading ' + url);
  17626. }
  17627. done(error, {});
  17628. },
  17629. dataType: "json",
  17630. async : options.getAsync
  17631. });
  17632. },
  17633. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17634. var payload = {};
  17635. payload[key] = defaultValue;
  17636. var urls = [];
  17637. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17638. for (var i = 0; i < o.fallbackLng.length; i++) {
  17639. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17640. }
  17641. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17642. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17643. } else if (o.sendMissingTo === 'all') {
  17644. for (var i = 0, l = lngs.length; i < l; i++) {
  17645. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17646. }
  17647. }
  17648. for (var y = 0, len = urls.length; y < len; y++) {
  17649. var item = urls[y];
  17650. f.ajax({
  17651. url: item.url,
  17652. type: o.sendType,
  17653. data: payload,
  17654. success: function(data, status, xhr) {
  17655. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17656. // add key to resStore
  17657. var keys = key.split('.');
  17658. var x = 0;
  17659. var value = resStore[item.lng][ns];
  17660. while (keys[x]) {
  17661. if (x === keys.length - 1) {
  17662. value = value[keys[x]] = defaultValue;
  17663. } else {
  17664. value = value[keys[x]] = value[keys[x]] || {};
  17665. }
  17666. x++;
  17667. }
  17668. },
  17669. error : function(xhr, status, error) {
  17670. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17671. },
  17672. dataType: "json",
  17673. async : o.postAsync
  17674. });
  17675. }
  17676. },
  17677. reload: reload
  17678. };
  17679. // defaults
  17680. var o = {
  17681. lng: undefined,
  17682. load: 'all',
  17683. preload: [],
  17684. lowerCaseLng: false,
  17685. returnObjectTrees: false,
  17686. fallbackLng: ['dev'],
  17687. fallbackNS: [],
  17688. detectLngQS: 'setLng',
  17689. detectLngFromLocalStorage: false,
  17690. ns: 'translation',
  17691. fallbackOnNull: true,
  17692. fallbackOnEmpty: false,
  17693. fallbackToDefaultNS: false,
  17694. nsseparator: ':',
  17695. keyseparator: '.',
  17696. selectorAttr: 'data-i18n',
  17697. debug: false,
  17698. resGetPath: 'locales/__lng__/__ns__.json',
  17699. resPostPath: 'locales/add/__lng__/__ns__',
  17700. getAsync: true,
  17701. postAsync: true,
  17702. resStore: undefined,
  17703. useLocalStorage: false,
  17704. localStorageExpirationTime: 7*24*60*60*1000,
  17705. dynamicLoad: false,
  17706. sendMissing: false,
  17707. sendMissingTo: 'fallback', // current | all
  17708. sendType: 'POST',
  17709. interpolationPrefix: '__',
  17710. interpolationSuffix: '__',
  17711. defaultVariables: false,
  17712. reusePrefix: '$t(',
  17713. reuseSuffix: ')',
  17714. pluralSuffix: '_plural',
  17715. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17716. contextNotFound: ['context_not_found', Math.random()].join(''),
  17717. escapeInterpolation: false,
  17718. indefiniteSuffix: '_indefinite',
  17719. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17720. setJqueryExt: true,
  17721. defaultValueFromContent: true,
  17722. useDataAttrOptions: false,
  17723. cookieExpirationTime: undefined,
  17724. useCookie: true,
  17725. cookieName: 'i18next',
  17726. cookieDomain: undefined,
  17727. objectTreeKeyHandler: undefined,
  17728. postProcess: undefined,
  17729. parseMissingKey: undefined,
  17730. missingKeyHandler: sync.postMissing,
  17731. shortcutFunction: 'sprintf' // or: defaultValue
  17732. };
  17733. function _extend(target, source) {
  17734. if (!source || typeof source === 'function') {
  17735. return target;
  17736. }
  17737. for (var attr in source) { target[attr] = source[attr]; }
  17738. return target;
  17739. }
  17740. function _deepExtend(target, source) {
  17741. for (var prop in source)
  17742. if (prop in target)
  17743. _deepExtend(target[prop], source[prop]);
  17744. else
  17745. target[prop] = source[prop];
  17746. return target;
  17747. }
  17748. function _each(object, callback, args) {
  17749. var name, i = 0,
  17750. length = object.length,
  17751. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17752. if (args) {
  17753. if (isObj) {
  17754. for (name in object) {
  17755. if (callback.apply(object[name], args) === false) {
  17756. break;
  17757. }
  17758. }
  17759. } else {
  17760. for ( ; i < length; ) {
  17761. if (callback.apply(object[i++], args) === false) {
  17762. break;
  17763. }
  17764. }
  17765. }
  17766. // A special, fast, case for the most common use of each
  17767. } else {
  17768. if (isObj) {
  17769. for (name in object) {
  17770. if (callback.call(object[name], name, object[name]) === false) {
  17771. break;
  17772. }
  17773. }
  17774. } else {
  17775. for ( ; i < length; ) {
  17776. if (callback.call(object[i], i, object[i++]) === false) {
  17777. break;
  17778. }
  17779. }
  17780. }
  17781. }
  17782. return object;
  17783. }
  17784. var _entityMap = {
  17785. "&": "&amp;",
  17786. "<": "&lt;",
  17787. ">": "&gt;",
  17788. '"': '&quot;',
  17789. "'": '&#39;',
  17790. "/": '&#x2F;'
  17791. };
  17792. function _escape(data) {
  17793. if (typeof data === 'string') {
  17794. return data.replace(/[&<>"'\/]/g, function (s) {
  17795. return _entityMap[s];
  17796. });
  17797. }else{
  17798. return data;
  17799. }
  17800. }
  17801. function _ajax(options) {
  17802. // v0.5.0 of https://github.com/goloroden/http.js
  17803. var getXhr = function (callback) {
  17804. // Use the native XHR object if the browser supports it.
  17805. if (window.XMLHttpRequest) {
  17806. return callback(null, new XMLHttpRequest());
  17807. } else if (window.ActiveXObject) {
  17808. // In Internet Explorer check for ActiveX versions of the XHR object.
  17809. try {
  17810. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  17811. } catch (e) {
  17812. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  17813. }
  17814. }
  17815. // If no XHR support was found, throw an error.
  17816. return callback(new Error());
  17817. };
  17818. var encodeUsingUrlEncoding = function (data) {
  17819. if(typeof data === 'string') {
  17820. return data;
  17821. }
  17822. var result = [];
  17823. for(var dataItem in data) {
  17824. if(data.hasOwnProperty(dataItem)) {
  17825. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  17826. }
  17827. }
  17828. return result.join('&');
  17829. };
  17830. var utf8 = function (text) {
  17831. text = text.replace(/\r\n/g, '\n');
  17832. var result = '';
  17833. for(var i = 0; i < text.length; i++) {
  17834. var c = text.charCodeAt(i);
  17835. if(c < 128) {
  17836. result += String.fromCharCode(c);
  17837. } else if((c > 127) && (c < 2048)) {
  17838. result += String.fromCharCode((c >> 6) | 192);
  17839. result += String.fromCharCode((c & 63) | 128);
  17840. } else {
  17841. result += String.fromCharCode((c >> 12) | 224);
  17842. result += String.fromCharCode(((c >> 6) & 63) | 128);
  17843. result += String.fromCharCode((c & 63) | 128);
  17844. }
  17845. }
  17846. return result;
  17847. };
  17848. var base64 = function (text) {
  17849. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17850. text = utf8(text);
  17851. var result = '',
  17852. chr1, chr2, chr3,
  17853. enc1, enc2, enc3, enc4,
  17854. i = 0;
  17855. do {
  17856. chr1 = text.charCodeAt(i++);
  17857. chr2 = text.charCodeAt(i++);
  17858. chr3 = text.charCodeAt(i++);
  17859. enc1 = chr1 >> 2;
  17860. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  17861. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  17862. enc4 = chr3 & 63;
  17863. if(isNaN(chr2)) {
  17864. enc3 = enc4 = 64;
  17865. } else if(isNaN(chr3)) {
  17866. enc4 = 64;
  17867. }
  17868. result +=
  17869. keyStr.charAt(enc1) +
  17870. keyStr.charAt(enc2) +
  17871. keyStr.charAt(enc3) +
  17872. keyStr.charAt(enc4);
  17873. chr1 = chr2 = chr3 = '';
  17874. enc1 = enc2 = enc3 = enc4 = '';
  17875. } while(i < text.length);
  17876. return result;
  17877. };
  17878. var mergeHeaders = function () {
  17879. // Use the first header object as base.
  17880. var result = arguments[0];
  17881. // Iterate through the remaining header objects and add them.
  17882. for(var i = 1; i < arguments.length; i++) {
  17883. var currentHeaders = arguments[i];
  17884. for(var header in currentHeaders) {
  17885. if(currentHeaders.hasOwnProperty(header)) {
  17886. result[header] = currentHeaders[header];
  17887. }
  17888. }
  17889. }
  17890. // Return the merged headers.
  17891. return result;
  17892. };
  17893. var ajax = function (method, url, options, callback) {
  17894. // Adjust parameters.
  17895. if(typeof options === 'function') {
  17896. callback = options;
  17897. options = {};
  17898. }
  17899. // Set default parameter values.
  17900. options.cache = options.cache || false;
  17901. options.data = options.data || {};
  17902. options.headers = options.headers || {};
  17903. options.jsonp = options.jsonp || false;
  17904. options.async = options.async === undefined ? true : options.async;
  17905. // Merge the various header objects.
  17906. var headers = mergeHeaders({
  17907. 'accept': '*/*',
  17908. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  17909. }, ajax.headers, options.headers);
  17910. // Encode the data according to the content-type.
  17911. var payload;
  17912. if (headers['content-type'] === 'application/json') {
  17913. payload = JSON.stringify(options.data);
  17914. } else {
  17915. payload = encodeUsingUrlEncoding(options.data);
  17916. }
  17917. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17918. // if neccessary.
  17919. if(method === 'GET') {
  17920. // Setup the query string.
  17921. var queryString = [];
  17922. if(payload) {
  17923. queryString.push(payload);
  17924. payload = null;
  17925. }
  17926. // Handle caching.
  17927. if(!options.cache) {
  17928. queryString.push('_=' + (new Date()).getTime());
  17929. }
  17930. // If neccessary prepare the query string for a JSONP call.
  17931. if(options.jsonp) {
  17932. queryString.push('callback=' + options.jsonp);
  17933. queryString.push('jsonp=' + options.jsonp);
  17934. }
  17935. // Merge the query string and attach it to the url.
  17936. queryString = queryString.join('&');
  17937. if (queryString.length > 1) {
  17938. if (url.indexOf('?') > -1) {
  17939. url += '&' + queryString;
  17940. } else {
  17941. url += '?' + queryString;
  17942. }
  17943. }
  17944. // Make a JSONP call if neccessary.
  17945. if(options.jsonp) {
  17946. var head = document.getElementsByTagName('head')[0];
  17947. var script = document.createElement('script');
  17948. script.type = 'text/javascript';
  17949. script.src = url;
  17950. head.appendChild(script);
  17951. return;
  17952. }
  17953. }
  17954. // Since we got here, it is no JSONP request, so make a normal XHR request.
  17955. getXhr(function (err, xhr) {
  17956. if(err) return callback(err);
  17957. // Open the request.
  17958. xhr.open(method, url, options.async);
  17959. // Set the request headers.
  17960. for(var header in headers) {
  17961. if(headers.hasOwnProperty(header)) {
  17962. xhr.setRequestHeader(header, headers[header]);
  17963. }
  17964. }
  17965. // Handle the request events.
  17966. xhr.onreadystatechange = function () {
  17967. if(xhr.readyState === 4) {
  17968. var data = xhr.responseText || '';
  17969. // If no callback is given, return.
  17970. if(!callback) {
  17971. return;
  17972. }
  17973. // Return an object that provides access to the data as text and JSON.
  17974. callback(xhr.status, {
  17975. text: function () {
  17976. return data;
  17977. },
  17978. json: function () {
  17979. try {
  17980. return JSON.parse(data)
  17981. } catch (e) {
  17982. f.error('Can not parse JSON. URL: ' + url);
  17983. return {};
  17984. }
  17985. }
  17986. });
  17987. }
  17988. };
  17989. // Actually send the XHR request.
  17990. xhr.send(payload);
  17991. });
  17992. };
  17993. // Define the external interface.
  17994. var http = {
  17995. authBasic: function (username, password) {
  17996. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  17997. },
  17998. connect: function (url, options, callback) {
  17999. return ajax('CONNECT', url, options, callback);
  18000. },
  18001. del: function (url, options, callback) {
  18002. return ajax('DELETE', url, options, callback);
  18003. },
  18004. get: function (url, options, callback) {
  18005. return ajax('GET', url, options, callback);
  18006. },
  18007. head: function (url, options, callback) {
  18008. return ajax('HEAD', url, options, callback);
  18009. },
  18010. headers: function (headers) {
  18011. ajax.headers = headers || {};
  18012. },
  18013. isAllowed: function (url, verb, callback) {
  18014. this.options(url, function (status, data) {
  18015. callback(data.text().indexOf(verb) !== -1);
  18016. });
  18017. },
  18018. options: function (url, options, callback) {
  18019. return ajax('OPTIONS', url, options, callback);
  18020. },
  18021. patch: function (url, options, callback) {
  18022. return ajax('PATCH', url, options, callback);
  18023. },
  18024. post: function (url, options, callback) {
  18025. return ajax('POST', url, options, callback);
  18026. },
  18027. put: function (url, options, callback) {
  18028. return ajax('PUT', url, options, callback);
  18029. },
  18030. trace: function (url, options, callback) {
  18031. return ajax('TRACE', url, options, callback);
  18032. }
  18033. };
  18034. var methode = options.type ? options.type.toLowerCase() : 'get';
  18035. http[methode](options.url, options, function (status, data) {
  18036. // file: protocol always gives status code 0, so check for data
  18037. if (status === 200 || (status === 0 && data.text())) {
  18038. options.success(data.json(), status, null);
  18039. } else {
  18040. options.error(data.text(), status, null);
  18041. }
  18042. });
  18043. }
  18044. var _cookie = {
  18045. create: function(name,value,minutes,domain) {
  18046. var expires;
  18047. if (minutes) {
  18048. var date = new Date();
  18049. date.setTime(date.getTime()+(minutes*60*1000));
  18050. expires = "; expires="+date.toGMTString();
  18051. }
  18052. else expires = "";
  18053. domain = (domain)? "domain="+domain+";" : "";
  18054. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18055. },
  18056. read: function(name) {
  18057. var nameEQ = name + "=";
  18058. var ca = document.cookie.split(';');
  18059. for(var i=0;i < ca.length;i++) {
  18060. var c = ca[i];
  18061. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18062. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18063. }
  18064. return null;
  18065. },
  18066. remove: function(name) {
  18067. this.create(name,"",-1);
  18068. }
  18069. };
  18070. var cookie_noop = {
  18071. create: function(name,value,minutes,domain) {},
  18072. read: function(name) { return null; },
  18073. remove: function(name) {}
  18074. };
  18075. // move dependent functions to a container so that
  18076. // they can be overriden easier in no jquery environment (node.js)
  18077. var f = {
  18078. extend: $ ? $.extend : _extend,
  18079. deepExtend: _deepExtend,
  18080. each: $ ? $.each : _each,
  18081. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18082. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18083. detectLanguage: detectLanguage,
  18084. escape: _escape,
  18085. log: function(str) {
  18086. if (o.debug && typeof console !== "undefined") console.log(str);
  18087. },
  18088. error: function(str) {
  18089. if (typeof console !== "undefined") console.error(str);
  18090. },
  18091. getCountyIndexOfLng: function(lng) {
  18092. var lng_index = 0;
  18093. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18094. return lng_index;
  18095. },
  18096. toLanguages: function(lng) {
  18097. var log = this.log;
  18098. function applyCase(l) {
  18099. var ret = l;
  18100. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18101. var parts = l.split('-');
  18102. ret = o.lowerCaseLng ?
  18103. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18104. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18105. } else {
  18106. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18107. }
  18108. return ret;
  18109. }
  18110. var languages = [];
  18111. var whitelist = o.lngWhitelist || false;
  18112. var addLanguage = function(language){
  18113. //reject langs not whitelisted
  18114. if(!whitelist || whitelist.indexOf(language) > -1){
  18115. languages.push(language);
  18116. }else{
  18117. log('rejecting non-whitelisted language: ' + language);
  18118. }
  18119. };
  18120. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18121. var parts = lng.split('-');
  18122. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18123. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18124. } else {
  18125. addLanguage(applyCase(lng));
  18126. }
  18127. for (var i = 0; i < o.fallbackLng.length; i++) {
  18128. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18129. }
  18130. return languages;
  18131. },
  18132. regexEscape: function(str) {
  18133. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18134. },
  18135. regexReplacementEscape: function(strOrFn) {
  18136. if (typeof strOrFn === 'string') {
  18137. return strOrFn.replace(/\$/g, "$$$$");
  18138. } else {
  18139. return strOrFn;
  18140. }
  18141. },
  18142. localStorage: {
  18143. setItem: function(key, value) {
  18144. if (window.localStorage) {
  18145. try {
  18146. window.localStorage.setItem(key, value);
  18147. } catch (e) {
  18148. f.log('failed to set value for key "' + key + '" to localStorage.');
  18149. }
  18150. }
  18151. }
  18152. }
  18153. };
  18154. function init(options, cb) {
  18155. if (typeof options === 'function') {
  18156. cb = options;
  18157. options = {};
  18158. }
  18159. options = options || {};
  18160. // override defaults with passed in options
  18161. f.extend(o, options);
  18162. delete o.fixLng; /* passed in each time */
  18163. // override functions: .log(), .detectLanguage(), etc
  18164. if (o.functions) {
  18165. delete o.functions;
  18166. f.extend(f, options.functions);
  18167. }
  18168. // create namespace object if namespace is passed in as string
  18169. if (typeof o.ns == 'string') {
  18170. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18171. }
  18172. // fallback namespaces
  18173. if (typeof o.fallbackNS == 'string') {
  18174. o.fallbackNS = [o.fallbackNS];
  18175. }
  18176. // fallback languages
  18177. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18178. o.fallbackLng = [o.fallbackLng];
  18179. }
  18180. // escape prefix/suffix
  18181. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18182. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18183. if (!o.lng) o.lng = f.detectLanguage();
  18184. languages = f.toLanguages(o.lng);
  18185. currentLng = languages[0];
  18186. f.log('currentLng set to: ' + currentLng);
  18187. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18188. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18189. }
  18190. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18191. f.localStorage.setItem('i18next_lng', currentLng);
  18192. }
  18193. var lngTranslate = translate;
  18194. if (options.fixLng) {
  18195. lngTranslate = function(key, options) {
  18196. options = options || {};
  18197. options.lng = options.lng || lngTranslate.lng;
  18198. return translate(key, options);
  18199. };
  18200. lngTranslate.lng = currentLng;
  18201. }
  18202. pluralExtensions.setCurrentLng(currentLng);
  18203. // add JQuery extensions
  18204. if ($ && o.setJqueryExt) addJqueryFunct();
  18205. // jQuery deferred
  18206. var deferred;
  18207. if ($ && $.Deferred) {
  18208. deferred = $.Deferred();
  18209. }
  18210. // return immidiatly if res are passed in
  18211. if (o.resStore) {
  18212. resStore = o.resStore;
  18213. initialized = true;
  18214. if (cb) cb(lngTranslate);
  18215. if (deferred) deferred.resolve(lngTranslate);
  18216. if (deferred) return deferred.promise();
  18217. return;
  18218. }
  18219. // languages to load
  18220. var lngsToLoad = f.toLanguages(o.lng);
  18221. if (typeof o.preload === 'string') o.preload = [o.preload];
  18222. for (var i = 0, l = o.preload.length; i < l; i++) {
  18223. var pres = f.toLanguages(o.preload[i]);
  18224. for (var y = 0, len = pres.length; y < len; y++) {
  18225. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18226. lngsToLoad.push(pres[y]);
  18227. }
  18228. }
  18229. }
  18230. // else load them
  18231. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18232. resStore = store;
  18233. initialized = true;
  18234. if (cb) cb(lngTranslate);
  18235. if (deferred) deferred.resolve(lngTranslate);
  18236. });
  18237. if (deferred) return deferred.promise();
  18238. }
  18239. function preload(lngs, cb) {
  18240. if (typeof lngs === 'string') lngs = [lngs];
  18241. for (var i = 0, l = lngs.length; i < l; i++) {
  18242. if (o.preload.indexOf(lngs[i]) < 0) {
  18243. o.preload.push(lngs[i]);
  18244. }
  18245. }
  18246. return init(cb);
  18247. }
  18248. function addResourceBundle(lng, ns, resources, deep) {
  18249. if (typeof ns !== 'string') {
  18250. resources = ns;
  18251. ns = o.ns.defaultNs;
  18252. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18253. o.ns.namespaces.push(ns);
  18254. }
  18255. resStore[lng] = resStore[lng] || {};
  18256. resStore[lng][ns] = resStore[lng][ns] || {};
  18257. if (deep) {
  18258. f.deepExtend(resStore[lng][ns], resources);
  18259. } else {
  18260. f.extend(resStore[lng][ns], resources);
  18261. }
  18262. }
  18263. function hasResourceBundle(lng, ns) {
  18264. if (typeof ns !== 'string') {
  18265. ns = o.ns.defaultNs;
  18266. }
  18267. resStore[lng] = resStore[lng] || {};
  18268. var res = resStore[lng][ns] || {};
  18269. var hasValues = false;
  18270. for(var prop in res) {
  18271. if (res.hasOwnProperty(prop)) {
  18272. hasValues = true;
  18273. }
  18274. }
  18275. return hasValues;
  18276. }
  18277. function removeResourceBundle(lng, ns) {
  18278. if (typeof ns !== 'string') {
  18279. ns = o.ns.defaultNs;
  18280. }
  18281. resStore[lng] = resStore[lng] || {};
  18282. resStore[lng][ns] = {};
  18283. }
  18284. function addResource(lng, ns, key, value) {
  18285. if (typeof ns !== 'string') {
  18286. resource = ns;
  18287. ns = o.ns.defaultNs;
  18288. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18289. o.ns.namespaces.push(ns);
  18290. }
  18291. resStore[lng] = resStore[lng] || {};
  18292. resStore[lng][ns] = resStore[lng][ns] || {};
  18293. var keys = key.split(o.keyseparator);
  18294. var x = 0;
  18295. var node = resStore[lng][ns];
  18296. var origRef = node;
  18297. while (keys[x]) {
  18298. if (x == keys.length - 1)
  18299. node[keys[x]] = value;
  18300. else {
  18301. if (node[keys[x]] == null)
  18302. node[keys[x]] = {};
  18303. node = node[keys[x]];
  18304. }
  18305. x++;
  18306. }
  18307. }
  18308. function addResources(lng, ns, resources) {
  18309. if (typeof ns !== 'string') {
  18310. resource = ns;
  18311. ns = o.ns.defaultNs;
  18312. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18313. o.ns.namespaces.push(ns);
  18314. }
  18315. for (var m in resources) {
  18316. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18317. }
  18318. }
  18319. function setDefaultNamespace(ns) {
  18320. o.ns.defaultNs = ns;
  18321. }
  18322. function loadNamespace(namespace, cb) {
  18323. loadNamespaces([namespace], cb);
  18324. }
  18325. function loadNamespaces(namespaces, cb) {
  18326. var opts = {
  18327. dynamicLoad: o.dynamicLoad,
  18328. resGetPath: o.resGetPath,
  18329. getAsync: o.getAsync,
  18330. customLoad: o.customLoad,
  18331. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18332. };
  18333. // languages to load
  18334. var lngsToLoad = f.toLanguages(o.lng);
  18335. if (typeof o.preload === 'string') o.preload = [o.preload];
  18336. for (var i = 0, l = o.preload.length; i < l; i++) {
  18337. var pres = f.toLanguages(o.preload[i]);
  18338. for (var y = 0, len = pres.length; y < len; y++) {
  18339. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18340. lngsToLoad.push(pres[y]);
  18341. }
  18342. }
  18343. }
  18344. // check if we have to load
  18345. var lngNeedLoad = [];
  18346. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18347. var needLoad = false;
  18348. var resSet = resStore[lngsToLoad[a]];
  18349. if (resSet) {
  18350. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18351. if (!resSet[namespaces[b]]) needLoad = true;
  18352. }
  18353. } else {
  18354. needLoad = true;
  18355. }
  18356. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18357. }
  18358. if (lngNeedLoad.length) {
  18359. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18360. var todo = namespaces.length * lngNeedLoad.length;
  18361. // load each file individual
  18362. f.each(namespaces, function(nsIndex, nsValue) {
  18363. // append namespace to namespace array
  18364. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18365. o.ns.namespaces.push(nsValue);
  18366. }
  18367. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18368. resStore[lngValue] = resStore[lngValue] || {};
  18369. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18370. todo--; // wait for all done befor callback
  18371. if (todo === 0 && cb) {
  18372. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18373. cb();
  18374. }
  18375. });
  18376. });
  18377. });
  18378. } else {
  18379. if (cb) cb();
  18380. }
  18381. }
  18382. function setLng(lng, options, cb) {
  18383. if (typeof options === 'function') {
  18384. cb = options;
  18385. options = {};
  18386. } else if (!options) {
  18387. options = {};
  18388. }
  18389. options.lng = lng;
  18390. return init(options, cb);
  18391. }
  18392. function lng() {
  18393. return currentLng;
  18394. }
  18395. function reload(cb) {
  18396. resStore = {};
  18397. setLng(currentLng, cb);
  18398. }
  18399. function addJqueryFunct() {
  18400. // $.t shortcut
  18401. $.t = $.t || translate;
  18402. function parse(ele, key, options) {
  18403. if (key.length === 0) return;
  18404. var attr = 'text';
  18405. if (key.indexOf('[') === 0) {
  18406. var parts = key.split(']');
  18407. key = parts[1];
  18408. attr = parts[0].substr(1, parts[0].length-1);
  18409. }
  18410. if (key.indexOf(';') === key.length-1) {
  18411. key = key.substr(0, key.length-2);
  18412. }
  18413. var optionsToUse;
  18414. if (attr === 'html') {
  18415. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18416. ele.html($.t(key, optionsToUse));
  18417. } else if (attr === 'text') {
  18418. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18419. ele.text($.t(key, optionsToUse));
  18420. } else if (attr === 'prepend') {
  18421. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18422. ele.prepend($.t(key, optionsToUse));
  18423. } else if (attr === 'append') {
  18424. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18425. ele.append($.t(key, optionsToUse));
  18426. } else if (attr.indexOf("data-") === 0) {
  18427. var dataAttr = attr.substr(("data-").length);
  18428. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18429. var translated = $.t(key, optionsToUse);
  18430. //we change into the data cache
  18431. ele.data(dataAttr, translated);
  18432. //we change into the dom
  18433. ele.attr(attr, translated);
  18434. } else {
  18435. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18436. ele.attr(attr, $.t(key, optionsToUse));
  18437. }
  18438. }
  18439. function localize(ele, options) {
  18440. var key = ele.attr(o.selectorAttr);
  18441. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18442. if (!key) return;
  18443. var target = ele
  18444. , targetSelector = ele.data("i18n-target");
  18445. if (targetSelector) {
  18446. target = ele.find(targetSelector) || ele;
  18447. }
  18448. if (!options && o.useDataAttrOptions === true) {
  18449. options = ele.data("i18n-options");
  18450. }
  18451. options = options || {};
  18452. if (key.indexOf(';') >= 0) {
  18453. var keys = key.split(';');
  18454. $.each(keys, function(m, k) {
  18455. if (k !== '') parse(target, k, options);
  18456. });
  18457. } else {
  18458. parse(target, key, options);
  18459. }
  18460. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18461. }
  18462. // fn
  18463. $.fn.i18n = function (options) {
  18464. return this.each(function() {
  18465. // localize element itself
  18466. localize($(this), options);
  18467. // localize childs
  18468. var elements = $(this).find('[' + o.selectorAttr + ']');
  18469. elements.each(function() {
  18470. localize($(this), options);
  18471. });
  18472. });
  18473. };
  18474. }
  18475. function applyReplacement(str, replacementHash, nestedKey, options) {
  18476. if (!str) return str;
  18477. options = options || replacementHash; // first call uses replacement hash combined with options
  18478. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18479. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18480. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18481. , unEscapingSuffix = 'HTML'+suffix;
  18482. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18483. f.each(hash, function(key, value) {
  18484. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18485. if (typeof value === 'object' && value !== null) {
  18486. str = applyReplacement(str, value, nextKey, options);
  18487. } else {
  18488. if (options.escapeInterpolation || o.escapeInterpolation) {
  18489. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18490. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18491. } else {
  18492. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18493. }
  18494. // str = options.escapeInterpolation;
  18495. }
  18496. });
  18497. return str;
  18498. }
  18499. // append it to functions
  18500. f.applyReplacement = applyReplacement;
  18501. function applyReuse(translated, options) {
  18502. var comma = ',';
  18503. var options_open = '{';
  18504. var options_close = '}';
  18505. var opts = f.extend({}, options);
  18506. delete opts.postProcess;
  18507. while (translated.indexOf(o.reusePrefix) != -1) {
  18508. replacementCounter++;
  18509. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18510. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18511. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18512. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18513. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18514. if (index_of_end_of_closing <= index_of_opening) {
  18515. f.error('there is an missing closing in following translation value', translated);
  18516. return '';
  18517. }
  18518. if (token_without_symbols.indexOf(comma) != -1) {
  18519. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18520. 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) {
  18521. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18522. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18523. try {
  18524. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18525. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18526. } catch (e) {
  18527. }
  18528. }
  18529. }
  18530. var translated_token = _translate(token_without_symbols, opts);
  18531. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18532. }
  18533. return translated;
  18534. }
  18535. function hasContext(options) {
  18536. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18537. }
  18538. function needsPlural(options, lng) {
  18539. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18540. }
  18541. function needsIndefiniteArticle(options) {
  18542. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18543. }
  18544. function exists(key, options) {
  18545. options = options || {};
  18546. var notFound = _getDefaultValue(key, options)
  18547. , found = _find(key, options);
  18548. return found !== undefined || found === notFound;
  18549. }
  18550. function translate(key, options) {
  18551. options = options || {};
  18552. if (!initialized) {
  18553. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18554. return options.defaultValue || '';
  18555. };
  18556. replacementCounter = 0;
  18557. return _translate.apply(null, arguments);
  18558. }
  18559. function _getDefaultValue(key, options) {
  18560. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18561. }
  18562. function _injectSprintfProcessor() {
  18563. var values = [];
  18564. // mh: build array from second argument onwards
  18565. for (var i = 1; i < arguments.length; i++) {
  18566. values.push(arguments[i]);
  18567. }
  18568. return {
  18569. postProcess: 'sprintf',
  18570. sprintf: values
  18571. };
  18572. }
  18573. function _translate(potentialKeys, options) {
  18574. if (options && typeof options !== 'object') {
  18575. if (o.shortcutFunction === 'sprintf') {
  18576. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18577. options = _injectSprintfProcessor.apply(null, arguments);
  18578. } else if (o.shortcutFunction === 'defaultValue') {
  18579. options = {
  18580. defaultValue: options
  18581. }
  18582. }
  18583. } else {
  18584. options = options || {};
  18585. }
  18586. if (typeof o.defaultVariables === 'object') {
  18587. options = f.extend({}, o.defaultVariables, options);
  18588. }
  18589. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18590. if (typeof potentialKeys === 'string') {
  18591. potentialKeys = [potentialKeys];
  18592. }
  18593. var key = potentialKeys[0];
  18594. if (potentialKeys.length > 1) {
  18595. for (var i = 0; i < potentialKeys.length; i++) {
  18596. key = potentialKeys[i];
  18597. if (exists(key, options)) {
  18598. break;
  18599. }
  18600. }
  18601. }
  18602. var notFound = _getDefaultValue(key, options)
  18603. , found = _find(key, options)
  18604. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18605. , ns = options.ns || o.ns.defaultNs
  18606. , parts;
  18607. // split ns and key
  18608. if (key.indexOf(o.nsseparator) > -1) {
  18609. parts = key.split(o.nsseparator);
  18610. ns = parts[0];
  18611. key = parts[1];
  18612. }
  18613. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18614. if (options.lng) {
  18615. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18616. } else {
  18617. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18618. }
  18619. }
  18620. var postProcessor = options.postProcess || o.postProcess;
  18621. if (found !== undefined && postProcessor) {
  18622. if (postProcessors[postProcessor]) {
  18623. found = postProcessors[postProcessor](found, key, options);
  18624. }
  18625. }
  18626. // process notFound if function exists
  18627. var splitNotFound = notFound;
  18628. if (notFound.indexOf(o.nsseparator) > -1) {
  18629. parts = notFound.split(o.nsseparator);
  18630. splitNotFound = parts[1];
  18631. }
  18632. if (splitNotFound === key && o.parseMissingKey) {
  18633. notFound = o.parseMissingKey(notFound);
  18634. }
  18635. if (found === undefined) {
  18636. notFound = applyReplacement(notFound, options);
  18637. notFound = applyReuse(notFound, options);
  18638. if (postProcessor && postProcessors[postProcessor]) {
  18639. var val = _getDefaultValue(key, options);
  18640. found = postProcessors[postProcessor](val, key, options);
  18641. }
  18642. }
  18643. return (found !== undefined) ? found : notFound;
  18644. }
  18645. function _find(key, options) {
  18646. options = options || {};
  18647. var optionWithoutCount, translated
  18648. , notFound = _getDefaultValue(key, options)
  18649. , lngs = languages;
  18650. if (!resStore) { return notFound; } // no resStore to translate from
  18651. // CI mode
  18652. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18653. // passed in lng
  18654. if (options.lngs) lngs = options.lngs;
  18655. if (options.lng) {
  18656. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18657. if (!resStore[lngs[0]]) {
  18658. var oldAsync = o.getAsync;
  18659. o.getAsync = false;
  18660. i18n.sync.load(lngs, o, function(err, store) {
  18661. f.extend(resStore, store);
  18662. o.getAsync = oldAsync;
  18663. });
  18664. }
  18665. }
  18666. var ns = options.ns || o.ns.defaultNs;
  18667. if (key.indexOf(o.nsseparator) > -1) {
  18668. var parts = key.split(o.nsseparator);
  18669. ns = parts[0];
  18670. key = parts[1];
  18671. }
  18672. if (hasContext(options)) {
  18673. optionWithoutCount = f.extend({}, options);
  18674. delete optionWithoutCount.context;
  18675. optionWithoutCount.defaultValue = o.contextNotFound;
  18676. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18677. translated = translate(contextKey, optionWithoutCount);
  18678. if (translated != o.contextNotFound) {
  18679. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18680. } // else continue translation with original/nonContext key
  18681. }
  18682. if (needsPlural(options, lngs[0])) {
  18683. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18684. delete optionWithoutCount.count;
  18685. delete optionWithoutCount.lng;
  18686. optionWithoutCount.defaultValue = o.pluralNotFound;
  18687. var pluralKey;
  18688. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18689. pluralKey = ns + o.nsseparator + key;
  18690. } else {
  18691. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18692. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18693. if (pluralExtension >= 0) {
  18694. pluralKey = pluralKey + '_' + pluralExtension;
  18695. } else if (pluralExtension === 1) {
  18696. pluralKey = ns + o.nsseparator + key; // singular
  18697. }
  18698. }
  18699. translated = translate(pluralKey, optionWithoutCount);
  18700. if (translated != o.pluralNotFound) {
  18701. return applyReplacement(translated, {
  18702. count: options.count,
  18703. interpolationPrefix: options.interpolationPrefix,
  18704. interpolationSuffix: options.interpolationSuffix
  18705. }); // apply replacement for count only
  18706. } else if (lngs.length > 1) {
  18707. // remove failed lng
  18708. var clone = lngs.slice();
  18709. clone.shift();
  18710. options = f.extend(options, { lngs: clone });
  18711. delete options.lng;
  18712. // retry with fallbacks
  18713. translated = translate(ns + o.nsseparator + key, options);
  18714. if (translated != o.pluralNotFound) return translated;
  18715. } else {
  18716. return translated;
  18717. }
  18718. }
  18719. if (needsIndefiniteArticle(options)) {
  18720. var optionsWithoutIndef = f.extend({}, options);
  18721. delete optionsWithoutIndef.indefinite_article;
  18722. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18723. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18724. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18725. translated = translate(indefiniteKey, optionsWithoutIndef);
  18726. if (translated != o.indefiniteNotFound) {
  18727. return translated;
  18728. }
  18729. }
  18730. var found;
  18731. var keys = key.split(o.keyseparator);
  18732. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18733. if (found !== undefined) break;
  18734. var l = lngs[i];
  18735. var x = 0;
  18736. var value = resStore[l] && resStore[l][ns];
  18737. while (keys[x]) {
  18738. value = value && value[keys[x]];
  18739. x++;
  18740. }
  18741. if (value !== undefined) {
  18742. var valueType = Object.prototype.toString.apply(value);
  18743. if (typeof value === 'string') {
  18744. value = applyReplacement(value, options);
  18745. value = applyReuse(value, options);
  18746. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18747. value = value.join('\n');
  18748. value = applyReplacement(value, options);
  18749. value = applyReuse(value, options);
  18750. } else if (value === null && o.fallbackOnNull === true) {
  18751. value = undefined;
  18752. } else if (value !== null) {
  18753. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18754. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18755. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18756. } else {
  18757. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18758. 'returned an object instead of string.';
  18759. f.log(value);
  18760. }
  18761. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18762. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18763. f.each(value, function(m) {
  18764. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18765. });
  18766. value = copy;
  18767. }
  18768. }
  18769. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18770. value = undefined;
  18771. found = value;
  18772. }
  18773. }
  18774. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18775. // set flag for fallback lookup - avoid recursion
  18776. options.isFallbackLookup = true;
  18777. if (o.fallbackNS.length) {
  18778. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  18779. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  18780. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  18781. /* compare value without namespace */
  18782. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  18783. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  18784. if (foundValue !== notFoundValue) break;
  18785. }
  18786. }
  18787. } else {
  18788. found = _find(key, options); // fallback to default NS
  18789. }
  18790. options.isFallbackLookup = false;
  18791. }
  18792. return found;
  18793. }
  18794. function detectLanguage() {
  18795. var detectedLng;
  18796. var whitelist = o.lngWhitelist || [];
  18797. var userLngChoices = [];
  18798. // get from qs
  18799. var qsParm = [];
  18800. if (typeof window !== 'undefined') {
  18801. (function() {
  18802. var query = window.location.search.substring(1);
  18803. var params = query.split('&');
  18804. for (var i=0; i<params.length; i++) {
  18805. var pos = params[i].indexOf('=');
  18806. if (pos > 0) {
  18807. var key = params[i].substring(0,pos);
  18808. if (key == o.detectLngQS) {
  18809. userLngChoices.push(params[i].substring(pos+1));
  18810. }
  18811. }
  18812. }
  18813. })();
  18814. }
  18815. // get from cookie
  18816. if (o.useCookie && typeof document !== 'undefined') {
  18817. var c = f.cookie.read(o.cookieName);
  18818. if (c) userLngChoices.push(c);
  18819. }
  18820. // get from localStorage
  18821. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  18822. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  18823. }
  18824. // get from navigator
  18825. if (typeof navigator !== 'undefined') {
  18826. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  18827. for (var i=0;i<navigator.languages.length;i++) {
  18828. userLngChoices.push(navigator.languages[i]);
  18829. }
  18830. }
  18831. if (navigator.userLanguage) {
  18832. userLngChoices.push(navigator.userLanguage);
  18833. }
  18834. if (navigator.language) {
  18835. userLngChoices.push(navigator.language);
  18836. }
  18837. }
  18838. (function() {
  18839. for (var i=0;i<userLngChoices.length;i++) {
  18840. var lng = userLngChoices[i];
  18841. if (lng.indexOf('-') > -1) {
  18842. var parts = lng.split('-');
  18843. lng = o.lowerCaseLng ?
  18844. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18845. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18846. }
  18847. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  18848. detectedLng = lng;
  18849. break;
  18850. }
  18851. }
  18852. })();
  18853. //fallback
  18854. if (!detectedLng){
  18855. detectedLng = o.fallbackLng[0];
  18856. }
  18857. return detectedLng;
  18858. }
  18859. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  18860. /* [code, name, numbers, pluralsType] */
  18861. var _rules = [
  18862. ["ach", "Acholi", [1,2], 1],
  18863. ["af", "Afrikaans",[1,2], 2],
  18864. ["ak", "Akan", [1,2], 1],
  18865. ["am", "Amharic", [1,2], 1],
  18866. ["an", "Aragonese",[1,2], 2],
  18867. ["ar", "Arabic", [0,1,2,3,11,100],5],
  18868. ["arn", "Mapudungun",[1,2], 1],
  18869. ["ast", "Asturian", [1,2], 2],
  18870. ["ay", "Aymará", [1], 3],
  18871. ["az", "Azerbaijani",[1,2],2],
  18872. ["be", "Belarusian",[1,2,5],4],
  18873. ["bg", "Bulgarian",[1,2], 2],
  18874. ["bn", "Bengali", [1,2], 2],
  18875. ["bo", "Tibetan", [1], 3],
  18876. ["br", "Breton", [1,2], 1],
  18877. ["bs", "Bosnian", [1,2,5],4],
  18878. ["ca", "Catalan", [1,2], 2],
  18879. ["cgg", "Chiga", [1], 3],
  18880. ["cs", "Czech", [1,2,5],6],
  18881. ["csb", "Kashubian",[1,2,5],7],
  18882. ["cy", "Welsh", [1,2,3,8],8],
  18883. ["da", "Danish", [1,2], 2],
  18884. ["de", "German", [1,2], 2],
  18885. ["dev", "Development Fallback", [1,2], 2],
  18886. ["dz", "Dzongkha", [1], 3],
  18887. ["el", "Greek", [1,2], 2],
  18888. ["en", "English", [1,2], 2],
  18889. ["eo", "Esperanto",[1,2], 2],
  18890. ["es", "Spanish", [1,2], 2],
  18891. ["es_ar","Argentinean Spanish", [1,2], 2],
  18892. ["et", "Estonian", [1,2], 2],
  18893. ["eu", "Basque", [1,2], 2],
  18894. ["fa", "Persian", [1], 3],
  18895. ["fi", "Finnish", [1,2], 2],
  18896. ["fil", "Filipino", [1,2], 1],
  18897. ["fo", "Faroese", [1,2], 2],
  18898. ["fr", "French", [1,2], 9],
  18899. ["fur", "Friulian", [1,2], 2],
  18900. ["fy", "Frisian", [1,2], 2],
  18901. ["ga", "Irish", [1,2,3,7,11],10],
  18902. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  18903. ["gl", "Galician", [1,2], 2],
  18904. ["gu", "Gujarati", [1,2], 2],
  18905. ["gun", "Gun", [1,2], 1],
  18906. ["ha", "Hausa", [1,2], 2],
  18907. ["he", "Hebrew", [1,2], 2],
  18908. ["hi", "Hindi", [1,2], 2],
  18909. ["hr", "Croatian", [1,2,5],4],
  18910. ["hu", "Hungarian",[1,2], 2],
  18911. ["hy", "Armenian", [1,2], 2],
  18912. ["ia", "Interlingua",[1,2],2],
  18913. ["id", "Indonesian",[1], 3],
  18914. ["is", "Icelandic",[1,2], 12],
  18915. ["it", "Italian", [1,2], 2],
  18916. ["ja", "Japanese", [1], 3],
  18917. ["jbo", "Lojban", [1], 3],
  18918. ["jv", "Javanese", [0,1], 13],
  18919. ["ka", "Georgian", [1], 3],
  18920. ["kk", "Kazakh", [1], 3],
  18921. ["km", "Khmer", [1], 3],
  18922. ["kn", "Kannada", [1,2], 2],
  18923. ["ko", "Korean", [1], 3],
  18924. ["ku", "Kurdish", [1,2], 2],
  18925. ["kw", "Cornish", [1,2,3,4],14],
  18926. ["ky", "Kyrgyz", [1], 3],
  18927. ["lb", "Letzeburgesch",[1,2],2],
  18928. ["ln", "Lingala", [1,2], 1],
  18929. ["lo", "Lao", [1], 3],
  18930. ["lt", "Lithuanian",[1,2,10],15],
  18931. ["lv", "Latvian", [1,2,0],16],
  18932. ["mai", "Maithili", [1,2], 2],
  18933. ["mfe", "Mauritian Creole",[1,2],1],
  18934. ["mg", "Malagasy", [1,2], 1],
  18935. ["mi", "Maori", [1,2], 1],
  18936. ["mk", "Macedonian",[1,2],17],
  18937. ["ml", "Malayalam",[1,2], 2],
  18938. ["mn", "Mongolian",[1,2], 2],
  18939. ["mnk", "Mandinka", [0,1,2],18],
  18940. ["mr", "Marathi", [1,2], 2],
  18941. ["ms", "Malay", [1], 3],
  18942. ["mt", "Maltese", [1,2,11,20],19],
  18943. ["nah", "Nahuatl", [1,2], 2],
  18944. ["nap", "Neapolitan",[1,2], 2],
  18945. ["nb", "Norwegian Bokmal",[1,2],2],
  18946. ["ne", "Nepali", [1,2], 2],
  18947. ["nl", "Dutch", [1,2], 2],
  18948. ["nn", "Norwegian Nynorsk",[1,2],2],
  18949. ["no", "Norwegian",[1,2], 2],
  18950. ["nso", "Northern Sotho",[1,2],2],
  18951. ["oc", "Occitan", [1,2], 1],
  18952. ["or", "Oriya", [2,1], 2],
  18953. ["pa", "Punjabi", [1,2], 2],
  18954. ["pap", "Papiamento",[1,2], 2],
  18955. ["pl", "Polish", [1,2,5],7],
  18956. ["pms", "Piemontese",[1,2], 2],
  18957. ["ps", "Pashto", [1,2], 2],
  18958. ["pt", "Portuguese",[1,2], 2],
  18959. ["pt_br","Brazilian Portuguese",[1,2], 2],
  18960. ["rm", "Romansh", [1,2], 2],
  18961. ["ro", "Romanian", [1,2,20],20],
  18962. ["ru", "Russian", [1,2,5],4],
  18963. ["sah", "Yakut", [1], 3],
  18964. ["sco", "Scots", [1,2], 2],
  18965. ["se", "Northern Sami",[1,2], 2],
  18966. ["si", "Sinhala", [1,2], 2],
  18967. ["sk", "Slovak", [1,2,5],6],
  18968. ["sl", "Slovenian",[5,1,2,3],21],
  18969. ["so", "Somali", [1,2], 2],
  18970. ["son", "Songhay", [1,2], 2],
  18971. ["sq", "Albanian", [1,2], 2],
  18972. ["sr", "Serbian", [1,2,5],4],
  18973. ["su", "Sundanese",[1], 3],
  18974. ["sv", "Swedish", [1,2], 2],
  18975. ["sw", "Swahili", [1,2], 2],
  18976. ["ta", "Tamil", [1,2], 2],
  18977. ["te", "Telugu", [1,2], 2],
  18978. ["tg", "Tajik", [1,2], 1],
  18979. ["th", "Thai", [1], 3],
  18980. ["ti", "Tigrinya", [1,2], 1],
  18981. ["tk", "Turkmen", [1,2], 2],
  18982. ["tr", "Turkish", [1,2], 1],
  18983. ["tt", "Tatar", [1], 3],
  18984. ["ug", "Uyghur", [1], 3],
  18985. ["uk", "Ukrainian",[1,2,5],4],
  18986. ["ur", "Urdu", [1,2], 2],
  18987. ["uz", "Uzbek", [1,2], 1],
  18988. ["vi", "Vietnamese",[1], 3],
  18989. ["wa", "Walloon", [1,2], 1],
  18990. ["wo", "Wolof", [1], 3],
  18991. ["yo", "Yoruba", [1,2], 2],
  18992. ["zh", "Chinese", [1], 3]
  18993. ];
  18994. var _rulesPluralsTypes = {
  18995. 1: function(n) {return Number(n > 1);},
  18996. 2: function(n) {return Number(n != 1);},
  18997. 3: function(n) {return 0;},
  18998. 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);},
  18999. 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);},
  19000. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19001. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19002. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19003. 9: function(n) {return Number(n >= 2);},
  19004. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19005. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19006. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19007. 13: function(n) {return Number(n !== 0);},
  19008. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19009. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19010. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19011. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19012. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19013. 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);},
  19014. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19015. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19016. };
  19017. var pluralExtensions = {
  19018. rules: (function () {
  19019. var l, rules = {};
  19020. for (l=_rules.length; l-- ;) {
  19021. rules[_rules[l][0]] = {
  19022. name: _rules[l][1],
  19023. numbers: _rules[l][2],
  19024. plurals: _rulesPluralsTypes[_rules[l][3]]
  19025. }
  19026. }
  19027. return rules;
  19028. }()),
  19029. // you can add your own pluralExtensions
  19030. addRule: function(lng, obj) {
  19031. pluralExtensions.rules[lng] = obj;
  19032. },
  19033. setCurrentLng: function(lng) {
  19034. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19035. var parts = lng.split('-');
  19036. pluralExtensions.currentRule = {
  19037. lng: lng,
  19038. rule: pluralExtensions.rules[parts[0]]
  19039. };
  19040. }
  19041. },
  19042. needsPlural: function(lng, count) {
  19043. var parts = lng.split('-');
  19044. var ext;
  19045. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19046. ext = pluralExtensions.currentRule.rule;
  19047. } else {
  19048. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19049. }
  19050. if (ext && ext.numbers.length <= 1) {
  19051. return false;
  19052. } else {
  19053. return this.get(lng, count) !== 1;
  19054. }
  19055. },
  19056. get: function(lng, count) {
  19057. var parts = lng.split('-');
  19058. function getResult(l, c) {
  19059. var ext;
  19060. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19061. ext = pluralExtensions.currentRule.rule;
  19062. } else {
  19063. ext = pluralExtensions.rules[l];
  19064. }
  19065. if (ext) {
  19066. var i;
  19067. if (ext.noAbs) {
  19068. i = ext.plurals(c);
  19069. } else {
  19070. i = ext.plurals(Math.abs(c));
  19071. }
  19072. var number = ext.numbers[i];
  19073. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19074. if (number === 2) {
  19075. number = -1; // regular plural
  19076. } else if (number === 1) {
  19077. number = 1; // singular
  19078. }
  19079. }//console.log(count + '-' + number);
  19080. return number;
  19081. } else {
  19082. return c === 1 ? '1' : '-1';
  19083. }
  19084. }
  19085. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19086. }
  19087. };
  19088. var postProcessors = {};
  19089. var addPostProcessor = function(name, fc) {
  19090. postProcessors[name] = fc;
  19091. };
  19092. // sprintf support
  19093. var sprintf = (function() {
  19094. function get_type(variable) {
  19095. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19096. }
  19097. function str_repeat(input, multiplier) {
  19098. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19099. return output.join('');
  19100. }
  19101. var str_format = function() {
  19102. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19103. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19104. }
  19105. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19106. };
  19107. str_format.format = function(parse_tree, argv) {
  19108. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19109. for (i = 0; i < tree_length; i++) {
  19110. node_type = get_type(parse_tree[i]);
  19111. if (node_type === 'string') {
  19112. output.push(parse_tree[i]);
  19113. }
  19114. else if (node_type === 'array') {
  19115. match = parse_tree[i]; // convenience purposes only
  19116. if (match[2]) { // keyword argument
  19117. arg = argv[cursor];
  19118. for (k = 0; k < match[2].length; k++) {
  19119. if (!arg.hasOwnProperty(match[2][k])) {
  19120. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19121. }
  19122. arg = arg[match[2][k]];
  19123. }
  19124. }
  19125. else if (match[1]) { // positional argument (explicit)
  19126. arg = argv[match[1]];
  19127. }
  19128. else { // positional argument (implicit)
  19129. arg = argv[cursor++];
  19130. }
  19131. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19132. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19133. }
  19134. switch (match[8]) {
  19135. case 'b': arg = arg.toString(2); break;
  19136. case 'c': arg = String.fromCharCode(arg); break;
  19137. case 'd': arg = parseInt(arg, 10); break;
  19138. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19139. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19140. case 'o': arg = arg.toString(8); break;
  19141. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19142. case 'u': arg = Math.abs(arg); break;
  19143. case 'x': arg = arg.toString(16); break;
  19144. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19145. }
  19146. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19147. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19148. pad_length = match[6] - String(arg).length;
  19149. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19150. output.push(match[5] ? arg + pad : pad + arg);
  19151. }
  19152. }
  19153. return output.join('');
  19154. };
  19155. str_format.cache = {};
  19156. str_format.parse = function(fmt) {
  19157. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19158. while (_fmt) {
  19159. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19160. parse_tree.push(match[0]);
  19161. }
  19162. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19163. parse_tree.push('%');
  19164. }
  19165. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19166. if (match[2]) {
  19167. arg_names |= 1;
  19168. var field_list = [], replacement_field = match[2], field_match = [];
  19169. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19170. field_list.push(field_match[1]);
  19171. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19172. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19173. field_list.push(field_match[1]);
  19174. }
  19175. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19176. field_list.push(field_match[1]);
  19177. }
  19178. else {
  19179. throw('[sprintf] huh?');
  19180. }
  19181. }
  19182. }
  19183. else {
  19184. throw('[sprintf] huh?');
  19185. }
  19186. match[2] = field_list;
  19187. }
  19188. else {
  19189. arg_names |= 2;
  19190. }
  19191. if (arg_names === 3) {
  19192. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19193. }
  19194. parse_tree.push(match);
  19195. }
  19196. else {
  19197. throw('[sprintf] huh?');
  19198. }
  19199. _fmt = _fmt.substring(match[0].length);
  19200. }
  19201. return parse_tree;
  19202. };
  19203. return str_format;
  19204. })();
  19205. var vsprintf = function(fmt, argv) {
  19206. argv.unshift(fmt);
  19207. return sprintf.apply(null, argv);
  19208. };
  19209. addPostProcessor("sprintf", function(val, key, opts) {
  19210. if (!opts.sprintf) return val;
  19211. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19212. return vsprintf(val, opts.sprintf);
  19213. } else if (typeof opts.sprintf === 'object') {
  19214. return sprintf(val, opts.sprintf);
  19215. }
  19216. return val;
  19217. });
  19218. // public api interface
  19219. i18n.init = init;
  19220. i18n.setLng = setLng;
  19221. i18n.preload = preload;
  19222. i18n.addResourceBundle = addResourceBundle;
  19223. i18n.hasResourceBundle = hasResourceBundle;
  19224. i18n.addResource = addResource;
  19225. i18n.addResources = addResources;
  19226. i18n.removeResourceBundle = removeResourceBundle;
  19227. i18n.loadNamespace = loadNamespace;
  19228. i18n.loadNamespaces = loadNamespaces;
  19229. i18n.setDefaultNamespace = setDefaultNamespace;
  19230. i18n.t = translate;
  19231. i18n.translate = translate;
  19232. i18n.exists = exists;
  19233. i18n.detectLanguage = f.detectLanguage;
  19234. i18n.pluralExtensions = pluralExtensions;
  19235. i18n.sync = sync;
  19236. i18n.functions = f;
  19237. i18n.lng = lng;
  19238. i18n.addPostProcessor = addPostProcessor;
  19239. i18n.options = o;
  19240. })();
  19241. },{"jquery":"jquery"}],69:[function(require,module,exports){
  19242. // Top level file is just a mixin of submodules & constants
  19243. 'use strict';
  19244. var assign = require('./lib/utils/common').assign;
  19245. var deflate = require('./lib/deflate');
  19246. var inflate = require('./lib/inflate');
  19247. var constants = require('./lib/zlib/constants');
  19248. var pako = {};
  19249. assign(pako, deflate, inflate, constants);
  19250. module.exports = pako;
  19251. },{"./lib/deflate":70,"./lib/inflate":71,"./lib/utils/common":72,"./lib/zlib/constants":75}],70:[function(require,module,exports){
  19252. 'use strict';
  19253. var zlib_deflate = require('./zlib/deflate.js');
  19254. var utils = require('./utils/common');
  19255. var strings = require('./utils/strings');
  19256. var msg = require('./zlib/messages');
  19257. var zstream = require('./zlib/zstream');
  19258. var toString = Object.prototype.toString;
  19259. /* Public constants ==========================================================*/
  19260. /* ===========================================================================*/
  19261. var Z_NO_FLUSH = 0;
  19262. var Z_FINISH = 4;
  19263. var Z_OK = 0;
  19264. var Z_STREAM_END = 1;
  19265. var Z_SYNC_FLUSH = 2;
  19266. var Z_DEFAULT_COMPRESSION = -1;
  19267. var Z_DEFAULT_STRATEGY = 0;
  19268. var Z_DEFLATED = 8;
  19269. /* ===========================================================================*/
  19270. /**
  19271. * class Deflate
  19272. *
  19273. * Generic JS-style wrapper for zlib calls. If you don't need
  19274. * streaming behaviour - use more simple functions: [[deflate]],
  19275. * [[deflateRaw]] and [[gzip]].
  19276. **/
  19277. /* internal
  19278. * Deflate.chunks -> Array
  19279. *
  19280. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19281. **/
  19282. /**
  19283. * Deflate.result -> Uint8Array|Array
  19284. *
  19285. * Compressed result, generated by default [[Deflate#onData]]
  19286. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19287. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19288. * push a chunk with explicit flush (call [[Deflate#push]] with
  19289. * `Z_SYNC_FLUSH` param).
  19290. **/
  19291. /**
  19292. * Deflate.err -> Number
  19293. *
  19294. * Error code after deflate finished. 0 (Z_OK) on success.
  19295. * You will not need it in real life, because deflate errors
  19296. * are possible only on wrong options or bad `onData` / `onEnd`
  19297. * custom handlers.
  19298. **/
  19299. /**
  19300. * Deflate.msg -> String
  19301. *
  19302. * Error message, if [[Deflate.err]] != 0
  19303. **/
  19304. /**
  19305. * new Deflate(options)
  19306. * - options (Object): zlib deflate options.
  19307. *
  19308. * Creates new deflator instance with specified params. Throws exception
  19309. * on bad params. Supported options:
  19310. *
  19311. * - `level`
  19312. * - `windowBits`
  19313. * - `memLevel`
  19314. * - `strategy`
  19315. *
  19316. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19317. * for more information on these.
  19318. *
  19319. * Additional options, for internal needs:
  19320. *
  19321. * - `chunkSize` - size of generated data chunks (16K by default)
  19322. * - `raw` (Boolean) - do raw deflate
  19323. * - `gzip` (Boolean) - create gzip wrapper
  19324. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19325. * (each char code [0..255])
  19326. * - `header` (Object) - custom header for gzip
  19327. * - `text` (Boolean) - true if compressed data believed to be text
  19328. * - `time` (Number) - modification time, unix timestamp
  19329. * - `os` (Number) - operation system code
  19330. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19331. * - `name` (String) - file name (binary string)
  19332. * - `comment` (String) - comment (binary string)
  19333. * - `hcrc` (Boolean) - true if header crc should be added
  19334. *
  19335. * ##### Example:
  19336. *
  19337. * ```javascript
  19338. * var pako = require('pako')
  19339. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19340. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19341. *
  19342. * var deflate = new pako.Deflate({ level: 3});
  19343. *
  19344. * deflate.push(chunk1, false);
  19345. * deflate.push(chunk2, true); // true -> last chunk
  19346. *
  19347. * if (deflate.err) { throw new Error(deflate.err); }
  19348. *
  19349. * console.log(deflate.result);
  19350. * ```
  19351. **/
  19352. var Deflate = function(options) {
  19353. this.options = utils.assign({
  19354. level: Z_DEFAULT_COMPRESSION,
  19355. method: Z_DEFLATED,
  19356. chunkSize: 16384,
  19357. windowBits: 15,
  19358. memLevel: 8,
  19359. strategy: Z_DEFAULT_STRATEGY,
  19360. to: ''
  19361. }, options || {});
  19362. var opt = this.options;
  19363. if (opt.raw && (opt.windowBits > 0)) {
  19364. opt.windowBits = -opt.windowBits;
  19365. }
  19366. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19367. opt.windowBits += 16;
  19368. }
  19369. this.err = 0; // error code, if happens (0 = Z_OK)
  19370. this.msg = ''; // error message
  19371. this.ended = false; // used to avoid multiple onEnd() calls
  19372. this.chunks = []; // chunks of compressed data
  19373. this.strm = new zstream();
  19374. this.strm.avail_out = 0;
  19375. var status = zlib_deflate.deflateInit2(
  19376. this.strm,
  19377. opt.level,
  19378. opt.method,
  19379. opt.windowBits,
  19380. opt.memLevel,
  19381. opt.strategy
  19382. );
  19383. if (status !== Z_OK) {
  19384. throw new Error(msg[status]);
  19385. }
  19386. if (opt.header) {
  19387. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19388. }
  19389. };
  19390. /**
  19391. * Deflate#push(data[, mode]) -> Boolean
  19392. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19393. * converted to utf8 byte sequence.
  19394. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19395. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19396. *
  19397. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19398. * new compressed chunks. Returns `true` on success. The last data block must have
  19399. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19400. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19401. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19402. *
  19403. * On fail call [[Deflate#onEnd]] with error code and return false.
  19404. *
  19405. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19406. * array format is detected automatically). Also, don't skip last param and always
  19407. * use the same type in your code (boolean or number). That will improve JS speed.
  19408. *
  19409. * For regular `Array`-s make sure all elements are [0..255].
  19410. *
  19411. * ##### Example
  19412. *
  19413. * ```javascript
  19414. * push(chunk, false); // push one of data chunks
  19415. * ...
  19416. * push(chunk, true); // push last chunk
  19417. * ```
  19418. **/
  19419. Deflate.prototype.push = function(data, mode) {
  19420. var strm = this.strm;
  19421. var chunkSize = this.options.chunkSize;
  19422. var status, _mode;
  19423. if (this.ended) { return false; }
  19424. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19425. // Convert data if needed
  19426. if (typeof data === 'string') {
  19427. // If we need to compress text, change encoding to utf8.
  19428. strm.input = strings.string2buf(data);
  19429. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19430. strm.input = new Uint8Array(data);
  19431. } else {
  19432. strm.input = data;
  19433. }
  19434. strm.next_in = 0;
  19435. strm.avail_in = strm.input.length;
  19436. do {
  19437. if (strm.avail_out === 0) {
  19438. strm.output = new utils.Buf8(chunkSize);
  19439. strm.next_out = 0;
  19440. strm.avail_out = chunkSize;
  19441. }
  19442. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19443. if (status !== Z_STREAM_END && status !== Z_OK) {
  19444. this.onEnd(status);
  19445. this.ended = true;
  19446. return false;
  19447. }
  19448. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19449. if (this.options.to === 'string') {
  19450. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19451. } else {
  19452. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19453. }
  19454. }
  19455. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19456. // Finalize on the last chunk.
  19457. if (_mode === Z_FINISH) {
  19458. status = zlib_deflate.deflateEnd(this.strm);
  19459. this.onEnd(status);
  19460. this.ended = true;
  19461. return status === Z_OK;
  19462. }
  19463. // callback interim results if Z_SYNC_FLUSH.
  19464. if (_mode === Z_SYNC_FLUSH) {
  19465. this.onEnd(Z_OK);
  19466. strm.avail_out = 0;
  19467. return true;
  19468. }
  19469. return true;
  19470. };
  19471. /**
  19472. * Deflate#onData(chunk) -> Void
  19473. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19474. * on js engine support. When string output requested, each chunk
  19475. * will be string.
  19476. *
  19477. * By default, stores data blocks in `chunks[]` property and glue
  19478. * those in `onEnd`. Override this handler, if you need another behaviour.
  19479. **/
  19480. Deflate.prototype.onData = function(chunk) {
  19481. this.chunks.push(chunk);
  19482. };
  19483. /**
  19484. * Deflate#onEnd(status) -> Void
  19485. * - status (Number): deflate status. 0 (Z_OK) on success,
  19486. * other if not.
  19487. *
  19488. * Called once after you tell deflate that the input stream is
  19489. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19490. * or if an error happened. By default - join collected chunks,
  19491. * free memory and fill `results` / `err` properties.
  19492. **/
  19493. Deflate.prototype.onEnd = function(status) {
  19494. // On success - join
  19495. if (status === Z_OK) {
  19496. if (this.options.to === 'string') {
  19497. this.result = this.chunks.join('');
  19498. } else {
  19499. this.result = utils.flattenChunks(this.chunks);
  19500. }
  19501. }
  19502. this.chunks = [];
  19503. this.err = status;
  19504. this.msg = this.strm.msg;
  19505. };
  19506. /**
  19507. * deflate(data[, options]) -> Uint8Array|Array|String
  19508. * - data (Uint8Array|Array|String): input data to compress.
  19509. * - options (Object): zlib deflate options.
  19510. *
  19511. * Compress `data` with deflate alrorythm and `options`.
  19512. *
  19513. * Supported options are:
  19514. *
  19515. * - level
  19516. * - windowBits
  19517. * - memLevel
  19518. * - strategy
  19519. *
  19520. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19521. * for more information on these.
  19522. *
  19523. * Sugar (options):
  19524. *
  19525. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19526. * negative windowBits implicitly.
  19527. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19528. * (each char code [0..255])
  19529. *
  19530. * ##### Example:
  19531. *
  19532. * ```javascript
  19533. * var pako = require('pako')
  19534. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19535. *
  19536. * console.log(pako.deflate(data));
  19537. * ```
  19538. **/
  19539. function deflate(input, options) {
  19540. var deflator = new Deflate(options);
  19541. deflator.push(input, true);
  19542. // That will never happens, if you don't cheat with options :)
  19543. if (deflator.err) { throw deflator.msg; }
  19544. return deflator.result;
  19545. }
  19546. /**
  19547. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19548. * - data (Uint8Array|Array|String): input data to compress.
  19549. * - options (Object): zlib deflate options.
  19550. *
  19551. * The same as [[deflate]], but creates raw data, without wrapper
  19552. * (header and adler32 crc).
  19553. **/
  19554. function deflateRaw(input, options) {
  19555. options = options || {};
  19556. options.raw = true;
  19557. return deflate(input, options);
  19558. }
  19559. /**
  19560. * gzip(data[, options]) -> Uint8Array|Array|String
  19561. * - data (Uint8Array|Array|String): input data to compress.
  19562. * - options (Object): zlib deflate options.
  19563. *
  19564. * The same as [[deflate]], but create gzip wrapper instead of
  19565. * deflate one.
  19566. **/
  19567. function gzip(input, options) {
  19568. options = options || {};
  19569. options.gzip = true;
  19570. return deflate(input, options);
  19571. }
  19572. exports.Deflate = Deflate;
  19573. exports.deflate = deflate;
  19574. exports.deflateRaw = deflateRaw;
  19575. exports.gzip = gzip;
  19576. },{"./utils/common":72,"./utils/strings":73,"./zlib/deflate.js":77,"./zlib/messages":82,"./zlib/zstream":84}],71:[function(require,module,exports){
  19577. 'use strict';
  19578. var zlib_inflate = require('./zlib/inflate.js');
  19579. var utils = require('./utils/common');
  19580. var strings = require('./utils/strings');
  19581. var c = require('./zlib/constants');
  19582. var msg = require('./zlib/messages');
  19583. var zstream = require('./zlib/zstream');
  19584. var gzheader = require('./zlib/gzheader');
  19585. var toString = Object.prototype.toString;
  19586. /**
  19587. * class Inflate
  19588. *
  19589. * Generic JS-style wrapper for zlib calls. If you don't need
  19590. * streaming behaviour - use more simple functions: [[inflate]]
  19591. * and [[inflateRaw]].
  19592. **/
  19593. /* internal
  19594. * inflate.chunks -> Array
  19595. *
  19596. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19597. **/
  19598. /**
  19599. * Inflate.result -> Uint8Array|Array|String
  19600. *
  19601. * Uncompressed result, generated by default [[Inflate#onData]]
  19602. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19603. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19604. * push a chunk with explicit flush (call [[Inflate#push]] with
  19605. * `Z_SYNC_FLUSH` param).
  19606. **/
  19607. /**
  19608. * Inflate.err -> Number
  19609. *
  19610. * Error code after inflate finished. 0 (Z_OK) on success.
  19611. * Should be checked if broken data possible.
  19612. **/
  19613. /**
  19614. * Inflate.msg -> String
  19615. *
  19616. * Error message, if [[Inflate.err]] != 0
  19617. **/
  19618. /**
  19619. * new Inflate(options)
  19620. * - options (Object): zlib inflate options.
  19621. *
  19622. * Creates new inflator instance with specified params. Throws exception
  19623. * on bad params. Supported options:
  19624. *
  19625. * - `windowBits`
  19626. *
  19627. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19628. * for more information on these.
  19629. *
  19630. * Additional options, for internal needs:
  19631. *
  19632. * - `chunkSize` - size of generated data chunks (16K by default)
  19633. * - `raw` (Boolean) - do raw inflate
  19634. * - `to` (String) - if equal to 'string', then result will be converted
  19635. * from utf8 to utf16 (javascript) string. When string output requested,
  19636. * chunk length can differ from `chunkSize`, depending on content.
  19637. *
  19638. * By default, when no options set, autodetect deflate/gzip data format via
  19639. * wrapper header.
  19640. *
  19641. * ##### Example:
  19642. *
  19643. * ```javascript
  19644. * var pako = require('pako')
  19645. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19646. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19647. *
  19648. * var inflate = new pako.Inflate({ level: 3});
  19649. *
  19650. * inflate.push(chunk1, false);
  19651. * inflate.push(chunk2, true); // true -> last chunk
  19652. *
  19653. * if (inflate.err) { throw new Error(inflate.err); }
  19654. *
  19655. * console.log(inflate.result);
  19656. * ```
  19657. **/
  19658. var Inflate = function(options) {
  19659. this.options = utils.assign({
  19660. chunkSize: 16384,
  19661. windowBits: 0,
  19662. to: ''
  19663. }, options || {});
  19664. var opt = this.options;
  19665. // Force window size for `raw` data, if not set directly,
  19666. // because we have no header for autodetect.
  19667. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19668. opt.windowBits = -opt.windowBits;
  19669. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19670. }
  19671. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19672. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19673. !(options && options.windowBits)) {
  19674. opt.windowBits += 32;
  19675. }
  19676. // Gzip header has no info about windows size, we can do autodetect only
  19677. // for deflate. So, if window size not set, force it to max when gzip possible
  19678. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19679. // bit 3 (16) -> gzipped data
  19680. // bit 4 (32) -> autodetect gzip/deflate
  19681. if ((opt.windowBits & 15) === 0) {
  19682. opt.windowBits |= 15;
  19683. }
  19684. }
  19685. this.err = 0; // error code, if happens (0 = Z_OK)
  19686. this.msg = ''; // error message
  19687. this.ended = false; // used to avoid multiple onEnd() calls
  19688. this.chunks = []; // chunks of compressed data
  19689. this.strm = new zstream();
  19690. this.strm.avail_out = 0;
  19691. var status = zlib_inflate.inflateInit2(
  19692. this.strm,
  19693. opt.windowBits
  19694. );
  19695. if (status !== c.Z_OK) {
  19696. throw new Error(msg[status]);
  19697. }
  19698. this.header = new gzheader();
  19699. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19700. };
  19701. /**
  19702. * Inflate#push(data[, mode]) -> Boolean
  19703. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19704. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19705. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19706. *
  19707. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19708. * new output chunks. Returns `true` on success. The last data block must have
  19709. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19710. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19711. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  19712. *
  19713. * On fail call [[Inflate#onEnd]] with error code and return false.
  19714. *
  19715. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19716. * format is detected automatically). Also, don't skip last param and always
  19717. * use the same type in your code (boolean or number). That will improve JS speed.
  19718. *
  19719. * For regular `Array`-s make sure all elements are [0..255].
  19720. *
  19721. * ##### Example
  19722. *
  19723. * ```javascript
  19724. * push(chunk, false); // push one of data chunks
  19725. * ...
  19726. * push(chunk, true); // push last chunk
  19727. * ```
  19728. **/
  19729. Inflate.prototype.push = function(data, mode) {
  19730. var strm = this.strm;
  19731. var chunkSize = this.options.chunkSize;
  19732. var status, _mode;
  19733. var next_out_utf8, tail, utf8str;
  19734. if (this.ended) { return false; }
  19735. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19736. // Convert data if needed
  19737. if (typeof data === 'string') {
  19738. // Only binary strings can be decompressed on practice
  19739. strm.input = strings.binstring2buf(data);
  19740. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19741. strm.input = new Uint8Array(data);
  19742. } else {
  19743. strm.input = data;
  19744. }
  19745. strm.next_in = 0;
  19746. strm.avail_in = strm.input.length;
  19747. do {
  19748. if (strm.avail_out === 0) {
  19749. strm.output = new utils.Buf8(chunkSize);
  19750. strm.next_out = 0;
  19751. strm.avail_out = chunkSize;
  19752. }
  19753. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19754. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19755. this.onEnd(status);
  19756. this.ended = true;
  19757. return false;
  19758. }
  19759. if (strm.next_out) {
  19760. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  19761. if (this.options.to === 'string') {
  19762. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19763. tail = strm.next_out - next_out_utf8;
  19764. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19765. // move tail
  19766. strm.next_out = tail;
  19767. strm.avail_out = chunkSize - tail;
  19768. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19769. this.onData(utf8str);
  19770. } else {
  19771. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19772. }
  19773. }
  19774. }
  19775. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19776. if (status === c.Z_STREAM_END) {
  19777. _mode = c.Z_FINISH;
  19778. }
  19779. // Finalize on the last chunk.
  19780. if (_mode === c.Z_FINISH) {
  19781. status = zlib_inflate.inflateEnd(this.strm);
  19782. this.onEnd(status);
  19783. this.ended = true;
  19784. return status === c.Z_OK;
  19785. }
  19786. // callback interim results if Z_SYNC_FLUSH.
  19787. if (_mode === c.Z_SYNC_FLUSH) {
  19788. this.onEnd(c.Z_OK);
  19789. strm.avail_out = 0;
  19790. return true;
  19791. }
  19792. return true;
  19793. };
  19794. /**
  19795. * Inflate#onData(chunk) -> Void
  19796. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19797. * on js engine support. When string output requested, each chunk
  19798. * will be string.
  19799. *
  19800. * By default, stores data blocks in `chunks[]` property and glue
  19801. * those in `onEnd`. Override this handler, if you need another behaviour.
  19802. **/
  19803. Inflate.prototype.onData = function(chunk) {
  19804. this.chunks.push(chunk);
  19805. };
  19806. /**
  19807. * Inflate#onEnd(status) -> Void
  19808. * - status (Number): inflate status. 0 (Z_OK) on success,
  19809. * other if not.
  19810. *
  19811. * Called either after you tell inflate that the input stream is
  19812. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19813. * or if an error happened. By default - join collected chunks,
  19814. * free memory and fill `results` / `err` properties.
  19815. **/
  19816. Inflate.prototype.onEnd = function(status) {
  19817. // On success - join
  19818. if (status === c.Z_OK) {
  19819. if (this.options.to === 'string') {
  19820. // Glue & convert here, until we teach pako to send
  19821. // utf8 alligned strings to onData
  19822. this.result = this.chunks.join('');
  19823. } else {
  19824. this.result = utils.flattenChunks(this.chunks);
  19825. }
  19826. }
  19827. this.chunks = [];
  19828. this.err = status;
  19829. this.msg = this.strm.msg;
  19830. };
  19831. /**
  19832. * inflate(data[, options]) -> Uint8Array|Array|String
  19833. * - data (Uint8Array|Array|String): input data to decompress.
  19834. * - options (Object): zlib inflate options.
  19835. *
  19836. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19837. * format via wrapper header by default. That's why we don't provide
  19838. * separate `ungzip` method.
  19839. *
  19840. * Supported options are:
  19841. *
  19842. * - windowBits
  19843. *
  19844. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19845. * for more information.
  19846. *
  19847. * Sugar (options):
  19848. *
  19849. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19850. * negative windowBits implicitly.
  19851. * - `to` (String) - if equal to 'string', then result will be converted
  19852. * from utf8 to utf16 (javascript) string. When string output requested,
  19853. * chunk length can differ from `chunkSize`, depending on content.
  19854. *
  19855. *
  19856. * ##### Example:
  19857. *
  19858. * ```javascript
  19859. * var pako = require('pako')
  19860. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19861. * , output;
  19862. *
  19863. * try {
  19864. * output = pako.inflate(input);
  19865. * } catch (err)
  19866. * console.log(err);
  19867. * }
  19868. * ```
  19869. **/
  19870. function inflate(input, options) {
  19871. var inflator = new Inflate(options);
  19872. inflator.push(input, true);
  19873. // That will never happens, if you don't cheat with options :)
  19874. if (inflator.err) { throw inflator.msg; }
  19875. return inflator.result;
  19876. }
  19877. /**
  19878. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19879. * - data (Uint8Array|Array|String): input data to decompress.
  19880. * - options (Object): zlib inflate options.
  19881. *
  19882. * The same as [[inflate]], but creates raw data, without wrapper
  19883. * (header and adler32 crc).
  19884. **/
  19885. function inflateRaw(input, options) {
  19886. options = options || {};
  19887. options.raw = true;
  19888. return inflate(input, options);
  19889. }
  19890. /**
  19891. * ungzip(data[, options]) -> Uint8Array|Array|String
  19892. * - data (Uint8Array|Array|String): input data to decompress.
  19893. * - options (Object): zlib inflate options.
  19894. *
  19895. * Just shortcut to [[inflate]], because it autodetects format
  19896. * by header.content. Done for convenience.
  19897. **/
  19898. exports.Inflate = Inflate;
  19899. exports.inflate = inflate;
  19900. exports.inflateRaw = inflateRaw;
  19901. exports.ungzip = inflate;
  19902. },{"./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){
  19903. 'use strict';
  19904. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19905. (typeof Uint16Array !== 'undefined') &&
  19906. (typeof Int32Array !== 'undefined');
  19907. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19908. var sources = Array.prototype.slice.call(arguments, 1);
  19909. while (sources.length) {
  19910. var source = sources.shift();
  19911. if (!source) { continue; }
  19912. if (typeof source !== 'object') {
  19913. throw new TypeError(source + 'must be non-object');
  19914. }
  19915. for (var p in source) {
  19916. if (source.hasOwnProperty(p)) {
  19917. obj[p] = source[p];
  19918. }
  19919. }
  19920. }
  19921. return obj;
  19922. };
  19923. // reduce buffer size, avoiding mem copy
  19924. exports.shrinkBuf = function (buf, size) {
  19925. if (buf.length === size) { return buf; }
  19926. if (buf.subarray) { return buf.subarray(0, size); }
  19927. buf.length = size;
  19928. return buf;
  19929. };
  19930. var fnTyped = {
  19931. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19932. if (src.subarray && dest.subarray) {
  19933. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19934. return;
  19935. }
  19936. // Fallback to ordinary array
  19937. for (var i=0; i<len; i++) {
  19938. dest[dest_offs + i] = src[src_offs + i];
  19939. }
  19940. },
  19941. // Join array of chunks to single array.
  19942. flattenChunks: function(chunks) {
  19943. var i, l, len, pos, chunk, result;
  19944. // calculate data length
  19945. len = 0;
  19946. for (i=0, l=chunks.length; i<l; i++) {
  19947. len += chunks[i].length;
  19948. }
  19949. // join chunks
  19950. result = new Uint8Array(len);
  19951. pos = 0;
  19952. for (i=0, l=chunks.length; i<l; i++) {
  19953. chunk = chunks[i];
  19954. result.set(chunk, pos);
  19955. pos += chunk.length;
  19956. }
  19957. return result;
  19958. }
  19959. };
  19960. var fnUntyped = {
  19961. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19962. for (var i=0; i<len; i++) {
  19963. dest[dest_offs + i] = src[src_offs + i];
  19964. }
  19965. },
  19966. // Join array of chunks to single array.
  19967. flattenChunks: function(chunks) {
  19968. return [].concat.apply([], chunks);
  19969. }
  19970. };
  19971. // Enable/Disable typed arrays use, for testing
  19972. //
  19973. exports.setTyped = function (on) {
  19974. if (on) {
  19975. exports.Buf8 = Uint8Array;
  19976. exports.Buf16 = Uint16Array;
  19977. exports.Buf32 = Int32Array;
  19978. exports.assign(exports, fnTyped);
  19979. } else {
  19980. exports.Buf8 = Array;
  19981. exports.Buf16 = Array;
  19982. exports.Buf32 = Array;
  19983. exports.assign(exports, fnUntyped);
  19984. }
  19985. };
  19986. exports.setTyped(TYPED_OK);
  19987. },{}],73:[function(require,module,exports){
  19988. // String encode/decode helpers
  19989. 'use strict';
  19990. var utils = require('./common');
  19991. // Quick check if we can use fast array to bin string conversion
  19992. //
  19993. // - apply(Array) can fail on Android 2.2
  19994. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19995. //
  19996. var STR_APPLY_OK = true;
  19997. var STR_APPLY_UIA_OK = true;
  19998. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19999. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20000. // Table with utf8 lengths (calculated by first byte of sequence)
  20001. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20002. // because max possible codepoint is 0x10ffff
  20003. var _utf8len = new utils.Buf8(256);
  20004. for (var q=0; q<256; q++) {
  20005. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20006. }
  20007. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20008. // convert string to array (typed, when possible)
  20009. exports.string2buf = function (str) {
  20010. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20011. // count binary size
  20012. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20013. c = str.charCodeAt(m_pos);
  20014. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20015. c2 = str.charCodeAt(m_pos+1);
  20016. if ((c2 & 0xfc00) === 0xdc00) {
  20017. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20018. m_pos++;
  20019. }
  20020. }
  20021. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20022. }
  20023. // allocate buffer
  20024. buf = new utils.Buf8(buf_len);
  20025. // convert
  20026. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20027. c = str.charCodeAt(m_pos);
  20028. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20029. c2 = str.charCodeAt(m_pos+1);
  20030. if ((c2 & 0xfc00) === 0xdc00) {
  20031. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20032. m_pos++;
  20033. }
  20034. }
  20035. if (c < 0x80) {
  20036. /* one byte */
  20037. buf[i++] = c;
  20038. } else if (c < 0x800) {
  20039. /* two bytes */
  20040. buf[i++] = 0xC0 | (c >>> 6);
  20041. buf[i++] = 0x80 | (c & 0x3f);
  20042. } else if (c < 0x10000) {
  20043. /* three bytes */
  20044. buf[i++] = 0xE0 | (c >>> 12);
  20045. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20046. buf[i++] = 0x80 | (c & 0x3f);
  20047. } else {
  20048. /* four bytes */
  20049. buf[i++] = 0xf0 | (c >>> 18);
  20050. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20051. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20052. buf[i++] = 0x80 | (c & 0x3f);
  20053. }
  20054. }
  20055. return buf;
  20056. };
  20057. // Helper (used in 2 places)
  20058. function buf2binstring(buf, len) {
  20059. // use fallback for big arrays to avoid stack overflow
  20060. if (len < 65537) {
  20061. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20062. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20063. }
  20064. }
  20065. var result = '';
  20066. for (var i=0; i < len; i++) {
  20067. result += String.fromCharCode(buf[i]);
  20068. }
  20069. return result;
  20070. }
  20071. // Convert byte array to binary string
  20072. exports.buf2binstring = function(buf) {
  20073. return buf2binstring(buf, buf.length);
  20074. };
  20075. // Convert binary string (typed, when possible)
  20076. exports.binstring2buf = function(str) {
  20077. var buf = new utils.Buf8(str.length);
  20078. for (var i=0, len=buf.length; i < len; i++) {
  20079. buf[i] = str.charCodeAt(i);
  20080. }
  20081. return buf;
  20082. };
  20083. // convert array to string
  20084. exports.buf2string = function (buf, max) {
  20085. var i, out, c, c_len;
  20086. var len = max || buf.length;
  20087. // Reserve max possible length (2 words per char)
  20088. // NB: by unknown reasons, Array is significantly faster for
  20089. // String.fromCharCode.apply than Uint16Array.
  20090. var utf16buf = new Array(len*2);
  20091. for (out=0, i=0; i<len;) {
  20092. c = buf[i++];
  20093. // quick process ascii
  20094. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20095. c_len = _utf8len[c];
  20096. // skip 5 & 6 byte codes
  20097. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20098. // apply mask on first byte
  20099. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20100. // join the rest
  20101. while (c_len > 1 && i < len) {
  20102. c = (c << 6) | (buf[i++] & 0x3f);
  20103. c_len--;
  20104. }
  20105. // terminated by end of string?
  20106. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20107. if (c < 0x10000) {
  20108. utf16buf[out++] = c;
  20109. } else {
  20110. c -= 0x10000;
  20111. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20112. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20113. }
  20114. }
  20115. return buf2binstring(utf16buf, out);
  20116. };
  20117. // Calculate max possible position in utf8 buffer,
  20118. // that will not break sequence. If that's not possible
  20119. // - (very small limits) return max size as is.
  20120. //
  20121. // buf[] - utf8 bytes array
  20122. // max - length limit (mandatory);
  20123. exports.utf8border = function(buf, max) {
  20124. var pos;
  20125. max = max || buf.length;
  20126. if (max > buf.length) { max = buf.length; }
  20127. // go back from last position, until start of sequence found
  20128. pos = max-1;
  20129. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20130. // Fuckup - very small and broken sequence,
  20131. // return max, because we should return something anyway.
  20132. if (pos < 0) { return max; }
  20133. // If we came to start of buffer - that means vuffer is too small,
  20134. // return max too.
  20135. if (pos === 0) { return max; }
  20136. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20137. };
  20138. },{"./common":72}],74:[function(require,module,exports){
  20139. 'use strict';
  20140. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20141. // It doesn't worth to make additional optimizationa as in original.
  20142. // Small size is preferable.
  20143. function adler32(adler, buf, len, pos) {
  20144. var s1 = (adler & 0xffff) |0,
  20145. s2 = ((adler >>> 16) & 0xffff) |0,
  20146. n = 0;
  20147. while (len !== 0) {
  20148. // Set limit ~ twice less than 5552, to keep
  20149. // s2 in 31-bits, because we force signed ints.
  20150. // in other case %= will fail.
  20151. n = len > 2000 ? 2000 : len;
  20152. len -= n;
  20153. do {
  20154. s1 = (s1 + buf[pos++]) |0;
  20155. s2 = (s2 + s1) |0;
  20156. } while (--n);
  20157. s1 %= 65521;
  20158. s2 %= 65521;
  20159. }
  20160. return (s1 | (s2 << 16)) |0;
  20161. }
  20162. module.exports = adler32;
  20163. },{}],75:[function(require,module,exports){
  20164. module.exports = {
  20165. /* Allowed flush values; see deflate() and inflate() below for details */
  20166. Z_NO_FLUSH: 0,
  20167. Z_PARTIAL_FLUSH: 1,
  20168. Z_SYNC_FLUSH: 2,
  20169. Z_FULL_FLUSH: 3,
  20170. Z_FINISH: 4,
  20171. Z_BLOCK: 5,
  20172. Z_TREES: 6,
  20173. /* Return codes for the compression/decompression functions. Negative values
  20174. * are errors, positive values are used for special but normal events.
  20175. */
  20176. Z_OK: 0,
  20177. Z_STREAM_END: 1,
  20178. Z_NEED_DICT: 2,
  20179. Z_ERRNO: -1,
  20180. Z_STREAM_ERROR: -2,
  20181. Z_DATA_ERROR: -3,
  20182. //Z_MEM_ERROR: -4,
  20183. Z_BUF_ERROR: -5,
  20184. //Z_VERSION_ERROR: -6,
  20185. /* compression levels */
  20186. Z_NO_COMPRESSION: 0,
  20187. Z_BEST_SPEED: 1,
  20188. Z_BEST_COMPRESSION: 9,
  20189. Z_DEFAULT_COMPRESSION: -1,
  20190. Z_FILTERED: 1,
  20191. Z_HUFFMAN_ONLY: 2,
  20192. Z_RLE: 3,
  20193. Z_FIXED: 4,
  20194. Z_DEFAULT_STRATEGY: 0,
  20195. /* Possible values of the data_type field (though see inflate()) */
  20196. Z_BINARY: 0,
  20197. Z_TEXT: 1,
  20198. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20199. Z_UNKNOWN: 2,
  20200. /* The deflate compression method */
  20201. Z_DEFLATED: 8
  20202. //Z_NULL: null // Use -1 or null inline, depending on var type
  20203. };
  20204. },{}],76:[function(require,module,exports){
  20205. 'use strict';
  20206. // Note: we can't get significant speed boost here.
  20207. // So write code to minimize size - no pregenerated tables
  20208. // and array tools dependencies.
  20209. // Use ordinary array, since untyped makes no boost here
  20210. function makeTable() {
  20211. var c, table = [];
  20212. for (var n =0; n < 256; n++) {
  20213. c = n;
  20214. for (var k =0; k < 8; k++) {
  20215. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20216. }
  20217. table[n] = c;
  20218. }
  20219. return table;
  20220. }
  20221. // Create table on load. Just 255 signed longs. Not a problem.
  20222. var crcTable = makeTable();
  20223. function crc32(crc, buf, len, pos) {
  20224. var t = crcTable,
  20225. end = pos + len;
  20226. crc = crc ^ (-1);
  20227. for (var i = pos; i < end; i++) {
  20228. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20229. }
  20230. return (crc ^ (-1)); // >>> 0;
  20231. }
  20232. module.exports = crc32;
  20233. },{}],77:[function(require,module,exports){
  20234. 'use strict';
  20235. var utils = require('../utils/common');
  20236. var trees = require('./trees');
  20237. var adler32 = require('./adler32');
  20238. var crc32 = require('./crc32');
  20239. var msg = require('./messages');
  20240. /* Public constants ==========================================================*/
  20241. /* ===========================================================================*/
  20242. /* Allowed flush values; see deflate() and inflate() below for details */
  20243. var Z_NO_FLUSH = 0;
  20244. var Z_PARTIAL_FLUSH = 1;
  20245. //var Z_SYNC_FLUSH = 2;
  20246. var Z_FULL_FLUSH = 3;
  20247. var Z_FINISH = 4;
  20248. var Z_BLOCK = 5;
  20249. //var Z_TREES = 6;
  20250. /* Return codes for the compression/decompression functions. Negative values
  20251. * are errors, positive values are used for special but normal events.
  20252. */
  20253. var Z_OK = 0;
  20254. var Z_STREAM_END = 1;
  20255. //var Z_NEED_DICT = 2;
  20256. //var Z_ERRNO = -1;
  20257. var Z_STREAM_ERROR = -2;
  20258. var Z_DATA_ERROR = -3;
  20259. //var Z_MEM_ERROR = -4;
  20260. var Z_BUF_ERROR = -5;
  20261. //var Z_VERSION_ERROR = -6;
  20262. /* compression levels */
  20263. //var Z_NO_COMPRESSION = 0;
  20264. //var Z_BEST_SPEED = 1;
  20265. //var Z_BEST_COMPRESSION = 9;
  20266. var Z_DEFAULT_COMPRESSION = -1;
  20267. var Z_FILTERED = 1;
  20268. var Z_HUFFMAN_ONLY = 2;
  20269. var Z_RLE = 3;
  20270. var Z_FIXED = 4;
  20271. var Z_DEFAULT_STRATEGY = 0;
  20272. /* Possible values of the data_type field (though see inflate()) */
  20273. //var Z_BINARY = 0;
  20274. //var Z_TEXT = 1;
  20275. //var Z_ASCII = 1; // = Z_TEXT
  20276. var Z_UNKNOWN = 2;
  20277. /* The deflate compression method */
  20278. var Z_DEFLATED = 8;
  20279. /*============================================================================*/
  20280. var MAX_MEM_LEVEL = 9;
  20281. /* Maximum value for memLevel in deflateInit2 */
  20282. var MAX_WBITS = 15;
  20283. /* 32K LZ77 window */
  20284. var DEF_MEM_LEVEL = 8;
  20285. var LENGTH_CODES = 29;
  20286. /* number of length codes, not counting the special END_BLOCK code */
  20287. var LITERALS = 256;
  20288. /* number of literal bytes 0..255 */
  20289. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20290. /* number of Literal or Length codes, including the END_BLOCK code */
  20291. var D_CODES = 30;
  20292. /* number of distance codes */
  20293. var BL_CODES = 19;
  20294. /* number of codes used to transfer the bit lengths */
  20295. var HEAP_SIZE = 2*L_CODES + 1;
  20296. /* maximum heap size */
  20297. var MAX_BITS = 15;
  20298. /* All codes must not exceed MAX_BITS bits */
  20299. var MIN_MATCH = 3;
  20300. var MAX_MATCH = 258;
  20301. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20302. var PRESET_DICT = 0x20;
  20303. var INIT_STATE = 42;
  20304. var EXTRA_STATE = 69;
  20305. var NAME_STATE = 73;
  20306. var COMMENT_STATE = 91;
  20307. var HCRC_STATE = 103;
  20308. var BUSY_STATE = 113;
  20309. var FINISH_STATE = 666;
  20310. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20311. var BS_BLOCK_DONE = 2; /* block flush performed */
  20312. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20313. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20314. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20315. function err(strm, errorCode) {
  20316. strm.msg = msg[errorCode];
  20317. return errorCode;
  20318. }
  20319. function rank(f) {
  20320. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20321. }
  20322. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20323. /* =========================================================================
  20324. * Flush as much pending output as possible. All deflate() output goes
  20325. * through this function so some applications may wish to modify it
  20326. * to avoid allocating a large strm->output buffer and copying into it.
  20327. * (See also read_buf()).
  20328. */
  20329. function flush_pending(strm) {
  20330. var s = strm.state;
  20331. //_tr_flush_bits(s);
  20332. var len = s.pending;
  20333. if (len > strm.avail_out) {
  20334. len = strm.avail_out;
  20335. }
  20336. if (len === 0) { return; }
  20337. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20338. strm.next_out += len;
  20339. s.pending_out += len;
  20340. strm.total_out += len;
  20341. strm.avail_out -= len;
  20342. s.pending -= len;
  20343. if (s.pending === 0) {
  20344. s.pending_out = 0;
  20345. }
  20346. }
  20347. function flush_block_only (s, last) {
  20348. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20349. s.block_start = s.strstart;
  20350. flush_pending(s.strm);
  20351. }
  20352. function put_byte(s, b) {
  20353. s.pending_buf[s.pending++] = b;
  20354. }
  20355. /* =========================================================================
  20356. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20357. * IN assertion: the stream state is correct and there is enough room in
  20358. * pending_buf.
  20359. */
  20360. function putShortMSB(s, b) {
  20361. // put_byte(s, (Byte)(b >> 8));
  20362. // put_byte(s, (Byte)(b & 0xff));
  20363. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20364. s.pending_buf[s.pending++] = b & 0xff;
  20365. }
  20366. /* ===========================================================================
  20367. * Read a new buffer from the current input stream, update the adler32
  20368. * and total number of bytes read. All deflate() input goes through
  20369. * this function so some applications may wish to modify it to avoid
  20370. * allocating a large strm->input buffer and copying from it.
  20371. * (See also flush_pending()).
  20372. */
  20373. function read_buf(strm, buf, start, size) {
  20374. var len = strm.avail_in;
  20375. if (len > size) { len = size; }
  20376. if (len === 0) { return 0; }
  20377. strm.avail_in -= len;
  20378. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20379. if (strm.state.wrap === 1) {
  20380. strm.adler = adler32(strm.adler, buf, len, start);
  20381. }
  20382. else if (strm.state.wrap === 2) {
  20383. strm.adler = crc32(strm.adler, buf, len, start);
  20384. }
  20385. strm.next_in += len;
  20386. strm.total_in += len;
  20387. return len;
  20388. }
  20389. /* ===========================================================================
  20390. * Set match_start to the longest match starting at the given string and
  20391. * return its length. Matches shorter or equal to prev_length are discarded,
  20392. * in which case the result is equal to prev_length and match_start is
  20393. * garbage.
  20394. * IN assertions: cur_match is the head of the hash chain for the current
  20395. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20396. * OUT assertion: the match length is not greater than s->lookahead.
  20397. */
  20398. function longest_match(s, cur_match) {
  20399. var chain_length = s.max_chain_length; /* max hash chain length */
  20400. var scan = s.strstart; /* current string */
  20401. var match; /* matched string */
  20402. var len; /* length of current match */
  20403. var best_len = s.prev_length; /* best match length so far */
  20404. var nice_match = s.nice_match; /* stop if match long enough */
  20405. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20406. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20407. var _win = s.window; // shortcut
  20408. var wmask = s.w_mask;
  20409. var prev = s.prev;
  20410. /* Stop when cur_match becomes <= limit. To simplify the code,
  20411. * we prevent matches with the string of window index 0.
  20412. */
  20413. var strend = s.strstart + MAX_MATCH;
  20414. var scan_end1 = _win[scan + best_len - 1];
  20415. var scan_end = _win[scan + best_len];
  20416. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20417. * It is easy to get rid of this optimization if necessary.
  20418. */
  20419. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20420. /* Do not waste too much time if we already have a good match: */
  20421. if (s.prev_length >= s.good_match) {
  20422. chain_length >>= 2;
  20423. }
  20424. /* Do not look for matches beyond the end of the input. This is necessary
  20425. * to make deflate deterministic.
  20426. */
  20427. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20428. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20429. do {
  20430. // Assert(cur_match < s->strstart, "no future");
  20431. match = cur_match;
  20432. /* Skip to next match if the match length cannot increase
  20433. * or if the match length is less than 2. Note that the checks below
  20434. * for insufficient lookahead only occur occasionally for performance
  20435. * reasons. Therefore uninitialized memory will be accessed, and
  20436. * conditional jumps will be made that depend on those values.
  20437. * However the length of the match is limited to the lookahead, so
  20438. * the output of deflate is not affected by the uninitialized values.
  20439. */
  20440. if (_win[match + best_len] !== scan_end ||
  20441. _win[match + best_len - 1] !== scan_end1 ||
  20442. _win[match] !== _win[scan] ||
  20443. _win[++match] !== _win[scan + 1]) {
  20444. continue;
  20445. }
  20446. /* The check at best_len-1 can be removed because it will be made
  20447. * again later. (This heuristic is not always a win.)
  20448. * It is not necessary to compare scan[2] and match[2] since they
  20449. * are always equal when the other bytes match, given that
  20450. * the hash keys are equal and that HASH_BITS >= 8.
  20451. */
  20452. scan += 2;
  20453. match++;
  20454. // Assert(*scan == *match, "match[2]?");
  20455. /* We check for insufficient lookahead only every 8th comparison;
  20456. * the 256th check will be made at strstart+258.
  20457. */
  20458. do {
  20459. /*jshint noempty:false*/
  20460. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20461. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20462. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20463. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20464. scan < strend);
  20465. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20466. len = MAX_MATCH - (strend - scan);
  20467. scan = strend - MAX_MATCH;
  20468. if (len > best_len) {
  20469. s.match_start = cur_match;
  20470. best_len = len;
  20471. if (len >= nice_match) {
  20472. break;
  20473. }
  20474. scan_end1 = _win[scan + best_len - 1];
  20475. scan_end = _win[scan + best_len];
  20476. }
  20477. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20478. if (best_len <= s.lookahead) {
  20479. return best_len;
  20480. }
  20481. return s.lookahead;
  20482. }
  20483. /* ===========================================================================
  20484. * Fill the window when the lookahead becomes insufficient.
  20485. * Updates strstart and lookahead.
  20486. *
  20487. * IN assertion: lookahead < MIN_LOOKAHEAD
  20488. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20489. * At least one byte has been read, or avail_in == 0; reads are
  20490. * performed for at least two bytes (required for the zip translate_eol
  20491. * option -- not supported here).
  20492. */
  20493. function fill_window(s) {
  20494. var _w_size = s.w_size;
  20495. var p, n, m, more, str;
  20496. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20497. do {
  20498. more = s.window_size - s.lookahead - s.strstart;
  20499. // JS ints have 32 bit, block below not needed
  20500. /* Deal with !@#$% 64K limit: */
  20501. //if (sizeof(int) <= 2) {
  20502. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20503. // more = wsize;
  20504. //
  20505. // } else if (more == (unsigned)(-1)) {
  20506. // /* Very unlikely, but possible on 16 bit machine if
  20507. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20508. // */
  20509. // more--;
  20510. // }
  20511. //}
  20512. /* If the window is almost full and there is insufficient lookahead,
  20513. * move the upper half to the lower one to make room in the upper half.
  20514. */
  20515. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20516. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20517. s.match_start -= _w_size;
  20518. s.strstart -= _w_size;
  20519. /* we now have strstart >= MAX_DIST */
  20520. s.block_start -= _w_size;
  20521. /* Slide the hash table (could be avoided with 32 bit values
  20522. at the expense of memory usage). We slide even when level == 0
  20523. to keep the hash table consistent if we switch back to level > 0
  20524. later. (Using level 0 permanently is not an optimal usage of
  20525. zlib, so we don't care about this pathological case.)
  20526. */
  20527. n = s.hash_size;
  20528. p = n;
  20529. do {
  20530. m = s.head[--p];
  20531. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20532. } while (--n);
  20533. n = _w_size;
  20534. p = n;
  20535. do {
  20536. m = s.prev[--p];
  20537. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20538. /* If n is not on any hash chain, prev[n] is garbage but
  20539. * its value will never be used.
  20540. */
  20541. } while (--n);
  20542. more += _w_size;
  20543. }
  20544. if (s.strm.avail_in === 0) {
  20545. break;
  20546. }
  20547. /* If there was no sliding:
  20548. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20549. * more == window_size - lookahead - strstart
  20550. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20551. * => more >= window_size - 2*WSIZE + 2
  20552. * In the BIG_MEM or MMAP case (not yet supported),
  20553. * window_size == input_size + MIN_LOOKAHEAD &&
  20554. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20555. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20556. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20557. */
  20558. //Assert(more >= 2, "more < 2");
  20559. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20560. s.lookahead += n;
  20561. /* Initialize the hash value now that we have some input: */
  20562. if (s.lookahead + s.insert >= MIN_MATCH) {
  20563. str = s.strstart - s.insert;
  20564. s.ins_h = s.window[str];
  20565. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20566. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20567. //#if MIN_MATCH != 3
  20568. // Call update_hash() MIN_MATCH-3 more times
  20569. //#endif
  20570. while (s.insert) {
  20571. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20572. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20573. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20574. s.head[s.ins_h] = str;
  20575. str++;
  20576. s.insert--;
  20577. if (s.lookahead + s.insert < MIN_MATCH) {
  20578. break;
  20579. }
  20580. }
  20581. }
  20582. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20583. * but this is not important since only literal bytes will be emitted.
  20584. */
  20585. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20586. /* If the WIN_INIT bytes after the end of the current data have never been
  20587. * written, then zero those bytes in order to avoid memory check reports of
  20588. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20589. * the longest match routines. Update the high water mark for the next
  20590. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20591. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20592. */
  20593. // if (s.high_water < s.window_size) {
  20594. // var curr = s.strstart + s.lookahead;
  20595. // var init = 0;
  20596. //
  20597. // if (s.high_water < curr) {
  20598. // /* Previous high water mark below current data -- zero WIN_INIT
  20599. // * bytes or up to end of window, whichever is less.
  20600. // */
  20601. // init = s.window_size - curr;
  20602. // if (init > WIN_INIT)
  20603. // init = WIN_INIT;
  20604. // zmemzero(s->window + curr, (unsigned)init);
  20605. // s->high_water = curr + init;
  20606. // }
  20607. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20608. // /* High water mark at or above current data, but below current data
  20609. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20610. // * to end of window, whichever is less.
  20611. // */
  20612. // init = (ulg)curr + WIN_INIT - s->high_water;
  20613. // if (init > s->window_size - s->high_water)
  20614. // init = s->window_size - s->high_water;
  20615. // zmemzero(s->window + s->high_water, (unsigned)init);
  20616. // s->high_water += init;
  20617. // }
  20618. // }
  20619. //
  20620. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20621. // "not enough room for search");
  20622. }
  20623. /* ===========================================================================
  20624. * Copy without compression as much as possible from the input stream, return
  20625. * the current block state.
  20626. * This function does not insert new strings in the dictionary since
  20627. * uncompressible data is probably not useful. This function is used
  20628. * only for the level=0 compression option.
  20629. * NOTE: this function should be optimized to avoid extra copying from
  20630. * window to pending_buf.
  20631. */
  20632. function deflate_stored(s, flush) {
  20633. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20634. * to pending_buf_size, and each stored block has a 5 byte header:
  20635. */
  20636. var max_block_size = 0xffff;
  20637. if (max_block_size > s.pending_buf_size - 5) {
  20638. max_block_size = s.pending_buf_size - 5;
  20639. }
  20640. /* Copy as much as possible from input to output: */
  20641. for (;;) {
  20642. /* Fill the window as much as possible: */
  20643. if (s.lookahead <= 1) {
  20644. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20645. // s->block_start >= (long)s->w_size, "slide too late");
  20646. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20647. // s.block_start >= s.w_size)) {
  20648. // throw new Error("slide too late");
  20649. // }
  20650. fill_window(s);
  20651. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20652. return BS_NEED_MORE;
  20653. }
  20654. if (s.lookahead === 0) {
  20655. break;
  20656. }
  20657. /* flush the current block */
  20658. }
  20659. //Assert(s->block_start >= 0L, "block gone");
  20660. // if (s.block_start < 0) throw new Error("block gone");
  20661. s.strstart += s.lookahead;
  20662. s.lookahead = 0;
  20663. /* Emit a stored block if pending_buf will be full: */
  20664. var max_start = s.block_start + max_block_size;
  20665. if (s.strstart === 0 || s.strstart >= max_start) {
  20666. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20667. s.lookahead = s.strstart - max_start;
  20668. s.strstart = max_start;
  20669. /*** FLUSH_BLOCK(s, 0); ***/
  20670. flush_block_only(s, false);
  20671. if (s.strm.avail_out === 0) {
  20672. return BS_NEED_MORE;
  20673. }
  20674. /***/
  20675. }
  20676. /* Flush if we may have to slide, otherwise block_start may become
  20677. * negative and the data will be gone:
  20678. */
  20679. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20680. /*** FLUSH_BLOCK(s, 0); ***/
  20681. flush_block_only(s, false);
  20682. if (s.strm.avail_out === 0) {
  20683. return BS_NEED_MORE;
  20684. }
  20685. /***/
  20686. }
  20687. }
  20688. s.insert = 0;
  20689. if (flush === Z_FINISH) {
  20690. /*** FLUSH_BLOCK(s, 1); ***/
  20691. flush_block_only(s, true);
  20692. if (s.strm.avail_out === 0) {
  20693. return BS_FINISH_STARTED;
  20694. }
  20695. /***/
  20696. return BS_FINISH_DONE;
  20697. }
  20698. if (s.strstart > s.block_start) {
  20699. /*** FLUSH_BLOCK(s, 0); ***/
  20700. flush_block_only(s, false);
  20701. if (s.strm.avail_out === 0) {
  20702. return BS_NEED_MORE;
  20703. }
  20704. /***/
  20705. }
  20706. return BS_NEED_MORE;
  20707. }
  20708. /* ===========================================================================
  20709. * Compress as much as possible from the input stream, return the current
  20710. * block state.
  20711. * This function does not perform lazy evaluation of matches and inserts
  20712. * new strings in the dictionary only for unmatched strings or for short
  20713. * matches. It is used only for the fast compression options.
  20714. */
  20715. function deflate_fast(s, flush) {
  20716. var hash_head; /* head of the hash chain */
  20717. var bflush; /* set if current block must be flushed */
  20718. for (;;) {
  20719. /* Make sure that we always have enough lookahead, except
  20720. * at the end of the input file. We need MAX_MATCH bytes
  20721. * for the next match, plus MIN_MATCH bytes to insert the
  20722. * string following the next match.
  20723. */
  20724. if (s.lookahead < MIN_LOOKAHEAD) {
  20725. fill_window(s);
  20726. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20727. return BS_NEED_MORE;
  20728. }
  20729. if (s.lookahead === 0) {
  20730. break; /* flush the current block */
  20731. }
  20732. }
  20733. /* Insert the string window[strstart .. strstart+2] in the
  20734. * dictionary, and set hash_head to the head of the hash chain:
  20735. */
  20736. hash_head = 0/*NIL*/;
  20737. if (s.lookahead >= MIN_MATCH) {
  20738. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20739. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20740. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20741. s.head[s.ins_h] = s.strstart;
  20742. /***/
  20743. }
  20744. /* Find the longest match, discarding those <= prev_length.
  20745. * At this point we have always match_length < MIN_MATCH
  20746. */
  20747. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20748. /* To simplify the code, we prevent matches with the string
  20749. * of window index 0 (in particular we have to avoid a match
  20750. * of the string with itself at the start of the input file).
  20751. */
  20752. s.match_length = longest_match(s, hash_head);
  20753. /* longest_match() sets match_start */
  20754. }
  20755. if (s.match_length >= MIN_MATCH) {
  20756. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20757. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20758. s.match_length - MIN_MATCH, bflush); ***/
  20759. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20760. s.lookahead -= s.match_length;
  20761. /* Insert new strings in the hash table only if the match length
  20762. * is not too large. This saves time but degrades compression.
  20763. */
  20764. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20765. s.match_length--; /* string at strstart already in table */
  20766. do {
  20767. s.strstart++;
  20768. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20769. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20770. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20771. s.head[s.ins_h] = s.strstart;
  20772. /***/
  20773. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20774. * always MIN_MATCH bytes ahead.
  20775. */
  20776. } while (--s.match_length !== 0);
  20777. s.strstart++;
  20778. } else
  20779. {
  20780. s.strstart += s.match_length;
  20781. s.match_length = 0;
  20782. s.ins_h = s.window[s.strstart];
  20783. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20784. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20785. //#if MIN_MATCH != 3
  20786. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20787. //#endif
  20788. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20789. * matter since it will be recomputed at next deflate call.
  20790. */
  20791. }
  20792. } else {
  20793. /* No match, output a literal byte */
  20794. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20795. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20796. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20797. s.lookahead--;
  20798. s.strstart++;
  20799. }
  20800. if (bflush) {
  20801. /*** FLUSH_BLOCK(s, 0); ***/
  20802. flush_block_only(s, false);
  20803. if (s.strm.avail_out === 0) {
  20804. return BS_NEED_MORE;
  20805. }
  20806. /***/
  20807. }
  20808. }
  20809. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20810. if (flush === Z_FINISH) {
  20811. /*** FLUSH_BLOCK(s, 1); ***/
  20812. flush_block_only(s, true);
  20813. if (s.strm.avail_out === 0) {
  20814. return BS_FINISH_STARTED;
  20815. }
  20816. /***/
  20817. return BS_FINISH_DONE;
  20818. }
  20819. if (s.last_lit) {
  20820. /*** FLUSH_BLOCK(s, 0); ***/
  20821. flush_block_only(s, false);
  20822. if (s.strm.avail_out === 0) {
  20823. return BS_NEED_MORE;
  20824. }
  20825. /***/
  20826. }
  20827. return BS_BLOCK_DONE;
  20828. }
  20829. /* ===========================================================================
  20830. * Same as above, but achieves better compression. We use a lazy
  20831. * evaluation for matches: a match is finally adopted only if there is
  20832. * no better match at the next window position.
  20833. */
  20834. function deflate_slow(s, flush) {
  20835. var hash_head; /* head of hash chain */
  20836. var bflush; /* set if current block must be flushed */
  20837. var max_insert;
  20838. /* Process the input block. */
  20839. for (;;) {
  20840. /* Make sure that we always have enough lookahead, except
  20841. * at the end of the input file. We need MAX_MATCH bytes
  20842. * for the next match, plus MIN_MATCH bytes to insert the
  20843. * string following the next match.
  20844. */
  20845. if (s.lookahead < MIN_LOOKAHEAD) {
  20846. fill_window(s);
  20847. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20848. return BS_NEED_MORE;
  20849. }
  20850. if (s.lookahead === 0) { break; } /* flush the current block */
  20851. }
  20852. /* Insert the string window[strstart .. strstart+2] in the
  20853. * dictionary, and set hash_head to the head of the hash chain:
  20854. */
  20855. hash_head = 0/*NIL*/;
  20856. if (s.lookahead >= MIN_MATCH) {
  20857. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20858. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20859. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20860. s.head[s.ins_h] = s.strstart;
  20861. /***/
  20862. }
  20863. /* Find the longest match, discarding those <= prev_length.
  20864. */
  20865. s.prev_length = s.match_length;
  20866. s.prev_match = s.match_start;
  20867. s.match_length = MIN_MATCH-1;
  20868. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20869. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20870. /* To simplify the code, we prevent matches with the string
  20871. * of window index 0 (in particular we have to avoid a match
  20872. * of the string with itself at the start of the input file).
  20873. */
  20874. s.match_length = longest_match(s, hash_head);
  20875. /* longest_match() sets match_start */
  20876. if (s.match_length <= 5 &&
  20877. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20878. /* If prev_match is also MIN_MATCH, match_start is garbage
  20879. * but we will ignore the current match anyway.
  20880. */
  20881. s.match_length = MIN_MATCH-1;
  20882. }
  20883. }
  20884. /* If there was a match at the previous step and the current
  20885. * match is not better, output the previous match:
  20886. */
  20887. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20888. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20889. /* Do not insert strings in hash table beyond this. */
  20890. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20891. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20892. s.prev_length - MIN_MATCH, bflush);***/
  20893. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20894. /* Insert in hash table all strings up to the end of the match.
  20895. * strstart-1 and strstart are already inserted. If there is not
  20896. * enough lookahead, the last two strings are not inserted in
  20897. * the hash table.
  20898. */
  20899. s.lookahead -= s.prev_length-1;
  20900. s.prev_length -= 2;
  20901. do {
  20902. if (++s.strstart <= max_insert) {
  20903. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20904. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20905. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20906. s.head[s.ins_h] = s.strstart;
  20907. /***/
  20908. }
  20909. } while (--s.prev_length !== 0);
  20910. s.match_available = 0;
  20911. s.match_length = MIN_MATCH-1;
  20912. s.strstart++;
  20913. if (bflush) {
  20914. /*** FLUSH_BLOCK(s, 0); ***/
  20915. flush_block_only(s, false);
  20916. if (s.strm.avail_out === 0) {
  20917. return BS_NEED_MORE;
  20918. }
  20919. /***/
  20920. }
  20921. } else if (s.match_available) {
  20922. /* If there was no match at the previous position, output a
  20923. * single literal. If there was a match but the current match
  20924. * is longer, truncate the previous match to a single literal.
  20925. */
  20926. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20927. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20928. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20929. if (bflush) {
  20930. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20931. flush_block_only(s, false);
  20932. /***/
  20933. }
  20934. s.strstart++;
  20935. s.lookahead--;
  20936. if (s.strm.avail_out === 0) {
  20937. return BS_NEED_MORE;
  20938. }
  20939. } else {
  20940. /* There is no previous match to compare with, wait for
  20941. * the next step to decide.
  20942. */
  20943. s.match_available = 1;
  20944. s.strstart++;
  20945. s.lookahead--;
  20946. }
  20947. }
  20948. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20949. if (s.match_available) {
  20950. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20951. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20952. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20953. s.match_available = 0;
  20954. }
  20955. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20956. if (flush === Z_FINISH) {
  20957. /*** FLUSH_BLOCK(s, 1); ***/
  20958. flush_block_only(s, true);
  20959. if (s.strm.avail_out === 0) {
  20960. return BS_FINISH_STARTED;
  20961. }
  20962. /***/
  20963. return BS_FINISH_DONE;
  20964. }
  20965. if (s.last_lit) {
  20966. /*** FLUSH_BLOCK(s, 0); ***/
  20967. flush_block_only(s, false);
  20968. if (s.strm.avail_out === 0) {
  20969. return BS_NEED_MORE;
  20970. }
  20971. /***/
  20972. }
  20973. return BS_BLOCK_DONE;
  20974. }
  20975. /* ===========================================================================
  20976. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20977. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20978. * deflate switches away from Z_RLE.)
  20979. */
  20980. function deflate_rle(s, flush) {
  20981. var bflush; /* set if current block must be flushed */
  20982. var prev; /* byte at distance one to match */
  20983. var scan, strend; /* scan goes up to strend for length of run */
  20984. var _win = s.window;
  20985. for (;;) {
  20986. /* Make sure that we always have enough lookahead, except
  20987. * at the end of the input file. We need MAX_MATCH bytes
  20988. * for the longest run, plus one for the unrolled loop.
  20989. */
  20990. if (s.lookahead <= MAX_MATCH) {
  20991. fill_window(s);
  20992. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20993. return BS_NEED_MORE;
  20994. }
  20995. if (s.lookahead === 0) { break; } /* flush the current block */
  20996. }
  20997. /* See how many times the previous byte repeats */
  20998. s.match_length = 0;
  20999. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21000. scan = s.strstart - 1;
  21001. prev = _win[scan];
  21002. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21003. strend = s.strstart + MAX_MATCH;
  21004. do {
  21005. /*jshint noempty:false*/
  21006. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21007. prev === _win[++scan] && prev === _win[++scan] &&
  21008. prev === _win[++scan] && prev === _win[++scan] &&
  21009. prev === _win[++scan] && prev === _win[++scan] &&
  21010. scan < strend);
  21011. s.match_length = MAX_MATCH - (strend - scan);
  21012. if (s.match_length > s.lookahead) {
  21013. s.match_length = s.lookahead;
  21014. }
  21015. }
  21016. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21017. }
  21018. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21019. if (s.match_length >= MIN_MATCH) {
  21020. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21021. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21022. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21023. s.lookahead -= s.match_length;
  21024. s.strstart += s.match_length;
  21025. s.match_length = 0;
  21026. } else {
  21027. /* No match, output a literal byte */
  21028. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21029. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21030. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21031. s.lookahead--;
  21032. s.strstart++;
  21033. }
  21034. if (bflush) {
  21035. /*** FLUSH_BLOCK(s, 0); ***/
  21036. flush_block_only(s, false);
  21037. if (s.strm.avail_out === 0) {
  21038. return BS_NEED_MORE;
  21039. }
  21040. /***/
  21041. }
  21042. }
  21043. s.insert = 0;
  21044. if (flush === Z_FINISH) {
  21045. /*** FLUSH_BLOCK(s, 1); ***/
  21046. flush_block_only(s, true);
  21047. if (s.strm.avail_out === 0) {
  21048. return BS_FINISH_STARTED;
  21049. }
  21050. /***/
  21051. return BS_FINISH_DONE;
  21052. }
  21053. if (s.last_lit) {
  21054. /*** FLUSH_BLOCK(s, 0); ***/
  21055. flush_block_only(s, false);
  21056. if (s.strm.avail_out === 0) {
  21057. return BS_NEED_MORE;
  21058. }
  21059. /***/
  21060. }
  21061. return BS_BLOCK_DONE;
  21062. }
  21063. /* ===========================================================================
  21064. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21065. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21066. */
  21067. function deflate_huff(s, flush) {
  21068. var bflush; /* set if current block must be flushed */
  21069. for (;;) {
  21070. /* Make sure that we have a literal to write. */
  21071. if (s.lookahead === 0) {
  21072. fill_window(s);
  21073. if (s.lookahead === 0) {
  21074. if (flush === Z_NO_FLUSH) {
  21075. return BS_NEED_MORE;
  21076. }
  21077. break; /* flush the current block */
  21078. }
  21079. }
  21080. /* Output a literal byte */
  21081. s.match_length = 0;
  21082. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21083. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21084. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21085. s.lookahead--;
  21086. s.strstart++;
  21087. if (bflush) {
  21088. /*** FLUSH_BLOCK(s, 0); ***/
  21089. flush_block_only(s, false);
  21090. if (s.strm.avail_out === 0) {
  21091. return BS_NEED_MORE;
  21092. }
  21093. /***/
  21094. }
  21095. }
  21096. s.insert = 0;
  21097. if (flush === Z_FINISH) {
  21098. /*** FLUSH_BLOCK(s, 1); ***/
  21099. flush_block_only(s, true);
  21100. if (s.strm.avail_out === 0) {
  21101. return BS_FINISH_STARTED;
  21102. }
  21103. /***/
  21104. return BS_FINISH_DONE;
  21105. }
  21106. if (s.last_lit) {
  21107. /*** FLUSH_BLOCK(s, 0); ***/
  21108. flush_block_only(s, false);
  21109. if (s.strm.avail_out === 0) {
  21110. return BS_NEED_MORE;
  21111. }
  21112. /***/
  21113. }
  21114. return BS_BLOCK_DONE;
  21115. }
  21116. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21117. * the desired pack level (0..9). The values given below have been tuned to
  21118. * exclude worst case performance for pathological files. Better values may be
  21119. * found for specific files.
  21120. */
  21121. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21122. this.good_length = good_length;
  21123. this.max_lazy = max_lazy;
  21124. this.nice_length = nice_length;
  21125. this.max_chain = max_chain;
  21126. this.func = func;
  21127. };
  21128. var configuration_table;
  21129. configuration_table = [
  21130. /* good lazy nice chain */
  21131. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21132. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21133. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21134. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21135. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21136. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21137. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21138. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21139. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21140. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21141. ];
  21142. /* ===========================================================================
  21143. * Initialize the "longest match" routines for a new zlib stream
  21144. */
  21145. function lm_init(s) {
  21146. s.window_size = 2 * s.w_size;
  21147. /*** CLEAR_HASH(s); ***/
  21148. zero(s.head); // Fill with NIL (= 0);
  21149. /* Set the default configuration parameters:
  21150. */
  21151. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21152. s.good_match = configuration_table[s.level].good_length;
  21153. s.nice_match = configuration_table[s.level].nice_length;
  21154. s.max_chain_length = configuration_table[s.level].max_chain;
  21155. s.strstart = 0;
  21156. s.block_start = 0;
  21157. s.lookahead = 0;
  21158. s.insert = 0;
  21159. s.match_length = s.prev_length = MIN_MATCH - 1;
  21160. s.match_available = 0;
  21161. s.ins_h = 0;
  21162. }
  21163. function DeflateState() {
  21164. this.strm = null; /* pointer back to this zlib stream */
  21165. this.status = 0; /* as the name implies */
  21166. this.pending_buf = null; /* output still pending */
  21167. this.pending_buf_size = 0; /* size of pending_buf */
  21168. this.pending_out = 0; /* next pending byte to output to the stream */
  21169. this.pending = 0; /* nb of bytes in the pending buffer */
  21170. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21171. this.gzhead = null; /* gzip header information to write */
  21172. this.gzindex = 0; /* where in extra, name, or comment */
  21173. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21174. this.last_flush = -1; /* value of flush param for previous deflate call */
  21175. this.w_size = 0; /* LZ77 window size (32K by default) */
  21176. this.w_bits = 0; /* log2(w_size) (8..16) */
  21177. this.w_mask = 0; /* w_size - 1 */
  21178. this.window = null;
  21179. /* Sliding window. Input bytes are read into the second half of the window,
  21180. * and move to the first half later to keep a dictionary of at least wSize
  21181. * bytes. With this organization, matches are limited to a distance of
  21182. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21183. * performed with a length multiple of the block size.
  21184. */
  21185. this.window_size = 0;
  21186. /* Actual size of window: 2*wSize, except when the user input buffer
  21187. * is directly used as sliding window.
  21188. */
  21189. this.prev = null;
  21190. /* Link to older string with same hash index. To limit the size of this
  21191. * array to 64K, this link is maintained only for the last 32K strings.
  21192. * An index in this array is thus a window index modulo 32K.
  21193. */
  21194. this.head = null; /* Heads of the hash chains or NIL. */
  21195. this.ins_h = 0; /* hash index of string to be inserted */
  21196. this.hash_size = 0; /* number of elements in hash table */
  21197. this.hash_bits = 0; /* log2(hash_size) */
  21198. this.hash_mask = 0; /* hash_size-1 */
  21199. this.hash_shift = 0;
  21200. /* Number of bits by which ins_h must be shifted at each input
  21201. * step. It must be such that after MIN_MATCH steps, the oldest
  21202. * byte no longer takes part in the hash key, that is:
  21203. * hash_shift * MIN_MATCH >= hash_bits
  21204. */
  21205. this.block_start = 0;
  21206. /* Window position at the beginning of the current output block. Gets
  21207. * negative when the window is moved backwards.
  21208. */
  21209. this.match_length = 0; /* length of best match */
  21210. this.prev_match = 0; /* previous match */
  21211. this.match_available = 0; /* set if previous match exists */
  21212. this.strstart = 0; /* start of string to insert */
  21213. this.match_start = 0; /* start of matching string */
  21214. this.lookahead = 0; /* number of valid bytes ahead in window */
  21215. this.prev_length = 0;
  21216. /* Length of the best match at previous step. Matches not greater than this
  21217. * are discarded. This is used in the lazy match evaluation.
  21218. */
  21219. this.max_chain_length = 0;
  21220. /* To speed up deflation, hash chains are never searched beyond this
  21221. * length. A higher limit improves compression ratio but degrades the
  21222. * speed.
  21223. */
  21224. this.max_lazy_match = 0;
  21225. /* Attempt to find a better match only when the current match is strictly
  21226. * smaller than this value. This mechanism is used only for compression
  21227. * levels >= 4.
  21228. */
  21229. // That's alias to max_lazy_match, don't use directly
  21230. //this.max_insert_length = 0;
  21231. /* Insert new strings in the hash table only if the match length is not
  21232. * greater than this length. This saves time but degrades compression.
  21233. * max_insert_length is used only for compression levels <= 3.
  21234. */
  21235. this.level = 0; /* compression level (1..9) */
  21236. this.strategy = 0; /* favor or force Huffman coding*/
  21237. this.good_match = 0;
  21238. /* Use a faster search when the previous match is longer than this */
  21239. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21240. /* used by trees.c: */
  21241. /* Didn't use ct_data typedef below to suppress compiler warning */
  21242. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21243. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21244. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21245. // Use flat array of DOUBLE size, with interleaved fata,
  21246. // because JS does not support effective
  21247. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21248. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21249. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21250. zero(this.dyn_ltree);
  21251. zero(this.dyn_dtree);
  21252. zero(this.bl_tree);
  21253. this.l_desc = null; /* desc. for literal tree */
  21254. this.d_desc = null; /* desc. for distance tree */
  21255. this.bl_desc = null; /* desc. for bit length tree */
  21256. //ush bl_count[MAX_BITS+1];
  21257. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21258. /* number of codes at each bit length for an optimal tree */
  21259. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21260. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21261. zero(this.heap);
  21262. this.heap_len = 0; /* number of elements in the heap */
  21263. this.heap_max = 0; /* element of largest frequency */
  21264. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21265. * The same heap array is used to build all trees.
  21266. */
  21267. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21268. zero(this.depth);
  21269. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21270. */
  21271. this.l_buf = 0; /* buffer index for literals or lengths */
  21272. this.lit_bufsize = 0;
  21273. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21274. * limiting lit_bufsize to 64K:
  21275. * - frequencies can be kept in 16 bit counters
  21276. * - if compression is not successful for the first block, all input
  21277. * data is still in the window so we can still emit a stored block even
  21278. * when input comes from standard input. (This can also be done for
  21279. * all blocks if lit_bufsize is not greater than 32K.)
  21280. * - if compression is not successful for a file smaller than 64K, we can
  21281. * even emit a stored file instead of a stored block (saving 5 bytes).
  21282. * This is applicable only for zip (not gzip or zlib).
  21283. * - creating new Huffman trees less frequently may not provide fast
  21284. * adaptation to changes in the input data statistics. (Take for
  21285. * example a binary file with poorly compressible code followed by
  21286. * a highly compressible string table.) Smaller buffer sizes give
  21287. * fast adaptation but have of course the overhead of transmitting
  21288. * trees more frequently.
  21289. * - I can't count above 4
  21290. */
  21291. this.last_lit = 0; /* running index in l_buf */
  21292. this.d_buf = 0;
  21293. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21294. * the same number of elements. To use different lengths, an extra flag
  21295. * array would be necessary.
  21296. */
  21297. this.opt_len = 0; /* bit length of current block with optimal trees */
  21298. this.static_len = 0; /* bit length of current block with static trees */
  21299. this.matches = 0; /* number of string matches in current block */
  21300. this.insert = 0; /* bytes at end of window left to insert */
  21301. this.bi_buf = 0;
  21302. /* Output buffer. bits are inserted starting at the bottom (least
  21303. * significant bits).
  21304. */
  21305. this.bi_valid = 0;
  21306. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21307. * are always zero.
  21308. */
  21309. // Used for window memory init. We safely ignore it for JS. That makes
  21310. // sense only for pointers and memory check tools.
  21311. //this.high_water = 0;
  21312. /* High water mark offset in window for initialized bytes -- bytes above
  21313. * this are set to zero in order to avoid memory check warnings when
  21314. * longest match routines access bytes past the input. This is then
  21315. * updated to the new high water mark.
  21316. */
  21317. }
  21318. function deflateResetKeep(strm) {
  21319. var s;
  21320. if (!strm || !strm.state) {
  21321. return err(strm, Z_STREAM_ERROR);
  21322. }
  21323. strm.total_in = strm.total_out = 0;
  21324. strm.data_type = Z_UNKNOWN;
  21325. s = strm.state;
  21326. s.pending = 0;
  21327. s.pending_out = 0;
  21328. if (s.wrap < 0) {
  21329. s.wrap = -s.wrap;
  21330. /* was made negative by deflate(..., Z_FINISH); */
  21331. }
  21332. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21333. strm.adler = (s.wrap === 2) ?
  21334. 0 // crc32(0, Z_NULL, 0)
  21335. :
  21336. 1; // adler32(0, Z_NULL, 0)
  21337. s.last_flush = Z_NO_FLUSH;
  21338. trees._tr_init(s);
  21339. return Z_OK;
  21340. }
  21341. function deflateReset(strm) {
  21342. var ret = deflateResetKeep(strm);
  21343. if (ret === Z_OK) {
  21344. lm_init(strm.state);
  21345. }
  21346. return ret;
  21347. }
  21348. function deflateSetHeader(strm, head) {
  21349. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21350. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21351. strm.state.gzhead = head;
  21352. return Z_OK;
  21353. }
  21354. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21355. if (!strm) { // === Z_NULL
  21356. return Z_STREAM_ERROR;
  21357. }
  21358. var wrap = 1;
  21359. if (level === Z_DEFAULT_COMPRESSION) {
  21360. level = 6;
  21361. }
  21362. if (windowBits < 0) { /* suppress zlib wrapper */
  21363. wrap = 0;
  21364. windowBits = -windowBits;
  21365. }
  21366. else if (windowBits > 15) {
  21367. wrap = 2; /* write gzip wrapper instead */
  21368. windowBits -= 16;
  21369. }
  21370. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21371. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21372. strategy < 0 || strategy > Z_FIXED) {
  21373. return err(strm, Z_STREAM_ERROR);
  21374. }
  21375. if (windowBits === 8) {
  21376. windowBits = 9;
  21377. }
  21378. /* until 256-byte window bug fixed */
  21379. var s = new DeflateState();
  21380. strm.state = s;
  21381. s.strm = strm;
  21382. s.wrap = wrap;
  21383. s.gzhead = null;
  21384. s.w_bits = windowBits;
  21385. s.w_size = 1 << s.w_bits;
  21386. s.w_mask = s.w_size - 1;
  21387. s.hash_bits = memLevel + 7;
  21388. s.hash_size = 1 << s.hash_bits;
  21389. s.hash_mask = s.hash_size - 1;
  21390. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21391. s.window = new utils.Buf8(s.w_size * 2);
  21392. s.head = new utils.Buf16(s.hash_size);
  21393. s.prev = new utils.Buf16(s.w_size);
  21394. // Don't need mem init magic for JS.
  21395. //s.high_water = 0; /* nothing written to s->window yet */
  21396. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21397. s.pending_buf_size = s.lit_bufsize * 4;
  21398. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21399. s.d_buf = s.lit_bufsize >> 1;
  21400. s.l_buf = (1 + 2) * s.lit_bufsize;
  21401. s.level = level;
  21402. s.strategy = strategy;
  21403. s.method = method;
  21404. return deflateReset(strm);
  21405. }
  21406. function deflateInit(strm, level) {
  21407. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21408. }
  21409. function deflate(strm, flush) {
  21410. var old_flush, s;
  21411. var beg, val; // for gzip header write only
  21412. if (!strm || !strm.state ||
  21413. flush > Z_BLOCK || flush < 0) {
  21414. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21415. }
  21416. s = strm.state;
  21417. if (!strm.output ||
  21418. (!strm.input && strm.avail_in !== 0) ||
  21419. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21420. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21421. }
  21422. s.strm = strm; /* just in case */
  21423. old_flush = s.last_flush;
  21424. s.last_flush = flush;
  21425. /* Write the header */
  21426. if (s.status === INIT_STATE) {
  21427. if (s.wrap === 2) { // GZIP header
  21428. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21429. put_byte(s, 31);
  21430. put_byte(s, 139);
  21431. put_byte(s, 8);
  21432. if (!s.gzhead) { // s->gzhead == Z_NULL
  21433. put_byte(s, 0);
  21434. put_byte(s, 0);
  21435. put_byte(s, 0);
  21436. put_byte(s, 0);
  21437. put_byte(s, 0);
  21438. put_byte(s, s.level === 9 ? 2 :
  21439. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21440. 4 : 0));
  21441. put_byte(s, OS_CODE);
  21442. s.status = BUSY_STATE;
  21443. }
  21444. else {
  21445. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21446. (s.gzhead.hcrc ? 2 : 0) +
  21447. (!s.gzhead.extra ? 0 : 4) +
  21448. (!s.gzhead.name ? 0 : 8) +
  21449. (!s.gzhead.comment ? 0 : 16)
  21450. );
  21451. put_byte(s, s.gzhead.time & 0xff);
  21452. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21453. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21454. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21455. put_byte(s, s.level === 9 ? 2 :
  21456. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21457. 4 : 0));
  21458. put_byte(s, s.gzhead.os & 0xff);
  21459. if (s.gzhead.extra && s.gzhead.extra.length) {
  21460. put_byte(s, s.gzhead.extra.length & 0xff);
  21461. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21462. }
  21463. if (s.gzhead.hcrc) {
  21464. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21465. }
  21466. s.gzindex = 0;
  21467. s.status = EXTRA_STATE;
  21468. }
  21469. }
  21470. else // DEFLATE header
  21471. {
  21472. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21473. var level_flags = -1;
  21474. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21475. level_flags = 0;
  21476. } else if (s.level < 6) {
  21477. level_flags = 1;
  21478. } else if (s.level === 6) {
  21479. level_flags = 2;
  21480. } else {
  21481. level_flags = 3;
  21482. }
  21483. header |= (level_flags << 6);
  21484. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21485. header += 31 - (header % 31);
  21486. s.status = BUSY_STATE;
  21487. putShortMSB(s, header);
  21488. /* Save the adler32 of the preset dictionary: */
  21489. if (s.strstart !== 0) {
  21490. putShortMSB(s, strm.adler >>> 16);
  21491. putShortMSB(s, strm.adler & 0xffff);
  21492. }
  21493. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21494. }
  21495. }
  21496. //#ifdef GZIP
  21497. if (s.status === EXTRA_STATE) {
  21498. if (s.gzhead.extra/* != Z_NULL*/) {
  21499. beg = s.pending; /* start of bytes to update crc */
  21500. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21501. if (s.pending === s.pending_buf_size) {
  21502. if (s.gzhead.hcrc && s.pending > beg) {
  21503. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21504. }
  21505. flush_pending(strm);
  21506. beg = s.pending;
  21507. if (s.pending === s.pending_buf_size) {
  21508. break;
  21509. }
  21510. }
  21511. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21512. s.gzindex++;
  21513. }
  21514. if (s.gzhead.hcrc && s.pending > beg) {
  21515. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21516. }
  21517. if (s.gzindex === s.gzhead.extra.length) {
  21518. s.gzindex = 0;
  21519. s.status = NAME_STATE;
  21520. }
  21521. }
  21522. else {
  21523. s.status = NAME_STATE;
  21524. }
  21525. }
  21526. if (s.status === NAME_STATE) {
  21527. if (s.gzhead.name/* != Z_NULL*/) {
  21528. beg = s.pending; /* start of bytes to update crc */
  21529. //int val;
  21530. do {
  21531. if (s.pending === s.pending_buf_size) {
  21532. if (s.gzhead.hcrc && s.pending > beg) {
  21533. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21534. }
  21535. flush_pending(strm);
  21536. beg = s.pending;
  21537. if (s.pending === s.pending_buf_size) {
  21538. val = 1;
  21539. break;
  21540. }
  21541. }
  21542. // JS specific: little magic to add zero terminator to end of string
  21543. if (s.gzindex < s.gzhead.name.length) {
  21544. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21545. } else {
  21546. val = 0;
  21547. }
  21548. put_byte(s, val);
  21549. } while (val !== 0);
  21550. if (s.gzhead.hcrc && s.pending > beg) {
  21551. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21552. }
  21553. if (val === 0) {
  21554. s.gzindex = 0;
  21555. s.status = COMMENT_STATE;
  21556. }
  21557. }
  21558. else {
  21559. s.status = COMMENT_STATE;
  21560. }
  21561. }
  21562. if (s.status === COMMENT_STATE) {
  21563. if (s.gzhead.comment/* != Z_NULL*/) {
  21564. beg = s.pending; /* start of bytes to update crc */
  21565. //int val;
  21566. do {
  21567. if (s.pending === s.pending_buf_size) {
  21568. if (s.gzhead.hcrc && s.pending > beg) {
  21569. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21570. }
  21571. flush_pending(strm);
  21572. beg = s.pending;
  21573. if (s.pending === s.pending_buf_size) {
  21574. val = 1;
  21575. break;
  21576. }
  21577. }
  21578. // JS specific: little magic to add zero terminator to end of string
  21579. if (s.gzindex < s.gzhead.comment.length) {
  21580. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21581. } else {
  21582. val = 0;
  21583. }
  21584. put_byte(s, val);
  21585. } while (val !== 0);
  21586. if (s.gzhead.hcrc && s.pending > beg) {
  21587. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21588. }
  21589. if (val === 0) {
  21590. s.status = HCRC_STATE;
  21591. }
  21592. }
  21593. else {
  21594. s.status = HCRC_STATE;
  21595. }
  21596. }
  21597. if (s.status === HCRC_STATE) {
  21598. if (s.gzhead.hcrc) {
  21599. if (s.pending + 2 > s.pending_buf_size) {
  21600. flush_pending(strm);
  21601. }
  21602. if (s.pending + 2 <= s.pending_buf_size) {
  21603. put_byte(s, strm.adler & 0xff);
  21604. put_byte(s, (strm.adler >> 8) & 0xff);
  21605. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21606. s.status = BUSY_STATE;
  21607. }
  21608. }
  21609. else {
  21610. s.status = BUSY_STATE;
  21611. }
  21612. }
  21613. //#endif
  21614. /* Flush as much pending output as possible */
  21615. if (s.pending !== 0) {
  21616. flush_pending(strm);
  21617. if (strm.avail_out === 0) {
  21618. /* Since avail_out is 0, deflate will be called again with
  21619. * more output space, but possibly with both pending and
  21620. * avail_in equal to zero. There won't be anything to do,
  21621. * but this is not an error situation so make sure we
  21622. * return OK instead of BUF_ERROR at next call of deflate:
  21623. */
  21624. s.last_flush = -1;
  21625. return Z_OK;
  21626. }
  21627. /* Make sure there is something to do and avoid duplicate consecutive
  21628. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21629. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21630. */
  21631. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21632. flush !== Z_FINISH) {
  21633. return err(strm, Z_BUF_ERROR);
  21634. }
  21635. /* User must not provide more input after the first FINISH: */
  21636. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21637. return err(strm, Z_BUF_ERROR);
  21638. }
  21639. /* Start a new block or continue the current one.
  21640. */
  21641. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21642. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21643. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21644. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21645. configuration_table[s.level].func(s, flush));
  21646. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21647. s.status = FINISH_STATE;
  21648. }
  21649. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21650. if (strm.avail_out === 0) {
  21651. s.last_flush = -1;
  21652. /* avoid BUF_ERROR next call, see above */
  21653. }
  21654. return Z_OK;
  21655. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21656. * of deflate should use the same flush parameter to make sure
  21657. * that the flush is complete. So we don't have to output an
  21658. * empty block here, this will be done at next call. This also
  21659. * ensures that for a very small output buffer, we emit at most
  21660. * one empty block.
  21661. */
  21662. }
  21663. if (bstate === BS_BLOCK_DONE) {
  21664. if (flush === Z_PARTIAL_FLUSH) {
  21665. trees._tr_align(s);
  21666. }
  21667. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21668. trees._tr_stored_block(s, 0, 0, false);
  21669. /* For a full flush, this empty block will be recognized
  21670. * as a special marker by inflate_sync().
  21671. */
  21672. if (flush === Z_FULL_FLUSH) {
  21673. /*** CLEAR_HASH(s); ***/ /* forget history */
  21674. zero(s.head); // Fill with NIL (= 0);
  21675. if (s.lookahead === 0) {
  21676. s.strstart = 0;
  21677. s.block_start = 0;
  21678. s.insert = 0;
  21679. }
  21680. }
  21681. }
  21682. flush_pending(strm);
  21683. if (strm.avail_out === 0) {
  21684. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21685. return Z_OK;
  21686. }
  21687. }
  21688. }
  21689. //Assert(strm->avail_out > 0, "bug2");
  21690. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21691. if (flush !== Z_FINISH) { return Z_OK; }
  21692. if (s.wrap <= 0) { return Z_STREAM_END; }
  21693. /* Write the trailer */
  21694. if (s.wrap === 2) {
  21695. put_byte(s, strm.adler & 0xff);
  21696. put_byte(s, (strm.adler >> 8) & 0xff);
  21697. put_byte(s, (strm.adler >> 16) & 0xff);
  21698. put_byte(s, (strm.adler >> 24) & 0xff);
  21699. put_byte(s, strm.total_in & 0xff);
  21700. put_byte(s, (strm.total_in >> 8) & 0xff);
  21701. put_byte(s, (strm.total_in >> 16) & 0xff);
  21702. put_byte(s, (strm.total_in >> 24) & 0xff);
  21703. }
  21704. else
  21705. {
  21706. putShortMSB(s, strm.adler >>> 16);
  21707. putShortMSB(s, strm.adler & 0xffff);
  21708. }
  21709. flush_pending(strm);
  21710. /* If avail_out is zero, the application will call deflate again
  21711. * to flush the rest.
  21712. */
  21713. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21714. /* write the trailer only once! */
  21715. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21716. }
  21717. function deflateEnd(strm) {
  21718. var status;
  21719. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21720. return Z_STREAM_ERROR;
  21721. }
  21722. status = strm.state.status;
  21723. if (status !== INIT_STATE &&
  21724. status !== EXTRA_STATE &&
  21725. status !== NAME_STATE &&
  21726. status !== COMMENT_STATE &&
  21727. status !== HCRC_STATE &&
  21728. status !== BUSY_STATE &&
  21729. status !== FINISH_STATE
  21730. ) {
  21731. return err(strm, Z_STREAM_ERROR);
  21732. }
  21733. strm.state = null;
  21734. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21735. }
  21736. /* =========================================================================
  21737. * Copy the source state to the destination state
  21738. */
  21739. //function deflateCopy(dest, source) {
  21740. //
  21741. //}
  21742. exports.deflateInit = deflateInit;
  21743. exports.deflateInit2 = deflateInit2;
  21744. exports.deflateReset = deflateReset;
  21745. exports.deflateResetKeep = deflateResetKeep;
  21746. exports.deflateSetHeader = deflateSetHeader;
  21747. exports.deflate = deflate;
  21748. exports.deflateEnd = deflateEnd;
  21749. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21750. /* Not implemented
  21751. exports.deflateBound = deflateBound;
  21752. exports.deflateCopy = deflateCopy;
  21753. exports.deflateSetDictionary = deflateSetDictionary;
  21754. exports.deflateParams = deflateParams;
  21755. exports.deflatePending = deflatePending;
  21756. exports.deflatePrime = deflatePrime;
  21757. exports.deflateTune = deflateTune;
  21758. */
  21759. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./messages":82,"./trees":83}],78:[function(require,module,exports){
  21760. 'use strict';
  21761. function GZheader() {
  21762. /* true if compressed data believed to be text */
  21763. this.text = 0;
  21764. /* modification time */
  21765. this.time = 0;
  21766. /* extra flags (not used when writing a gzip file) */
  21767. this.xflags = 0;
  21768. /* operating system */
  21769. this.os = 0;
  21770. /* pointer to extra field or Z_NULL if none */
  21771. this.extra = null;
  21772. /* extra field length (valid if extra != Z_NULL) */
  21773. this.extra_len = 0; // Actually, we don't need it in JS,
  21774. // but leave for few code modifications
  21775. //
  21776. // Setup limits is not necessary because in js we should not preallocate memory
  21777. // for inflate use constant limit in 65536 bytes
  21778. //
  21779. /* space at extra (only when reading header) */
  21780. // this.extra_max = 0;
  21781. /* pointer to zero-terminated file name or Z_NULL */
  21782. this.name = '';
  21783. /* space at name (only when reading header) */
  21784. // this.name_max = 0;
  21785. /* pointer to zero-terminated comment or Z_NULL */
  21786. this.comment = '';
  21787. /* space at comment (only when reading header) */
  21788. // this.comm_max = 0;
  21789. /* true if there was or will be a header crc */
  21790. this.hcrc = 0;
  21791. /* true when done reading gzip header (not used when writing a gzip file) */
  21792. this.done = false;
  21793. }
  21794. module.exports = GZheader;
  21795. },{}],79:[function(require,module,exports){
  21796. 'use strict';
  21797. // See state defs from inflate.js
  21798. var BAD = 30; /* got a data error -- remain here until reset */
  21799. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21800. /*
  21801. Decode literal, length, and distance codes and write out the resulting
  21802. literal and match bytes until either not enough input or output is
  21803. available, an end-of-block is encountered, or a data error is encountered.
  21804. When large enough input and output buffers are supplied to inflate(), for
  21805. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21806. inflate execution time is spent in this routine.
  21807. Entry assumptions:
  21808. state.mode === LEN
  21809. strm.avail_in >= 6
  21810. strm.avail_out >= 258
  21811. start >= strm.avail_out
  21812. state.bits < 8
  21813. On return, state.mode is one of:
  21814. LEN -- ran out of enough output space or enough available input
  21815. TYPE -- reached end of block code, inflate() to interpret next block
  21816. BAD -- error in block data
  21817. Notes:
  21818. - The maximum input bits used by a length/distance pair is 15 bits for the
  21819. length code, 5 bits for the length extra, 15 bits for the distance code,
  21820. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21821. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21822. checking for available input while decoding.
  21823. - The maximum bytes that a single length/distance pair can output is 258
  21824. bytes, which is the maximum length that can be coded. inflate_fast()
  21825. requires strm.avail_out >= 258 for each loop to avoid checking for
  21826. output space.
  21827. */
  21828. module.exports = function inflate_fast(strm, start) {
  21829. var state;
  21830. var _in; /* local strm.input */
  21831. var last; /* have enough input while in < last */
  21832. var _out; /* local strm.output */
  21833. var beg; /* inflate()'s initial strm.output */
  21834. var end; /* while out < end, enough space available */
  21835. //#ifdef INFLATE_STRICT
  21836. var dmax; /* maximum distance from zlib header */
  21837. //#endif
  21838. var wsize; /* window size or zero if not using window */
  21839. var whave; /* valid bytes in the window */
  21840. var wnext; /* window write index */
  21841. var window; /* allocated sliding window, if wsize != 0 */
  21842. var hold; /* local strm.hold */
  21843. var bits; /* local strm.bits */
  21844. var lcode; /* local strm.lencode */
  21845. var dcode; /* local strm.distcode */
  21846. var lmask; /* mask for first level of length codes */
  21847. var dmask; /* mask for first level of distance codes */
  21848. var here; /* retrieved table entry */
  21849. var op; /* code bits, operation, extra bits, or */
  21850. /* window position, window bytes to copy */
  21851. var len; /* match length, unused bytes */
  21852. var dist; /* match distance */
  21853. var from; /* where to copy match from */
  21854. var from_source;
  21855. var input, output; // JS specific, because we have no pointers
  21856. /* copy state to local variables */
  21857. state = strm.state;
  21858. //here = state.here;
  21859. _in = strm.next_in;
  21860. input = strm.input;
  21861. last = _in + (strm.avail_in - 5);
  21862. _out = strm.next_out;
  21863. output = strm.output;
  21864. beg = _out - (start - strm.avail_out);
  21865. end = _out + (strm.avail_out - 257);
  21866. //#ifdef INFLATE_STRICT
  21867. dmax = state.dmax;
  21868. //#endif
  21869. wsize = state.wsize;
  21870. whave = state.whave;
  21871. wnext = state.wnext;
  21872. window = state.window;
  21873. hold = state.hold;
  21874. bits = state.bits;
  21875. lcode = state.lencode;
  21876. dcode = state.distcode;
  21877. lmask = (1 << state.lenbits) - 1;
  21878. dmask = (1 << state.distbits) - 1;
  21879. /* decode literals and length/distances until end-of-block or not enough
  21880. input data or output space */
  21881. top:
  21882. do {
  21883. if (bits < 15) {
  21884. hold += input[_in++] << bits;
  21885. bits += 8;
  21886. hold += input[_in++] << bits;
  21887. bits += 8;
  21888. }
  21889. here = lcode[hold & lmask];
  21890. dolen:
  21891. for (;;) { // Goto emulation
  21892. op = here >>> 24/*here.bits*/;
  21893. hold >>>= op;
  21894. bits -= op;
  21895. op = (here >>> 16) & 0xff/*here.op*/;
  21896. if (op === 0) { /* literal */
  21897. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21898. // "inflate: literal '%c'\n" :
  21899. // "inflate: literal 0x%02x\n", here.val));
  21900. output[_out++] = here & 0xffff/*here.val*/;
  21901. }
  21902. else if (op & 16) { /* length base */
  21903. len = here & 0xffff/*here.val*/;
  21904. op &= 15; /* number of extra bits */
  21905. if (op) {
  21906. if (bits < op) {
  21907. hold += input[_in++] << bits;
  21908. bits += 8;
  21909. }
  21910. len += hold & ((1 << op) - 1);
  21911. hold >>>= op;
  21912. bits -= op;
  21913. }
  21914. //Tracevv((stderr, "inflate: length %u\n", len));
  21915. if (bits < 15) {
  21916. hold += input[_in++] << bits;
  21917. bits += 8;
  21918. hold += input[_in++] << bits;
  21919. bits += 8;
  21920. }
  21921. here = dcode[hold & dmask];
  21922. dodist:
  21923. for (;;) { // goto emulation
  21924. op = here >>> 24/*here.bits*/;
  21925. hold >>>= op;
  21926. bits -= op;
  21927. op = (here >>> 16) & 0xff/*here.op*/;
  21928. if (op & 16) { /* distance base */
  21929. dist = here & 0xffff/*here.val*/;
  21930. op &= 15; /* number of extra bits */
  21931. if (bits < op) {
  21932. hold += input[_in++] << bits;
  21933. bits += 8;
  21934. if (bits < op) {
  21935. hold += input[_in++] << bits;
  21936. bits += 8;
  21937. }
  21938. }
  21939. dist += hold & ((1 << op) - 1);
  21940. //#ifdef INFLATE_STRICT
  21941. if (dist > dmax) {
  21942. strm.msg = 'invalid distance too far back';
  21943. state.mode = BAD;
  21944. break top;
  21945. }
  21946. //#endif
  21947. hold >>>= op;
  21948. bits -= op;
  21949. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21950. op = _out - beg; /* max distance in output */
  21951. if (dist > op) { /* see if copy from window */
  21952. op = dist - op; /* distance back in window */
  21953. if (op > whave) {
  21954. if (state.sane) {
  21955. strm.msg = 'invalid distance too far back';
  21956. state.mode = BAD;
  21957. break top;
  21958. }
  21959. // (!) This block is disabled in zlib defailts,
  21960. // don't enable it for binary compatibility
  21961. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21962. // if (len <= op - whave) {
  21963. // do {
  21964. // output[_out++] = 0;
  21965. // } while (--len);
  21966. // continue top;
  21967. // }
  21968. // len -= op - whave;
  21969. // do {
  21970. // output[_out++] = 0;
  21971. // } while (--op > whave);
  21972. // if (op === 0) {
  21973. // from = _out - dist;
  21974. // do {
  21975. // output[_out++] = output[from++];
  21976. // } while (--len);
  21977. // continue top;
  21978. // }
  21979. //#endif
  21980. }
  21981. from = 0; // window index
  21982. from_source = window;
  21983. if (wnext === 0) { /* very common case */
  21984. from += wsize - op;
  21985. if (op < len) { /* some from window */
  21986. len -= op;
  21987. do {
  21988. output[_out++] = window[from++];
  21989. } while (--op);
  21990. from = _out - dist; /* rest from output */
  21991. from_source = output;
  21992. }
  21993. }
  21994. else if (wnext < op) { /* wrap around window */
  21995. from += wsize + wnext - op;
  21996. op -= wnext;
  21997. if (op < len) { /* some from end of window */
  21998. len -= op;
  21999. do {
  22000. output[_out++] = window[from++];
  22001. } while (--op);
  22002. from = 0;
  22003. if (wnext < len) { /* some from start of window */
  22004. op = wnext;
  22005. len -= op;
  22006. do {
  22007. output[_out++] = window[from++];
  22008. } while (--op);
  22009. from = _out - dist; /* rest from output */
  22010. from_source = output;
  22011. }
  22012. }
  22013. }
  22014. else { /* contiguous in window */
  22015. from += wnext - op;
  22016. if (op < len) { /* some from window */
  22017. len -= op;
  22018. do {
  22019. output[_out++] = window[from++];
  22020. } while (--op);
  22021. from = _out - dist; /* rest from output */
  22022. from_source = output;
  22023. }
  22024. }
  22025. while (len > 2) {
  22026. output[_out++] = from_source[from++];
  22027. output[_out++] = from_source[from++];
  22028. output[_out++] = from_source[from++];
  22029. len -= 3;
  22030. }
  22031. if (len) {
  22032. output[_out++] = from_source[from++];
  22033. if (len > 1) {
  22034. output[_out++] = from_source[from++];
  22035. }
  22036. }
  22037. }
  22038. else {
  22039. from = _out - dist; /* copy direct from output */
  22040. do { /* minimum length is three */
  22041. output[_out++] = output[from++];
  22042. output[_out++] = output[from++];
  22043. output[_out++] = output[from++];
  22044. len -= 3;
  22045. } while (len > 2);
  22046. if (len) {
  22047. output[_out++] = output[from++];
  22048. if (len > 1) {
  22049. output[_out++] = output[from++];
  22050. }
  22051. }
  22052. }
  22053. }
  22054. else if ((op & 64) === 0) { /* 2nd level distance code */
  22055. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22056. continue dodist;
  22057. }
  22058. else {
  22059. strm.msg = 'invalid distance code';
  22060. state.mode = BAD;
  22061. break top;
  22062. }
  22063. break; // need to emulate goto via "continue"
  22064. }
  22065. }
  22066. else if ((op & 64) === 0) { /* 2nd level length code */
  22067. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22068. continue dolen;
  22069. }
  22070. else if (op & 32) { /* end-of-block */
  22071. //Tracevv((stderr, "inflate: end of block\n"));
  22072. state.mode = TYPE;
  22073. break top;
  22074. }
  22075. else {
  22076. strm.msg = 'invalid literal/length code';
  22077. state.mode = BAD;
  22078. break top;
  22079. }
  22080. break; // need to emulate goto via "continue"
  22081. }
  22082. } while (_in < last && _out < end);
  22083. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22084. len = bits >> 3;
  22085. _in -= len;
  22086. bits -= len << 3;
  22087. hold &= (1 << bits) - 1;
  22088. /* update state and return */
  22089. strm.next_in = _in;
  22090. strm.next_out = _out;
  22091. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22092. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22093. state.hold = hold;
  22094. state.bits = bits;
  22095. return;
  22096. };
  22097. },{}],80:[function(require,module,exports){
  22098. 'use strict';
  22099. var utils = require('../utils/common');
  22100. var adler32 = require('./adler32');
  22101. var crc32 = require('./crc32');
  22102. var inflate_fast = require('./inffast');
  22103. var inflate_table = require('./inftrees');
  22104. var CODES = 0;
  22105. var LENS = 1;
  22106. var DISTS = 2;
  22107. /* Public constants ==========================================================*/
  22108. /* ===========================================================================*/
  22109. /* Allowed flush values; see deflate() and inflate() below for details */
  22110. //var Z_NO_FLUSH = 0;
  22111. //var Z_PARTIAL_FLUSH = 1;
  22112. //var Z_SYNC_FLUSH = 2;
  22113. //var Z_FULL_FLUSH = 3;
  22114. var Z_FINISH = 4;
  22115. var Z_BLOCK = 5;
  22116. var Z_TREES = 6;
  22117. /* Return codes for the compression/decompression functions. Negative values
  22118. * are errors, positive values are used for special but normal events.
  22119. */
  22120. var Z_OK = 0;
  22121. var Z_STREAM_END = 1;
  22122. var Z_NEED_DICT = 2;
  22123. //var Z_ERRNO = -1;
  22124. var Z_STREAM_ERROR = -2;
  22125. var Z_DATA_ERROR = -3;
  22126. var Z_MEM_ERROR = -4;
  22127. var Z_BUF_ERROR = -5;
  22128. //var Z_VERSION_ERROR = -6;
  22129. /* The deflate compression method */
  22130. var Z_DEFLATED = 8;
  22131. /* STATES ====================================================================*/
  22132. /* ===========================================================================*/
  22133. var HEAD = 1; /* i: waiting for magic header */
  22134. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22135. var TIME = 3; /* i: waiting for modification time (gzip) */
  22136. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22137. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22138. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22139. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22140. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22141. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22142. var DICTID = 10; /* i: waiting for dictionary check value */
  22143. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22144. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22145. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22146. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22147. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22148. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22149. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22150. var LENLENS = 18; /* i: waiting for code length code lengths */
  22151. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22152. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22153. var LEN = 21; /* i: waiting for length/lit/eob code */
  22154. var LENEXT = 22; /* i: waiting for length extra bits */
  22155. var DIST = 23; /* i: waiting for distance code */
  22156. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22157. var MATCH = 25; /* o: waiting for output space to copy string */
  22158. var LIT = 26; /* o: waiting for output space to write literal */
  22159. var CHECK = 27; /* i: waiting for 32-bit check value */
  22160. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22161. var DONE = 29; /* finished check, done -- remain here until reset */
  22162. var BAD = 30; /* got a data error -- remain here until reset */
  22163. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22164. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22165. /* ===========================================================================*/
  22166. var ENOUGH_LENS = 852;
  22167. var ENOUGH_DISTS = 592;
  22168. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22169. var MAX_WBITS = 15;
  22170. /* 32K LZ77 window */
  22171. var DEF_WBITS = MAX_WBITS;
  22172. function ZSWAP32(q) {
  22173. return (((q >>> 24) & 0xff) +
  22174. ((q >>> 8) & 0xff00) +
  22175. ((q & 0xff00) << 8) +
  22176. ((q & 0xff) << 24));
  22177. }
  22178. function InflateState() {
  22179. this.mode = 0; /* current inflate mode */
  22180. this.last = false; /* true if processing last block */
  22181. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22182. this.havedict = false; /* true if dictionary provided */
  22183. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22184. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22185. this.check = 0; /* protected copy of check value */
  22186. this.total = 0; /* protected copy of output count */
  22187. // TODO: may be {}
  22188. this.head = null; /* where to save gzip header information */
  22189. /* sliding window */
  22190. this.wbits = 0; /* log base 2 of requested window size */
  22191. this.wsize = 0; /* window size or zero if not using window */
  22192. this.whave = 0; /* valid bytes in the window */
  22193. this.wnext = 0; /* window write index */
  22194. this.window = null; /* allocated sliding window, if needed */
  22195. /* bit accumulator */
  22196. this.hold = 0; /* input bit accumulator */
  22197. this.bits = 0; /* number of bits in "in" */
  22198. /* for string and stored block copying */
  22199. this.length = 0; /* literal or length of data to copy */
  22200. this.offset = 0; /* distance back to copy string from */
  22201. /* for table and code decoding */
  22202. this.extra = 0; /* extra bits needed */
  22203. /* fixed and dynamic code tables */
  22204. this.lencode = null; /* starting table for length/literal codes */
  22205. this.distcode = null; /* starting table for distance codes */
  22206. this.lenbits = 0; /* index bits for lencode */
  22207. this.distbits = 0; /* index bits for distcode */
  22208. /* dynamic table building */
  22209. this.ncode = 0; /* number of code length code lengths */
  22210. this.nlen = 0; /* number of length code lengths */
  22211. this.ndist = 0; /* number of distance code lengths */
  22212. this.have = 0; /* number of code lengths in lens[] */
  22213. this.next = null; /* next available space in codes[] */
  22214. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22215. this.work = new utils.Buf16(288); /* work area for code table building */
  22216. /*
  22217. because we don't have pointers in js, we use lencode and distcode directly
  22218. as buffers so we don't need codes
  22219. */
  22220. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22221. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22222. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22223. this.sane = 0; /* if false, allow invalid distance too far */
  22224. this.back = 0; /* bits back of last unprocessed length/lit */
  22225. this.was = 0; /* initial length of match */
  22226. }
  22227. function inflateResetKeep(strm) {
  22228. var state;
  22229. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22230. state = strm.state;
  22231. strm.total_in = strm.total_out = state.total = 0;
  22232. strm.msg = ''; /*Z_NULL*/
  22233. if (state.wrap) { /* to support ill-conceived Java test suite */
  22234. strm.adler = state.wrap & 1;
  22235. }
  22236. state.mode = HEAD;
  22237. state.last = 0;
  22238. state.havedict = 0;
  22239. state.dmax = 32768;
  22240. state.head = null/*Z_NULL*/;
  22241. state.hold = 0;
  22242. state.bits = 0;
  22243. //state.lencode = state.distcode = state.next = state.codes;
  22244. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22245. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22246. state.sane = 1;
  22247. state.back = -1;
  22248. //Tracev((stderr, "inflate: reset\n"));
  22249. return Z_OK;
  22250. }
  22251. function inflateReset(strm) {
  22252. var state;
  22253. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22254. state = strm.state;
  22255. state.wsize = 0;
  22256. state.whave = 0;
  22257. state.wnext = 0;
  22258. return inflateResetKeep(strm);
  22259. }
  22260. function inflateReset2(strm, windowBits) {
  22261. var wrap;
  22262. var state;
  22263. /* get the state */
  22264. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22265. state = strm.state;
  22266. /* extract wrap request from windowBits parameter */
  22267. if (windowBits < 0) {
  22268. wrap = 0;
  22269. windowBits = -windowBits;
  22270. }
  22271. else {
  22272. wrap = (windowBits >> 4) + 1;
  22273. if (windowBits < 48) {
  22274. windowBits &= 15;
  22275. }
  22276. }
  22277. /* set number of window bits, free window if different */
  22278. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22279. return Z_STREAM_ERROR;
  22280. }
  22281. if (state.window !== null && state.wbits !== windowBits) {
  22282. state.window = null;
  22283. }
  22284. /* update state and reset the rest of it */
  22285. state.wrap = wrap;
  22286. state.wbits = windowBits;
  22287. return inflateReset(strm);
  22288. }
  22289. function inflateInit2(strm, windowBits) {
  22290. var ret;
  22291. var state;
  22292. if (!strm) { return Z_STREAM_ERROR; }
  22293. //strm.msg = Z_NULL; /* in case we return an error */
  22294. state = new InflateState();
  22295. //if (state === Z_NULL) return Z_MEM_ERROR;
  22296. //Tracev((stderr, "inflate: allocated\n"));
  22297. strm.state = state;
  22298. state.window = null/*Z_NULL*/;
  22299. ret = inflateReset2(strm, windowBits);
  22300. if (ret !== Z_OK) {
  22301. strm.state = null/*Z_NULL*/;
  22302. }
  22303. return ret;
  22304. }
  22305. function inflateInit(strm) {
  22306. return inflateInit2(strm, DEF_WBITS);
  22307. }
  22308. /*
  22309. Return state with length and distance decoding tables and index sizes set to
  22310. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22311. If BUILDFIXED is defined, then instead this routine builds the tables the
  22312. first time it's called, and returns those tables the first time and
  22313. thereafter. This reduces the size of the code by about 2K bytes, in
  22314. exchange for a little execution time. However, BUILDFIXED should not be
  22315. used for threaded applications, since the rewriting of the tables and virgin
  22316. may not be thread-safe.
  22317. */
  22318. var virgin = true;
  22319. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22320. function fixedtables(state) {
  22321. /* build fixed huffman tables if first call (may not be thread safe) */
  22322. if (virgin) {
  22323. var sym;
  22324. lenfix = new utils.Buf32(512);
  22325. distfix = new utils.Buf32(32);
  22326. /* literal/length table */
  22327. sym = 0;
  22328. while (sym < 144) { state.lens[sym++] = 8; }
  22329. while (sym < 256) { state.lens[sym++] = 9; }
  22330. while (sym < 280) { state.lens[sym++] = 7; }
  22331. while (sym < 288) { state.lens[sym++] = 8; }
  22332. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22333. /* distance table */
  22334. sym = 0;
  22335. while (sym < 32) { state.lens[sym++] = 5; }
  22336. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22337. /* do this just once */
  22338. virgin = false;
  22339. }
  22340. state.lencode = lenfix;
  22341. state.lenbits = 9;
  22342. state.distcode = distfix;
  22343. state.distbits = 5;
  22344. }
  22345. /*
  22346. Update the window with the last wsize (normally 32K) bytes written before
  22347. returning. If window does not exist yet, create it. This is only called
  22348. when a window is already in use, or when output has been written during this
  22349. inflate call, but the end of the deflate stream has not been reached yet.
  22350. It is also called to create a window for dictionary data when a dictionary
  22351. is loaded.
  22352. Providing output buffers larger than 32K to inflate() should provide a speed
  22353. advantage, since only the last 32K of output is copied to the sliding window
  22354. upon return from inflate(), and since all distances after the first 32K of
  22355. output will fall in the output data, making match copies simpler and faster.
  22356. The advantage may be dependent on the size of the processor's data caches.
  22357. */
  22358. function updatewindow(strm, src, end, copy) {
  22359. var dist;
  22360. var state = strm.state;
  22361. /* if it hasn't been done already, allocate space for the window */
  22362. if (state.window === null) {
  22363. state.wsize = 1 << state.wbits;
  22364. state.wnext = 0;
  22365. state.whave = 0;
  22366. state.window = new utils.Buf8(state.wsize);
  22367. }
  22368. /* copy state->wsize or less output bytes into the circular window */
  22369. if (copy >= state.wsize) {
  22370. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22371. state.wnext = 0;
  22372. state.whave = state.wsize;
  22373. }
  22374. else {
  22375. dist = state.wsize - state.wnext;
  22376. if (dist > copy) {
  22377. dist = copy;
  22378. }
  22379. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22380. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22381. copy -= dist;
  22382. if (copy) {
  22383. //zmemcpy(state->window, end - copy, copy);
  22384. utils.arraySet(state.window,src, end - copy, copy, 0);
  22385. state.wnext = copy;
  22386. state.whave = state.wsize;
  22387. }
  22388. else {
  22389. state.wnext += dist;
  22390. if (state.wnext === state.wsize) { state.wnext = 0; }
  22391. if (state.whave < state.wsize) { state.whave += dist; }
  22392. }
  22393. }
  22394. return 0;
  22395. }
  22396. function inflate(strm, flush) {
  22397. var state;
  22398. var input, output; // input/output buffers
  22399. var next; /* next input INDEX */
  22400. var put; /* next output INDEX */
  22401. var have, left; /* available input and output */
  22402. var hold; /* bit buffer */
  22403. var bits; /* bits in bit buffer */
  22404. var _in, _out; /* save starting available input and output */
  22405. var copy; /* number of stored or match bytes to copy */
  22406. var from; /* where to copy match bytes from */
  22407. var from_source;
  22408. var here = 0; /* current decoding table entry */
  22409. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22410. //var last; /* parent table entry */
  22411. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22412. var len; /* length to copy for repeats, bits to drop */
  22413. var ret; /* return code */
  22414. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22415. var opts;
  22416. var n; // temporary var for NEED_BITS
  22417. var order = /* permutation of code lengths */
  22418. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22419. if (!strm || !strm.state || !strm.output ||
  22420. (!strm.input && strm.avail_in !== 0)) {
  22421. return Z_STREAM_ERROR;
  22422. }
  22423. state = strm.state;
  22424. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22425. //--- LOAD() ---
  22426. put = strm.next_out;
  22427. output = strm.output;
  22428. left = strm.avail_out;
  22429. next = strm.next_in;
  22430. input = strm.input;
  22431. have = strm.avail_in;
  22432. hold = state.hold;
  22433. bits = state.bits;
  22434. //---
  22435. _in = have;
  22436. _out = left;
  22437. ret = Z_OK;
  22438. inf_leave: // goto emulation
  22439. for (;;) {
  22440. switch (state.mode) {
  22441. case HEAD:
  22442. if (state.wrap === 0) {
  22443. state.mode = TYPEDO;
  22444. break;
  22445. }
  22446. //=== NEEDBITS(16);
  22447. while (bits < 16) {
  22448. if (have === 0) { break inf_leave; }
  22449. have--;
  22450. hold += input[next++] << bits;
  22451. bits += 8;
  22452. }
  22453. //===//
  22454. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22455. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22456. //=== CRC2(state.check, hold);
  22457. hbuf[0] = hold & 0xff;
  22458. hbuf[1] = (hold >>> 8) & 0xff;
  22459. state.check = crc32(state.check, hbuf, 2, 0);
  22460. //===//
  22461. //=== INITBITS();
  22462. hold = 0;
  22463. bits = 0;
  22464. //===//
  22465. state.mode = FLAGS;
  22466. break;
  22467. }
  22468. state.flags = 0; /* expect zlib header */
  22469. if (state.head) {
  22470. state.head.done = false;
  22471. }
  22472. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22473. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22474. strm.msg = 'incorrect header check';
  22475. state.mode = BAD;
  22476. break;
  22477. }
  22478. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22479. strm.msg = 'unknown compression method';
  22480. state.mode = BAD;
  22481. break;
  22482. }
  22483. //--- DROPBITS(4) ---//
  22484. hold >>>= 4;
  22485. bits -= 4;
  22486. //---//
  22487. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22488. if (state.wbits === 0) {
  22489. state.wbits = len;
  22490. }
  22491. else if (len > state.wbits) {
  22492. strm.msg = 'invalid window size';
  22493. state.mode = BAD;
  22494. break;
  22495. }
  22496. state.dmax = 1 << len;
  22497. //Tracev((stderr, "inflate: zlib header ok\n"));
  22498. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22499. state.mode = hold & 0x200 ? DICTID : TYPE;
  22500. //=== INITBITS();
  22501. hold = 0;
  22502. bits = 0;
  22503. //===//
  22504. break;
  22505. case FLAGS:
  22506. //=== NEEDBITS(16); */
  22507. while (bits < 16) {
  22508. if (have === 0) { break inf_leave; }
  22509. have--;
  22510. hold += input[next++] << bits;
  22511. bits += 8;
  22512. }
  22513. //===//
  22514. state.flags = hold;
  22515. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22516. strm.msg = 'unknown compression method';
  22517. state.mode = BAD;
  22518. break;
  22519. }
  22520. if (state.flags & 0xe000) {
  22521. strm.msg = 'unknown header flags set';
  22522. state.mode = BAD;
  22523. break;
  22524. }
  22525. if (state.head) {
  22526. state.head.text = ((hold >> 8) & 1);
  22527. }
  22528. if (state.flags & 0x0200) {
  22529. //=== CRC2(state.check, hold);
  22530. hbuf[0] = hold & 0xff;
  22531. hbuf[1] = (hold >>> 8) & 0xff;
  22532. state.check = crc32(state.check, hbuf, 2, 0);
  22533. //===//
  22534. }
  22535. //=== INITBITS();
  22536. hold = 0;
  22537. bits = 0;
  22538. //===//
  22539. state.mode = TIME;
  22540. /* falls through */
  22541. case TIME:
  22542. //=== NEEDBITS(32); */
  22543. while (bits < 32) {
  22544. if (have === 0) { break inf_leave; }
  22545. have--;
  22546. hold += input[next++] << bits;
  22547. bits += 8;
  22548. }
  22549. //===//
  22550. if (state.head) {
  22551. state.head.time = hold;
  22552. }
  22553. if (state.flags & 0x0200) {
  22554. //=== CRC4(state.check, hold)
  22555. hbuf[0] = hold & 0xff;
  22556. hbuf[1] = (hold >>> 8) & 0xff;
  22557. hbuf[2] = (hold >>> 16) & 0xff;
  22558. hbuf[3] = (hold >>> 24) & 0xff;
  22559. state.check = crc32(state.check, hbuf, 4, 0);
  22560. //===
  22561. }
  22562. //=== INITBITS();
  22563. hold = 0;
  22564. bits = 0;
  22565. //===//
  22566. state.mode = OS;
  22567. /* falls through */
  22568. case OS:
  22569. //=== NEEDBITS(16); */
  22570. while (bits < 16) {
  22571. if (have === 0) { break inf_leave; }
  22572. have--;
  22573. hold += input[next++] << bits;
  22574. bits += 8;
  22575. }
  22576. //===//
  22577. if (state.head) {
  22578. state.head.xflags = (hold & 0xff);
  22579. state.head.os = (hold >> 8);
  22580. }
  22581. if (state.flags & 0x0200) {
  22582. //=== CRC2(state.check, hold);
  22583. hbuf[0] = hold & 0xff;
  22584. hbuf[1] = (hold >>> 8) & 0xff;
  22585. state.check = crc32(state.check, hbuf, 2, 0);
  22586. //===//
  22587. }
  22588. //=== INITBITS();
  22589. hold = 0;
  22590. bits = 0;
  22591. //===//
  22592. state.mode = EXLEN;
  22593. /* falls through */
  22594. case EXLEN:
  22595. if (state.flags & 0x0400) {
  22596. //=== NEEDBITS(16); */
  22597. while (bits < 16) {
  22598. if (have === 0) { break inf_leave; }
  22599. have--;
  22600. hold += input[next++] << bits;
  22601. bits += 8;
  22602. }
  22603. //===//
  22604. state.length = hold;
  22605. if (state.head) {
  22606. state.head.extra_len = hold;
  22607. }
  22608. if (state.flags & 0x0200) {
  22609. //=== CRC2(state.check, hold);
  22610. hbuf[0] = hold & 0xff;
  22611. hbuf[1] = (hold >>> 8) & 0xff;
  22612. state.check = crc32(state.check, hbuf, 2, 0);
  22613. //===//
  22614. }
  22615. //=== INITBITS();
  22616. hold = 0;
  22617. bits = 0;
  22618. //===//
  22619. }
  22620. else if (state.head) {
  22621. state.head.extra = null/*Z_NULL*/;
  22622. }
  22623. state.mode = EXTRA;
  22624. /* falls through */
  22625. case EXTRA:
  22626. if (state.flags & 0x0400) {
  22627. copy = state.length;
  22628. if (copy > have) { copy = have; }
  22629. if (copy) {
  22630. if (state.head) {
  22631. len = state.head.extra_len - state.length;
  22632. if (!state.head.extra) {
  22633. // Use untyped array for more conveniend processing later
  22634. state.head.extra = new Array(state.head.extra_len);
  22635. }
  22636. utils.arraySet(
  22637. state.head.extra,
  22638. input,
  22639. next,
  22640. // extra field is limited to 65536 bytes
  22641. // - no need for additional size check
  22642. copy,
  22643. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22644. len
  22645. );
  22646. //zmemcpy(state.head.extra + len, next,
  22647. // len + copy > state.head.extra_max ?
  22648. // state.head.extra_max - len : copy);
  22649. }
  22650. if (state.flags & 0x0200) {
  22651. state.check = crc32(state.check, input, copy, next);
  22652. }
  22653. have -= copy;
  22654. next += copy;
  22655. state.length -= copy;
  22656. }
  22657. if (state.length) { break inf_leave; }
  22658. }
  22659. state.length = 0;
  22660. state.mode = NAME;
  22661. /* falls through */
  22662. case NAME:
  22663. if (state.flags & 0x0800) {
  22664. if (have === 0) { break inf_leave; }
  22665. copy = 0;
  22666. do {
  22667. // TODO: 2 or 1 bytes?
  22668. len = input[next + copy++];
  22669. /* use constant limit because in js we should not preallocate memory */
  22670. if (state.head && len &&
  22671. (state.length < 65536 /*state.head.name_max*/)) {
  22672. state.head.name += String.fromCharCode(len);
  22673. }
  22674. } while (len && copy < have);
  22675. if (state.flags & 0x0200) {
  22676. state.check = crc32(state.check, input, copy, next);
  22677. }
  22678. have -= copy;
  22679. next += copy;
  22680. if (len) { break inf_leave; }
  22681. }
  22682. else if (state.head) {
  22683. state.head.name = null;
  22684. }
  22685. state.length = 0;
  22686. state.mode = COMMENT;
  22687. /* falls through */
  22688. case COMMENT:
  22689. if (state.flags & 0x1000) {
  22690. if (have === 0) { break inf_leave; }
  22691. copy = 0;
  22692. do {
  22693. len = input[next + copy++];
  22694. /* use constant limit because in js we should not preallocate memory */
  22695. if (state.head && len &&
  22696. (state.length < 65536 /*state.head.comm_max*/)) {
  22697. state.head.comment += String.fromCharCode(len);
  22698. }
  22699. } while (len && copy < have);
  22700. if (state.flags & 0x0200) {
  22701. state.check = crc32(state.check, input, copy, next);
  22702. }
  22703. have -= copy;
  22704. next += copy;
  22705. if (len) { break inf_leave; }
  22706. }
  22707. else if (state.head) {
  22708. state.head.comment = null;
  22709. }
  22710. state.mode = HCRC;
  22711. /* falls through */
  22712. case HCRC:
  22713. if (state.flags & 0x0200) {
  22714. //=== NEEDBITS(16); */
  22715. while (bits < 16) {
  22716. if (have === 0) { break inf_leave; }
  22717. have--;
  22718. hold += input[next++] << bits;
  22719. bits += 8;
  22720. }
  22721. //===//
  22722. if (hold !== (state.check & 0xffff)) {
  22723. strm.msg = 'header crc mismatch';
  22724. state.mode = BAD;
  22725. break;
  22726. }
  22727. //=== INITBITS();
  22728. hold = 0;
  22729. bits = 0;
  22730. //===//
  22731. }
  22732. if (state.head) {
  22733. state.head.hcrc = ((state.flags >> 9) & 1);
  22734. state.head.done = true;
  22735. }
  22736. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22737. state.mode = TYPE;
  22738. break;
  22739. case DICTID:
  22740. //=== NEEDBITS(32); */
  22741. while (bits < 32) {
  22742. if (have === 0) { break inf_leave; }
  22743. have--;
  22744. hold += input[next++] << bits;
  22745. bits += 8;
  22746. }
  22747. //===//
  22748. strm.adler = state.check = ZSWAP32(hold);
  22749. //=== INITBITS();
  22750. hold = 0;
  22751. bits = 0;
  22752. //===//
  22753. state.mode = DICT;
  22754. /* falls through */
  22755. case DICT:
  22756. if (state.havedict === 0) {
  22757. //--- RESTORE() ---
  22758. strm.next_out = put;
  22759. strm.avail_out = left;
  22760. strm.next_in = next;
  22761. strm.avail_in = have;
  22762. state.hold = hold;
  22763. state.bits = bits;
  22764. //---
  22765. return Z_NEED_DICT;
  22766. }
  22767. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22768. state.mode = TYPE;
  22769. /* falls through */
  22770. case TYPE:
  22771. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22772. /* falls through */
  22773. case TYPEDO:
  22774. if (state.last) {
  22775. //--- BYTEBITS() ---//
  22776. hold >>>= bits & 7;
  22777. bits -= bits & 7;
  22778. //---//
  22779. state.mode = CHECK;
  22780. break;
  22781. }
  22782. //=== NEEDBITS(3); */
  22783. while (bits < 3) {
  22784. if (have === 0) { break inf_leave; }
  22785. have--;
  22786. hold += input[next++] << bits;
  22787. bits += 8;
  22788. }
  22789. //===//
  22790. state.last = (hold & 0x01)/*BITS(1)*/;
  22791. //--- DROPBITS(1) ---//
  22792. hold >>>= 1;
  22793. bits -= 1;
  22794. //---//
  22795. switch ((hold & 0x03)/*BITS(2)*/) {
  22796. case 0: /* stored block */
  22797. //Tracev((stderr, "inflate: stored block%s\n",
  22798. // state.last ? " (last)" : ""));
  22799. state.mode = STORED;
  22800. break;
  22801. case 1: /* fixed block */
  22802. fixedtables(state);
  22803. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22804. // state.last ? " (last)" : ""));
  22805. state.mode = LEN_; /* decode codes */
  22806. if (flush === Z_TREES) {
  22807. //--- DROPBITS(2) ---//
  22808. hold >>>= 2;
  22809. bits -= 2;
  22810. //---//
  22811. break inf_leave;
  22812. }
  22813. break;
  22814. case 2: /* dynamic block */
  22815. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22816. // state.last ? " (last)" : ""));
  22817. state.mode = TABLE;
  22818. break;
  22819. case 3:
  22820. strm.msg = 'invalid block type';
  22821. state.mode = BAD;
  22822. }
  22823. //--- DROPBITS(2) ---//
  22824. hold >>>= 2;
  22825. bits -= 2;
  22826. //---//
  22827. break;
  22828. case STORED:
  22829. //--- BYTEBITS() ---// /* go to byte boundary */
  22830. hold >>>= bits & 7;
  22831. bits -= bits & 7;
  22832. //---//
  22833. //=== NEEDBITS(32); */
  22834. while (bits < 32) {
  22835. if (have === 0) { break inf_leave; }
  22836. have--;
  22837. hold += input[next++] << bits;
  22838. bits += 8;
  22839. }
  22840. //===//
  22841. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22842. strm.msg = 'invalid stored block lengths';
  22843. state.mode = BAD;
  22844. break;
  22845. }
  22846. state.length = hold & 0xffff;
  22847. //Tracev((stderr, "inflate: stored length %u\n",
  22848. // state.length));
  22849. //=== INITBITS();
  22850. hold = 0;
  22851. bits = 0;
  22852. //===//
  22853. state.mode = COPY_;
  22854. if (flush === Z_TREES) { break inf_leave; }
  22855. /* falls through */
  22856. case COPY_:
  22857. state.mode = COPY;
  22858. /* falls through */
  22859. case COPY:
  22860. copy = state.length;
  22861. if (copy) {
  22862. if (copy > have) { copy = have; }
  22863. if (copy > left) { copy = left; }
  22864. if (copy === 0) { break inf_leave; }
  22865. //--- zmemcpy(put, next, copy); ---
  22866. utils.arraySet(output, input, next, copy, put);
  22867. //---//
  22868. have -= copy;
  22869. next += copy;
  22870. left -= copy;
  22871. put += copy;
  22872. state.length -= copy;
  22873. break;
  22874. }
  22875. //Tracev((stderr, "inflate: stored end\n"));
  22876. state.mode = TYPE;
  22877. break;
  22878. case TABLE:
  22879. //=== NEEDBITS(14); */
  22880. while (bits < 14) {
  22881. if (have === 0) { break inf_leave; }
  22882. have--;
  22883. hold += input[next++] << bits;
  22884. bits += 8;
  22885. }
  22886. //===//
  22887. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22888. //--- DROPBITS(5) ---//
  22889. hold >>>= 5;
  22890. bits -= 5;
  22891. //---//
  22892. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22893. //--- DROPBITS(5) ---//
  22894. hold >>>= 5;
  22895. bits -= 5;
  22896. //---//
  22897. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22898. //--- DROPBITS(4) ---//
  22899. hold >>>= 4;
  22900. bits -= 4;
  22901. //---//
  22902. //#ifndef PKZIP_BUG_WORKAROUND
  22903. if (state.nlen > 286 || state.ndist > 30) {
  22904. strm.msg = 'too many length or distance symbols';
  22905. state.mode = BAD;
  22906. break;
  22907. }
  22908. //#endif
  22909. //Tracev((stderr, "inflate: table sizes ok\n"));
  22910. state.have = 0;
  22911. state.mode = LENLENS;
  22912. /* falls through */
  22913. case LENLENS:
  22914. while (state.have < state.ncode) {
  22915. //=== NEEDBITS(3);
  22916. while (bits < 3) {
  22917. if (have === 0) { break inf_leave; }
  22918. have--;
  22919. hold += input[next++] << bits;
  22920. bits += 8;
  22921. }
  22922. //===//
  22923. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22924. //--- DROPBITS(3) ---//
  22925. hold >>>= 3;
  22926. bits -= 3;
  22927. //---//
  22928. }
  22929. while (state.have < 19) {
  22930. state.lens[order[state.have++]] = 0;
  22931. }
  22932. // We have separate tables & no pointers. 2 commented lines below not needed.
  22933. //state.next = state.codes;
  22934. //state.lencode = state.next;
  22935. // Switch to use dynamic table
  22936. state.lencode = state.lendyn;
  22937. state.lenbits = 7;
  22938. opts = {bits: state.lenbits};
  22939. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22940. state.lenbits = opts.bits;
  22941. if (ret) {
  22942. strm.msg = 'invalid code lengths set';
  22943. state.mode = BAD;
  22944. break;
  22945. }
  22946. //Tracev((stderr, "inflate: code lengths ok\n"));
  22947. state.have = 0;
  22948. state.mode = CODELENS;
  22949. /* falls through */
  22950. case CODELENS:
  22951. while (state.have < state.nlen + state.ndist) {
  22952. for (;;) {
  22953. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22954. here_bits = here >>> 24;
  22955. here_op = (here >>> 16) & 0xff;
  22956. here_val = here & 0xffff;
  22957. if ((here_bits) <= bits) { break; }
  22958. //--- PULLBYTE() ---//
  22959. if (have === 0) { break inf_leave; }
  22960. have--;
  22961. hold += input[next++] << bits;
  22962. bits += 8;
  22963. //---//
  22964. }
  22965. if (here_val < 16) {
  22966. //--- DROPBITS(here.bits) ---//
  22967. hold >>>= here_bits;
  22968. bits -= here_bits;
  22969. //---//
  22970. state.lens[state.have++] = here_val;
  22971. }
  22972. else {
  22973. if (here_val === 16) {
  22974. //=== NEEDBITS(here.bits + 2);
  22975. n = here_bits + 2;
  22976. while (bits < n) {
  22977. if (have === 0) { break inf_leave; }
  22978. have--;
  22979. hold += input[next++] << bits;
  22980. bits += 8;
  22981. }
  22982. //===//
  22983. //--- DROPBITS(here.bits) ---//
  22984. hold >>>= here_bits;
  22985. bits -= here_bits;
  22986. //---//
  22987. if (state.have === 0) {
  22988. strm.msg = 'invalid bit length repeat';
  22989. state.mode = BAD;
  22990. break;
  22991. }
  22992. len = state.lens[state.have - 1];
  22993. copy = 3 + (hold & 0x03);//BITS(2);
  22994. //--- DROPBITS(2) ---//
  22995. hold >>>= 2;
  22996. bits -= 2;
  22997. //---//
  22998. }
  22999. else if (here_val === 17) {
  23000. //=== NEEDBITS(here.bits + 3);
  23001. n = here_bits + 3;
  23002. while (bits < n) {
  23003. if (have === 0) { break inf_leave; }
  23004. have--;
  23005. hold += input[next++] << bits;
  23006. bits += 8;
  23007. }
  23008. //===//
  23009. //--- DROPBITS(here.bits) ---//
  23010. hold >>>= here_bits;
  23011. bits -= here_bits;
  23012. //---//
  23013. len = 0;
  23014. copy = 3 + (hold & 0x07);//BITS(3);
  23015. //--- DROPBITS(3) ---//
  23016. hold >>>= 3;
  23017. bits -= 3;
  23018. //---//
  23019. }
  23020. else {
  23021. //=== NEEDBITS(here.bits + 7);
  23022. n = here_bits + 7;
  23023. while (bits < n) {
  23024. if (have === 0) { break inf_leave; }
  23025. have--;
  23026. hold += input[next++] << bits;
  23027. bits += 8;
  23028. }
  23029. //===//
  23030. //--- DROPBITS(here.bits) ---//
  23031. hold >>>= here_bits;
  23032. bits -= here_bits;
  23033. //---//
  23034. len = 0;
  23035. copy = 11 + (hold & 0x7f);//BITS(7);
  23036. //--- DROPBITS(7) ---//
  23037. hold >>>= 7;
  23038. bits -= 7;
  23039. //---//
  23040. }
  23041. if (state.have + copy > state.nlen + state.ndist) {
  23042. strm.msg = 'invalid bit length repeat';
  23043. state.mode = BAD;
  23044. break;
  23045. }
  23046. while (copy--) {
  23047. state.lens[state.have++] = len;
  23048. }
  23049. }
  23050. }
  23051. /* handle error breaks in while */
  23052. if (state.mode === BAD) { break; }
  23053. /* check for end-of-block code (better have one) */
  23054. if (state.lens[256] === 0) {
  23055. strm.msg = 'invalid code -- missing end-of-block';
  23056. state.mode = BAD;
  23057. break;
  23058. }
  23059. /* build code tables -- note: do not change the lenbits or distbits
  23060. values here (9 and 6) without reading the comments in inftrees.h
  23061. concerning the ENOUGH constants, which depend on those values */
  23062. state.lenbits = 9;
  23063. opts = {bits: state.lenbits};
  23064. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23065. // We have separate tables & no pointers. 2 commented lines below not needed.
  23066. // state.next_index = opts.table_index;
  23067. state.lenbits = opts.bits;
  23068. // state.lencode = state.next;
  23069. if (ret) {
  23070. strm.msg = 'invalid literal/lengths set';
  23071. state.mode = BAD;
  23072. break;
  23073. }
  23074. state.distbits = 6;
  23075. //state.distcode.copy(state.codes);
  23076. // Switch to use dynamic table
  23077. state.distcode = state.distdyn;
  23078. opts = {bits: state.distbits};
  23079. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23080. // We have separate tables & no pointers. 2 commented lines below not needed.
  23081. // state.next_index = opts.table_index;
  23082. state.distbits = opts.bits;
  23083. // state.distcode = state.next;
  23084. if (ret) {
  23085. strm.msg = 'invalid distances set';
  23086. state.mode = BAD;
  23087. break;
  23088. }
  23089. //Tracev((stderr, 'inflate: codes ok\n'));
  23090. state.mode = LEN_;
  23091. if (flush === Z_TREES) { break inf_leave; }
  23092. /* falls through */
  23093. case LEN_:
  23094. state.mode = LEN;
  23095. /* falls through */
  23096. case LEN:
  23097. if (have >= 6 && left >= 258) {
  23098. //--- RESTORE() ---
  23099. strm.next_out = put;
  23100. strm.avail_out = left;
  23101. strm.next_in = next;
  23102. strm.avail_in = have;
  23103. state.hold = hold;
  23104. state.bits = bits;
  23105. //---
  23106. inflate_fast(strm, _out);
  23107. //--- LOAD() ---
  23108. put = strm.next_out;
  23109. output = strm.output;
  23110. left = strm.avail_out;
  23111. next = strm.next_in;
  23112. input = strm.input;
  23113. have = strm.avail_in;
  23114. hold = state.hold;
  23115. bits = state.bits;
  23116. //---
  23117. if (state.mode === TYPE) {
  23118. state.back = -1;
  23119. }
  23120. break;
  23121. }
  23122. state.back = 0;
  23123. for (;;) {
  23124. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23125. here_bits = here >>> 24;
  23126. here_op = (here >>> 16) & 0xff;
  23127. here_val = here & 0xffff;
  23128. if (here_bits <= bits) { break; }
  23129. //--- PULLBYTE() ---//
  23130. if (have === 0) { break inf_leave; }
  23131. have--;
  23132. hold += input[next++] << bits;
  23133. bits += 8;
  23134. //---//
  23135. }
  23136. if (here_op && (here_op & 0xf0) === 0) {
  23137. last_bits = here_bits;
  23138. last_op = here_op;
  23139. last_val = here_val;
  23140. for (;;) {
  23141. here = state.lencode[last_val +
  23142. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23143. here_bits = here >>> 24;
  23144. here_op = (here >>> 16) & 0xff;
  23145. here_val = here & 0xffff;
  23146. if ((last_bits + here_bits) <= bits) { break; }
  23147. //--- PULLBYTE() ---//
  23148. if (have === 0) { break inf_leave; }
  23149. have--;
  23150. hold += input[next++] << bits;
  23151. bits += 8;
  23152. //---//
  23153. }
  23154. //--- DROPBITS(last.bits) ---//
  23155. hold >>>= last_bits;
  23156. bits -= last_bits;
  23157. //---//
  23158. state.back += last_bits;
  23159. }
  23160. //--- DROPBITS(here.bits) ---//
  23161. hold >>>= here_bits;
  23162. bits -= here_bits;
  23163. //---//
  23164. state.back += here_bits;
  23165. state.length = here_val;
  23166. if (here_op === 0) {
  23167. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23168. // "inflate: literal '%c'\n" :
  23169. // "inflate: literal 0x%02x\n", here.val));
  23170. state.mode = LIT;
  23171. break;
  23172. }
  23173. if (here_op & 32) {
  23174. //Tracevv((stderr, "inflate: end of block\n"));
  23175. state.back = -1;
  23176. state.mode = TYPE;
  23177. break;
  23178. }
  23179. if (here_op & 64) {
  23180. strm.msg = 'invalid literal/length code';
  23181. state.mode = BAD;
  23182. break;
  23183. }
  23184. state.extra = here_op & 15;
  23185. state.mode = LENEXT;
  23186. /* falls through */
  23187. case LENEXT:
  23188. if (state.extra) {
  23189. //=== NEEDBITS(state.extra);
  23190. n = state.extra;
  23191. while (bits < n) {
  23192. if (have === 0) { break inf_leave; }
  23193. have--;
  23194. hold += input[next++] << bits;
  23195. bits += 8;
  23196. }
  23197. //===//
  23198. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23199. //--- DROPBITS(state.extra) ---//
  23200. hold >>>= state.extra;
  23201. bits -= state.extra;
  23202. //---//
  23203. state.back += state.extra;
  23204. }
  23205. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23206. state.was = state.length;
  23207. state.mode = DIST;
  23208. /* falls through */
  23209. case DIST:
  23210. for (;;) {
  23211. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23212. here_bits = here >>> 24;
  23213. here_op = (here >>> 16) & 0xff;
  23214. here_val = here & 0xffff;
  23215. if ((here_bits) <= bits) { break; }
  23216. //--- PULLBYTE() ---//
  23217. if (have === 0) { break inf_leave; }
  23218. have--;
  23219. hold += input[next++] << bits;
  23220. bits += 8;
  23221. //---//
  23222. }
  23223. if ((here_op & 0xf0) === 0) {
  23224. last_bits = here_bits;
  23225. last_op = here_op;
  23226. last_val = here_val;
  23227. for (;;) {
  23228. here = state.distcode[last_val +
  23229. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23230. here_bits = here >>> 24;
  23231. here_op = (here >>> 16) & 0xff;
  23232. here_val = here & 0xffff;
  23233. if ((last_bits + here_bits) <= bits) { break; }
  23234. //--- PULLBYTE() ---//
  23235. if (have === 0) { break inf_leave; }
  23236. have--;
  23237. hold += input[next++] << bits;
  23238. bits += 8;
  23239. //---//
  23240. }
  23241. //--- DROPBITS(last.bits) ---//
  23242. hold >>>= last_bits;
  23243. bits -= last_bits;
  23244. //---//
  23245. state.back += last_bits;
  23246. }
  23247. //--- DROPBITS(here.bits) ---//
  23248. hold >>>= here_bits;
  23249. bits -= here_bits;
  23250. //---//
  23251. state.back += here_bits;
  23252. if (here_op & 64) {
  23253. strm.msg = 'invalid distance code';
  23254. state.mode = BAD;
  23255. break;
  23256. }
  23257. state.offset = here_val;
  23258. state.extra = (here_op) & 15;
  23259. state.mode = DISTEXT;
  23260. /* falls through */
  23261. case DISTEXT:
  23262. if (state.extra) {
  23263. //=== NEEDBITS(state.extra);
  23264. n = state.extra;
  23265. while (bits < n) {
  23266. if (have === 0) { break inf_leave; }
  23267. have--;
  23268. hold += input[next++] << bits;
  23269. bits += 8;
  23270. }
  23271. //===//
  23272. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23273. //--- DROPBITS(state.extra) ---//
  23274. hold >>>= state.extra;
  23275. bits -= state.extra;
  23276. //---//
  23277. state.back += state.extra;
  23278. }
  23279. //#ifdef INFLATE_STRICT
  23280. if (state.offset > state.dmax) {
  23281. strm.msg = 'invalid distance too far back';
  23282. state.mode = BAD;
  23283. break;
  23284. }
  23285. //#endif
  23286. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23287. state.mode = MATCH;
  23288. /* falls through */
  23289. case MATCH:
  23290. if (left === 0) { break inf_leave; }
  23291. copy = _out - left;
  23292. if (state.offset > copy) { /* copy from window */
  23293. copy = state.offset - copy;
  23294. if (copy > state.whave) {
  23295. if (state.sane) {
  23296. strm.msg = 'invalid distance too far back';
  23297. state.mode = BAD;
  23298. break;
  23299. }
  23300. // (!) This block is disabled in zlib defailts,
  23301. // don't enable it for binary compatibility
  23302. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23303. // Trace((stderr, "inflate.c too far\n"));
  23304. // copy -= state.whave;
  23305. // if (copy > state.length) { copy = state.length; }
  23306. // if (copy > left) { copy = left; }
  23307. // left -= copy;
  23308. // state.length -= copy;
  23309. // do {
  23310. // output[put++] = 0;
  23311. // } while (--copy);
  23312. // if (state.length === 0) { state.mode = LEN; }
  23313. // break;
  23314. //#endif
  23315. }
  23316. if (copy > state.wnext) {
  23317. copy -= state.wnext;
  23318. from = state.wsize - copy;
  23319. }
  23320. else {
  23321. from = state.wnext - copy;
  23322. }
  23323. if (copy > state.length) { copy = state.length; }
  23324. from_source = state.window;
  23325. }
  23326. else { /* copy from output */
  23327. from_source = output;
  23328. from = put - state.offset;
  23329. copy = state.length;
  23330. }
  23331. if (copy > left) { copy = left; }
  23332. left -= copy;
  23333. state.length -= copy;
  23334. do {
  23335. output[put++] = from_source[from++];
  23336. } while (--copy);
  23337. if (state.length === 0) { state.mode = LEN; }
  23338. break;
  23339. case LIT:
  23340. if (left === 0) { break inf_leave; }
  23341. output[put++] = state.length;
  23342. left--;
  23343. state.mode = LEN;
  23344. break;
  23345. case CHECK:
  23346. if (state.wrap) {
  23347. //=== NEEDBITS(32);
  23348. while (bits < 32) {
  23349. if (have === 0) { break inf_leave; }
  23350. have--;
  23351. // Use '|' insdead of '+' to make sure that result is signed
  23352. hold |= input[next++] << bits;
  23353. bits += 8;
  23354. }
  23355. //===//
  23356. _out -= left;
  23357. strm.total_out += _out;
  23358. state.total += _out;
  23359. if (_out) {
  23360. strm.adler = state.check =
  23361. /*UPDATE(state.check, put - _out, _out);*/
  23362. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23363. }
  23364. _out = left;
  23365. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23366. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23367. strm.msg = 'incorrect data check';
  23368. state.mode = BAD;
  23369. break;
  23370. }
  23371. //=== INITBITS();
  23372. hold = 0;
  23373. bits = 0;
  23374. //===//
  23375. //Tracev((stderr, "inflate: check matches trailer\n"));
  23376. }
  23377. state.mode = LENGTH;
  23378. /* falls through */
  23379. case LENGTH:
  23380. if (state.wrap && state.flags) {
  23381. //=== NEEDBITS(32);
  23382. while (bits < 32) {
  23383. if (have === 0) { break inf_leave; }
  23384. have--;
  23385. hold += input[next++] << bits;
  23386. bits += 8;
  23387. }
  23388. //===//
  23389. if (hold !== (state.total & 0xffffffff)) {
  23390. strm.msg = 'incorrect length check';
  23391. state.mode = BAD;
  23392. break;
  23393. }
  23394. //=== INITBITS();
  23395. hold = 0;
  23396. bits = 0;
  23397. //===//
  23398. //Tracev((stderr, "inflate: length matches trailer\n"));
  23399. }
  23400. state.mode = DONE;
  23401. /* falls through */
  23402. case DONE:
  23403. ret = Z_STREAM_END;
  23404. break inf_leave;
  23405. case BAD:
  23406. ret = Z_DATA_ERROR;
  23407. break inf_leave;
  23408. case MEM:
  23409. return Z_MEM_ERROR;
  23410. case SYNC:
  23411. /* falls through */
  23412. default:
  23413. return Z_STREAM_ERROR;
  23414. }
  23415. }
  23416. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23417. /*
  23418. Return from inflate(), updating the total counts and the check value.
  23419. If there was no progress during the inflate() call, return a buffer
  23420. error. Call updatewindow() to create and/or update the window state.
  23421. Note: a memory error from inflate() is non-recoverable.
  23422. */
  23423. //--- RESTORE() ---
  23424. strm.next_out = put;
  23425. strm.avail_out = left;
  23426. strm.next_in = next;
  23427. strm.avail_in = have;
  23428. state.hold = hold;
  23429. state.bits = bits;
  23430. //---
  23431. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23432. (state.mode < CHECK || flush !== Z_FINISH))) {
  23433. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23434. state.mode = MEM;
  23435. return Z_MEM_ERROR;
  23436. }
  23437. }
  23438. _in -= strm.avail_in;
  23439. _out -= strm.avail_out;
  23440. strm.total_in += _in;
  23441. strm.total_out += _out;
  23442. state.total += _out;
  23443. if (state.wrap && _out) {
  23444. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23445. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23446. }
  23447. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23448. (state.mode === TYPE ? 128 : 0) +
  23449. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23450. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23451. ret = Z_BUF_ERROR;
  23452. }
  23453. return ret;
  23454. }
  23455. function inflateEnd(strm) {
  23456. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23457. return Z_STREAM_ERROR;
  23458. }
  23459. var state = strm.state;
  23460. if (state.window) {
  23461. state.window = null;
  23462. }
  23463. strm.state = null;
  23464. return Z_OK;
  23465. }
  23466. function inflateGetHeader(strm, head) {
  23467. var state;
  23468. /* check state */
  23469. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23470. state = strm.state;
  23471. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23472. /* save header structure */
  23473. state.head = head;
  23474. head.done = false;
  23475. return Z_OK;
  23476. }
  23477. exports.inflateReset = inflateReset;
  23478. exports.inflateReset2 = inflateReset2;
  23479. exports.inflateResetKeep = inflateResetKeep;
  23480. exports.inflateInit = inflateInit;
  23481. exports.inflateInit2 = inflateInit2;
  23482. exports.inflate = inflate;
  23483. exports.inflateEnd = inflateEnd;
  23484. exports.inflateGetHeader = inflateGetHeader;
  23485. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23486. /* Not implemented
  23487. exports.inflateCopy = inflateCopy;
  23488. exports.inflateGetDictionary = inflateGetDictionary;
  23489. exports.inflateMark = inflateMark;
  23490. exports.inflatePrime = inflatePrime;
  23491. exports.inflateSetDictionary = inflateSetDictionary;
  23492. exports.inflateSync = inflateSync;
  23493. exports.inflateSyncPoint = inflateSyncPoint;
  23494. exports.inflateUndermine = inflateUndermine;
  23495. */
  23496. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./inffast":79,"./inftrees":81}],81:[function(require,module,exports){
  23497. 'use strict';
  23498. var utils = require('../utils/common');
  23499. var MAXBITS = 15;
  23500. var ENOUGH_LENS = 852;
  23501. var ENOUGH_DISTS = 592;
  23502. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23503. var CODES = 0;
  23504. var LENS = 1;
  23505. var DISTS = 2;
  23506. var lbase = [ /* Length codes 257..285 base */
  23507. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23508. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23509. ];
  23510. var lext = [ /* Length codes 257..285 extra */
  23511. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23512. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23513. ];
  23514. var dbase = [ /* Distance codes 0..29 base */
  23515. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23516. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23517. 8193, 12289, 16385, 24577, 0, 0
  23518. ];
  23519. var dext = [ /* Distance codes 0..29 extra */
  23520. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23521. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23522. 28, 28, 29, 29, 64, 64
  23523. ];
  23524. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23525. {
  23526. var bits = opts.bits;
  23527. //here = opts.here; /* table entry for duplication */
  23528. var len = 0; /* a code's length in bits */
  23529. var sym = 0; /* index of code symbols */
  23530. var min = 0, max = 0; /* minimum and maximum code lengths */
  23531. var root = 0; /* number of index bits for root table */
  23532. var curr = 0; /* number of index bits for current table */
  23533. var drop = 0; /* code bits to drop for sub-table */
  23534. var left = 0; /* number of prefix codes available */
  23535. var used = 0; /* code entries in table used */
  23536. var huff = 0; /* Huffman code */
  23537. var incr; /* for incrementing code, index */
  23538. var fill; /* index for replicating entries */
  23539. var low; /* low bits for current root entry */
  23540. var mask; /* mask for low root bits */
  23541. var next; /* next available space in table */
  23542. var base = null; /* base value table to use */
  23543. var base_index = 0;
  23544. // var shoextra; /* extra bits table to use */
  23545. var end; /* use base and extra for symbol > end */
  23546. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23547. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23548. var extra = null;
  23549. var extra_index = 0;
  23550. var here_bits, here_op, here_val;
  23551. /*
  23552. Process a set of code lengths to create a canonical Huffman code. The
  23553. code lengths are lens[0..codes-1]. Each length corresponds to the
  23554. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23555. symbols by length from short to long, and retaining the symbol order
  23556. for codes with equal lengths. Then the code starts with all zero bits
  23557. for the first code of the shortest length, and the codes are integer
  23558. increments for the same length, and zeros are appended as the length
  23559. increases. For the deflate format, these bits are stored backwards
  23560. from their more natural integer increment ordering, and so when the
  23561. decoding tables are built in the large loop below, the integer codes
  23562. are incremented backwards.
  23563. This routine assumes, but does not check, that all of the entries in
  23564. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23565. 1..MAXBITS is interpreted as that code length. zero means that that
  23566. symbol does not occur in this code.
  23567. The codes are sorted by computing a count of codes for each length,
  23568. creating from that a table of starting indices for each length in the
  23569. sorted table, and then entering the symbols in order in the sorted
  23570. table. The sorted table is work[], with that space being provided by
  23571. the caller.
  23572. The length counts are used for other purposes as well, i.e. finding
  23573. the minimum and maximum length codes, determining if there are any
  23574. codes at all, checking for a valid set of lengths, and looking ahead
  23575. at length counts to determine sub-table sizes when building the
  23576. decoding tables.
  23577. */
  23578. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23579. for (len = 0; len <= MAXBITS; len++) {
  23580. count[len] = 0;
  23581. }
  23582. for (sym = 0; sym < codes; sym++) {
  23583. count[lens[lens_index + sym]]++;
  23584. }
  23585. /* bound code lengths, force root to be within code lengths */
  23586. root = bits;
  23587. for (max = MAXBITS; max >= 1; max--) {
  23588. if (count[max] !== 0) { break; }
  23589. }
  23590. if (root > max) {
  23591. root = max;
  23592. }
  23593. if (max === 0) { /* no symbols to code at all */
  23594. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23595. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23596. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23597. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23598. //table.op[opts.table_index] = 64;
  23599. //table.bits[opts.table_index] = 1;
  23600. //table.val[opts.table_index++] = 0;
  23601. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23602. opts.bits = 1;
  23603. return 0; /* no symbols, but wait for decoding to report error */
  23604. }
  23605. for (min = 1; min < max; min++) {
  23606. if (count[min] !== 0) { break; }
  23607. }
  23608. if (root < min) {
  23609. root = min;
  23610. }
  23611. /* check for an over-subscribed or incomplete set of lengths */
  23612. left = 1;
  23613. for (len = 1; len <= MAXBITS; len++) {
  23614. left <<= 1;
  23615. left -= count[len];
  23616. if (left < 0) {
  23617. return -1;
  23618. } /* over-subscribed */
  23619. }
  23620. if (left > 0 && (type === CODES || max !== 1)) {
  23621. return -1; /* incomplete set */
  23622. }
  23623. /* generate offsets into symbol table for each length for sorting */
  23624. offs[1] = 0;
  23625. for (len = 1; len < MAXBITS; len++) {
  23626. offs[len + 1] = offs[len] + count[len];
  23627. }
  23628. /* sort symbols by length, by symbol order within each length */
  23629. for (sym = 0; sym < codes; sym++) {
  23630. if (lens[lens_index + sym] !== 0) {
  23631. work[offs[lens[lens_index + sym]]++] = sym;
  23632. }
  23633. }
  23634. /*
  23635. Create and fill in decoding tables. In this loop, the table being
  23636. filled is at next and has curr index bits. The code being used is huff
  23637. with length len. That code is converted to an index by dropping drop
  23638. bits off of the bottom. For codes where len is less than drop + curr,
  23639. those top drop + curr - len bits are incremented through all values to
  23640. fill the table with replicated entries.
  23641. root is the number of index bits for the root table. When len exceeds
  23642. root, sub-tables are created pointed to by the root entry with an index
  23643. of the low root bits of huff. This is saved in low to check for when a
  23644. new sub-table should be started. drop is zero when the root table is
  23645. being filled, and drop is root when sub-tables are being filled.
  23646. When a new sub-table is needed, it is necessary to look ahead in the
  23647. code lengths to determine what size sub-table is needed. The length
  23648. counts are used for this, and so count[] is decremented as codes are
  23649. entered in the tables.
  23650. used keeps track of how many table entries have been allocated from the
  23651. provided *table space. It is checked for LENS and DIST tables against
  23652. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23653. the initial root table size constants. See the comments in inftrees.h
  23654. for more information.
  23655. sym increments through all symbols, and the loop terminates when
  23656. all codes of length max, i.e. all codes, have been processed. This
  23657. routine permits incomplete codes, so another loop after this one fills
  23658. in the rest of the decoding tables with invalid code markers.
  23659. */
  23660. /* set up for code type */
  23661. // poor man optimization - use if-else instead of switch,
  23662. // to avoid deopts in old v8
  23663. if (type === CODES) {
  23664. base = extra = work; /* dummy value--not used */
  23665. end = 19;
  23666. } else if (type === LENS) {
  23667. base = lbase;
  23668. base_index -= 257;
  23669. extra = lext;
  23670. extra_index -= 257;
  23671. end = 256;
  23672. } else { /* DISTS */
  23673. base = dbase;
  23674. extra = dext;
  23675. end = -1;
  23676. }
  23677. /* initialize opts for loop */
  23678. huff = 0; /* starting code */
  23679. sym = 0; /* starting code symbol */
  23680. len = min; /* starting code length */
  23681. next = table_index; /* current table to fill in */
  23682. curr = root; /* current table index bits */
  23683. drop = 0; /* current bits to drop from code for index */
  23684. low = -1; /* trigger new sub-table when len > root */
  23685. used = 1 << root; /* use root table entries */
  23686. mask = used - 1; /* mask for comparing low */
  23687. /* check available table space */
  23688. if ((type === LENS && used > ENOUGH_LENS) ||
  23689. (type === DISTS && used > ENOUGH_DISTS)) {
  23690. return 1;
  23691. }
  23692. var i=0;
  23693. /* process all codes and make table entries */
  23694. for (;;) {
  23695. i++;
  23696. /* create table entry */
  23697. here_bits = len - drop;
  23698. if (work[sym] < end) {
  23699. here_op = 0;
  23700. here_val = work[sym];
  23701. }
  23702. else if (work[sym] > end) {
  23703. here_op = extra[extra_index + work[sym]];
  23704. here_val = base[base_index + work[sym]];
  23705. }
  23706. else {
  23707. here_op = 32 + 64; /* end of block */
  23708. here_val = 0;
  23709. }
  23710. /* replicate for those indices with low len bits equal to huff */
  23711. incr = 1 << (len - drop);
  23712. fill = 1 << curr;
  23713. min = fill; /* save offset to next table */
  23714. do {
  23715. fill -= incr;
  23716. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23717. } while (fill !== 0);
  23718. /* backwards increment the len-bit code huff */
  23719. incr = 1 << (len - 1);
  23720. while (huff & incr) {
  23721. incr >>= 1;
  23722. }
  23723. if (incr !== 0) {
  23724. huff &= incr - 1;
  23725. huff += incr;
  23726. } else {
  23727. huff = 0;
  23728. }
  23729. /* go to next symbol, update count, len */
  23730. sym++;
  23731. if (--count[len] === 0) {
  23732. if (len === max) { break; }
  23733. len = lens[lens_index + work[sym]];
  23734. }
  23735. /* create new sub-table if needed */
  23736. if (len > root && (huff & mask) !== low) {
  23737. /* if first time, transition to sub-tables */
  23738. if (drop === 0) {
  23739. drop = root;
  23740. }
  23741. /* increment past last table */
  23742. next += min; /* here min is 1 << curr */
  23743. /* determine length of next table */
  23744. curr = len - drop;
  23745. left = 1 << curr;
  23746. while (curr + drop < max) {
  23747. left -= count[curr + drop];
  23748. if (left <= 0) { break; }
  23749. curr++;
  23750. left <<= 1;
  23751. }
  23752. /* check for enough space */
  23753. used += 1 << curr;
  23754. if ((type === LENS && used > ENOUGH_LENS) ||
  23755. (type === DISTS && used > ENOUGH_DISTS)) {
  23756. return 1;
  23757. }
  23758. /* point entry in root table to sub-table */
  23759. low = huff & mask;
  23760. /*table.op[low] = curr;
  23761. table.bits[low] = root;
  23762. table.val[low] = next - opts.table_index;*/
  23763. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23764. }
  23765. }
  23766. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23767. at most one remaining entry, since if the code is incomplete, the
  23768. maximum code length that was allowed to get this far is one bit) */
  23769. if (huff !== 0) {
  23770. //table.op[next + huff] = 64; /* invalid code marker */
  23771. //table.bits[next + huff] = len - drop;
  23772. //table.val[next + huff] = 0;
  23773. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23774. }
  23775. /* set return parameters */
  23776. //opts.table_index += used;
  23777. opts.bits = root;
  23778. return 0;
  23779. };
  23780. },{"../utils/common":72}],82:[function(require,module,exports){
  23781. 'use strict';
  23782. module.exports = {
  23783. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23784. '1': 'stream end', /* Z_STREAM_END 1 */
  23785. '0': '', /* Z_OK 0 */
  23786. '-1': 'file error', /* Z_ERRNO (-1) */
  23787. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23788. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23789. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23790. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23791. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23792. };
  23793. },{}],83:[function(require,module,exports){
  23794. 'use strict';
  23795. var utils = require('../utils/common');
  23796. /* Public constants ==========================================================*/
  23797. /* ===========================================================================*/
  23798. //var Z_FILTERED = 1;
  23799. //var Z_HUFFMAN_ONLY = 2;
  23800. //var Z_RLE = 3;
  23801. var Z_FIXED = 4;
  23802. //var Z_DEFAULT_STRATEGY = 0;
  23803. /* Possible values of the data_type field (though see inflate()) */
  23804. var Z_BINARY = 0;
  23805. var Z_TEXT = 1;
  23806. //var Z_ASCII = 1; // = Z_TEXT
  23807. var Z_UNKNOWN = 2;
  23808. /*============================================================================*/
  23809. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23810. // From zutil.h
  23811. var STORED_BLOCK = 0;
  23812. var STATIC_TREES = 1;
  23813. var DYN_TREES = 2;
  23814. /* The three kinds of block type */
  23815. var MIN_MATCH = 3;
  23816. var MAX_MATCH = 258;
  23817. /* The minimum and maximum match lengths */
  23818. // From deflate.h
  23819. /* ===========================================================================
  23820. * Internal compression state.
  23821. */
  23822. var LENGTH_CODES = 29;
  23823. /* number of length codes, not counting the special END_BLOCK code */
  23824. var LITERALS = 256;
  23825. /* number of literal bytes 0..255 */
  23826. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23827. /* number of Literal or Length codes, including the END_BLOCK code */
  23828. var D_CODES = 30;
  23829. /* number of distance codes */
  23830. var BL_CODES = 19;
  23831. /* number of codes used to transfer the bit lengths */
  23832. var HEAP_SIZE = 2*L_CODES + 1;
  23833. /* maximum heap size */
  23834. var MAX_BITS = 15;
  23835. /* All codes must not exceed MAX_BITS bits */
  23836. var Buf_size = 16;
  23837. /* size of bit buffer in bi_buf */
  23838. /* ===========================================================================
  23839. * Constants
  23840. */
  23841. var MAX_BL_BITS = 7;
  23842. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23843. var END_BLOCK = 256;
  23844. /* end of block literal code */
  23845. var REP_3_6 = 16;
  23846. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23847. var REPZ_3_10 = 17;
  23848. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23849. var REPZ_11_138 = 18;
  23850. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23851. var extra_lbits = /* extra bits for each length code */
  23852. [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];
  23853. var extra_dbits = /* extra bits for each distance code */
  23854. [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];
  23855. var extra_blbits = /* extra bits for each bit length code */
  23856. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23857. var bl_order =
  23858. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23859. /* The lengths of the bit length codes are sent in order of decreasing
  23860. * probability, to avoid transmitting the lengths for unused bit length codes.
  23861. */
  23862. /* ===========================================================================
  23863. * Local data. These are initialized only once.
  23864. */
  23865. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23866. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23867. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23868. var static_ltree = new Array((L_CODES+2) * 2);
  23869. zero(static_ltree);
  23870. /* The static literal tree. Since the bit lengths are imposed, there is no
  23871. * need for the L_CODES extra codes used during heap construction. However
  23872. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23873. * below).
  23874. */
  23875. var static_dtree = new Array(D_CODES * 2);
  23876. zero(static_dtree);
  23877. /* The static distance tree. (Actually a trivial tree since all codes use
  23878. * 5 bits.)
  23879. */
  23880. var _dist_code = new Array(DIST_CODE_LEN);
  23881. zero(_dist_code);
  23882. /* Distance codes. The first 256 values correspond to the distances
  23883. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23884. * the 15 bit distances.
  23885. */
  23886. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23887. zero(_length_code);
  23888. /* length code for each normalized match length (0 == MIN_MATCH) */
  23889. var base_length = new Array(LENGTH_CODES);
  23890. zero(base_length);
  23891. /* First normalized length for each code (0 = MIN_MATCH) */
  23892. var base_dist = new Array(D_CODES);
  23893. zero(base_dist);
  23894. /* First normalized distance for each code (0 = distance of 1) */
  23895. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23896. this.static_tree = static_tree; /* static tree or NULL */
  23897. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23898. this.extra_base = extra_base; /* base index for extra_bits */
  23899. this.elems = elems; /* max number of elements in the tree */
  23900. this.max_length = max_length; /* max bit length for the codes */
  23901. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23902. this.has_stree = static_tree && static_tree.length;
  23903. };
  23904. var static_l_desc;
  23905. var static_d_desc;
  23906. var static_bl_desc;
  23907. var TreeDesc = function(dyn_tree, stat_desc) {
  23908. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23909. this.max_code = 0; /* largest code with non zero frequency */
  23910. this.stat_desc = stat_desc; /* the corresponding static tree */
  23911. };
  23912. function d_code(dist) {
  23913. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23914. }
  23915. /* ===========================================================================
  23916. * Output a short LSB first on the stream.
  23917. * IN assertion: there is enough room in pendingBuf.
  23918. */
  23919. function put_short (s, w) {
  23920. // put_byte(s, (uch)((w) & 0xff));
  23921. // put_byte(s, (uch)((ush)(w) >> 8));
  23922. s.pending_buf[s.pending++] = (w) & 0xff;
  23923. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23924. }
  23925. /* ===========================================================================
  23926. * Send a value on a given number of bits.
  23927. * IN assertion: length <= 16 and value fits in length bits.
  23928. */
  23929. function send_bits(s, value, length) {
  23930. if (s.bi_valid > (Buf_size - length)) {
  23931. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23932. put_short(s, s.bi_buf);
  23933. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23934. s.bi_valid += length - Buf_size;
  23935. } else {
  23936. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23937. s.bi_valid += length;
  23938. }
  23939. }
  23940. function send_code(s, c, tree) {
  23941. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23942. }
  23943. /* ===========================================================================
  23944. * Reverse the first len bits of a code, using straightforward code (a faster
  23945. * method would use a table)
  23946. * IN assertion: 1 <= len <= 15
  23947. */
  23948. function bi_reverse(code, len) {
  23949. var res = 0;
  23950. do {
  23951. res |= code & 1;
  23952. code >>>= 1;
  23953. res <<= 1;
  23954. } while (--len > 0);
  23955. return res >>> 1;
  23956. }
  23957. /* ===========================================================================
  23958. * Flush the bit buffer, keeping at most 7 bits in it.
  23959. */
  23960. function bi_flush(s) {
  23961. if (s.bi_valid === 16) {
  23962. put_short(s, s.bi_buf);
  23963. s.bi_buf = 0;
  23964. s.bi_valid = 0;
  23965. } else if (s.bi_valid >= 8) {
  23966. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23967. s.bi_buf >>= 8;
  23968. s.bi_valid -= 8;
  23969. }
  23970. }
  23971. /* ===========================================================================
  23972. * Compute the optimal bit lengths for a tree and update the total bit length
  23973. * for the current block.
  23974. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23975. * above are the tree nodes sorted by increasing frequency.
  23976. * OUT assertions: the field len is set to the optimal bit length, the
  23977. * array bl_count contains the frequencies for each bit length.
  23978. * The length opt_len is updated; static_len is also updated if stree is
  23979. * not null.
  23980. */
  23981. function gen_bitlen(s, desc)
  23982. // deflate_state *s;
  23983. // tree_desc *desc; /* the tree descriptor */
  23984. {
  23985. var tree = desc.dyn_tree;
  23986. var max_code = desc.max_code;
  23987. var stree = desc.stat_desc.static_tree;
  23988. var has_stree = desc.stat_desc.has_stree;
  23989. var extra = desc.stat_desc.extra_bits;
  23990. var base = desc.stat_desc.extra_base;
  23991. var max_length = desc.stat_desc.max_length;
  23992. var h; /* heap index */
  23993. var n, m; /* iterate over the tree elements */
  23994. var bits; /* bit length */
  23995. var xbits; /* extra bits */
  23996. var f; /* frequency */
  23997. var overflow = 0; /* number of elements with bit length too large */
  23998. for (bits = 0; bits <= MAX_BITS; bits++) {
  23999. s.bl_count[bits] = 0;
  24000. }
  24001. /* In a first pass, compute the optimal bit lengths (which may
  24002. * overflow in the case of the bit length tree).
  24003. */
  24004. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24005. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24006. n = s.heap[h];
  24007. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24008. if (bits > max_length) {
  24009. bits = max_length;
  24010. overflow++;
  24011. }
  24012. tree[n*2 + 1]/*.Len*/ = bits;
  24013. /* We overwrite tree[n].Dad which is no longer needed */
  24014. if (n > max_code) { continue; } /* not a leaf node */
  24015. s.bl_count[bits]++;
  24016. xbits = 0;
  24017. if (n >= base) {
  24018. xbits = extra[n-base];
  24019. }
  24020. f = tree[n * 2]/*.Freq*/;
  24021. s.opt_len += f * (bits + xbits);
  24022. if (has_stree) {
  24023. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24024. }
  24025. }
  24026. if (overflow === 0) { return; }
  24027. // Trace((stderr,"\nbit length overflow\n"));
  24028. /* This happens for example on obj2 and pic of the Calgary corpus */
  24029. /* Find the first bit length which could increase: */
  24030. do {
  24031. bits = max_length-1;
  24032. while (s.bl_count[bits] === 0) { bits--; }
  24033. s.bl_count[bits]--; /* move one leaf down the tree */
  24034. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24035. s.bl_count[max_length]--;
  24036. /* The brother of the overflow item also moves one step up,
  24037. * but this does not affect bl_count[max_length]
  24038. */
  24039. overflow -= 2;
  24040. } while (overflow > 0);
  24041. /* Now recompute all bit lengths, scanning in increasing frequency.
  24042. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24043. * lengths instead of fixing only the wrong ones. This idea is taken
  24044. * from 'ar' written by Haruhiko Okumura.)
  24045. */
  24046. for (bits = max_length; bits !== 0; bits--) {
  24047. n = s.bl_count[bits];
  24048. while (n !== 0) {
  24049. m = s.heap[--h];
  24050. if (m > max_code) { continue; }
  24051. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24052. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24053. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24054. tree[m*2 + 1]/*.Len*/ = bits;
  24055. }
  24056. n--;
  24057. }
  24058. }
  24059. }
  24060. /* ===========================================================================
  24061. * Generate the codes for a given tree and bit counts (which need not be
  24062. * optimal).
  24063. * IN assertion: the array bl_count contains the bit length statistics for
  24064. * the given tree and the field len is set for all tree elements.
  24065. * OUT assertion: the field code is set for all tree elements of non
  24066. * zero code length.
  24067. */
  24068. function gen_codes(tree, max_code, bl_count)
  24069. // ct_data *tree; /* the tree to decorate */
  24070. // int max_code; /* largest code with non zero frequency */
  24071. // ushf *bl_count; /* number of codes at each bit length */
  24072. {
  24073. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24074. var code = 0; /* running code value */
  24075. var bits; /* bit index */
  24076. var n; /* code index */
  24077. /* The distribution counts are first used to generate the code values
  24078. * without bit reversal.
  24079. */
  24080. for (bits = 1; bits <= MAX_BITS; bits++) {
  24081. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24082. }
  24083. /* Check that the bit counts in bl_count are consistent. The last code
  24084. * must be all ones.
  24085. */
  24086. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24087. // "inconsistent bit counts");
  24088. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24089. for (n = 0; n <= max_code; n++) {
  24090. var len = tree[n*2 + 1]/*.Len*/;
  24091. if (len === 0) { continue; }
  24092. /* Now reverse the bits */
  24093. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24094. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24095. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24096. }
  24097. }
  24098. /* ===========================================================================
  24099. * Initialize the various 'constant' tables.
  24100. */
  24101. function tr_static_init() {
  24102. var n; /* iterates over tree elements */
  24103. var bits; /* bit counter */
  24104. var length; /* length value */
  24105. var code; /* code value */
  24106. var dist; /* distance index */
  24107. var bl_count = new Array(MAX_BITS+1);
  24108. /* number of codes at each bit length for an optimal tree */
  24109. // do check in _tr_init()
  24110. //if (static_init_done) return;
  24111. /* For some embedded targets, global variables are not initialized: */
  24112. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24113. static_l_desc.static_tree = static_ltree;
  24114. static_l_desc.extra_bits = extra_lbits;
  24115. static_d_desc.static_tree = static_dtree;
  24116. static_d_desc.extra_bits = extra_dbits;
  24117. static_bl_desc.extra_bits = extra_blbits;
  24118. #endif*/
  24119. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24120. length = 0;
  24121. for (code = 0; code < LENGTH_CODES-1; code++) {
  24122. base_length[code] = length;
  24123. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24124. _length_code[length++] = code;
  24125. }
  24126. }
  24127. //Assert (length == 256, "tr_static_init: length != 256");
  24128. /* Note that the length 255 (match length 258) can be represented
  24129. * in two different ways: code 284 + 5 bits or code 285, so we
  24130. * overwrite length_code[255] to use the best encoding:
  24131. */
  24132. _length_code[length-1] = code;
  24133. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24134. dist = 0;
  24135. for (code = 0 ; code < 16; code++) {
  24136. base_dist[code] = dist;
  24137. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24138. _dist_code[dist++] = code;
  24139. }
  24140. }
  24141. //Assert (dist == 256, "tr_static_init: dist != 256");
  24142. dist >>= 7; /* from now on, all distances are divided by 128 */
  24143. for (; code < D_CODES; code++) {
  24144. base_dist[code] = dist << 7;
  24145. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24146. _dist_code[256 + dist++] = code;
  24147. }
  24148. }
  24149. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24150. /* Construct the codes of the static literal tree */
  24151. for (bits = 0; bits <= MAX_BITS; bits++) {
  24152. bl_count[bits] = 0;
  24153. }
  24154. n = 0;
  24155. while (n <= 143) {
  24156. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24157. n++;
  24158. bl_count[8]++;
  24159. }
  24160. while (n <= 255) {
  24161. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24162. n++;
  24163. bl_count[9]++;
  24164. }
  24165. while (n <= 279) {
  24166. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24167. n++;
  24168. bl_count[7]++;
  24169. }
  24170. while (n <= 287) {
  24171. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24172. n++;
  24173. bl_count[8]++;
  24174. }
  24175. /* Codes 286 and 287 do not exist, but we must include them in the
  24176. * tree construction to get a canonical Huffman tree (longest code
  24177. * all ones)
  24178. */
  24179. gen_codes(static_ltree, L_CODES+1, bl_count);
  24180. /* The static distance tree is trivial: */
  24181. for (n = 0; n < D_CODES; n++) {
  24182. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24183. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24184. }
  24185. // Now data ready and we can init static trees
  24186. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24187. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24188. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24189. //static_init_done = true;
  24190. }
  24191. /* ===========================================================================
  24192. * Initialize a new block.
  24193. */
  24194. function init_block(s) {
  24195. var n; /* iterates over tree elements */
  24196. /* Initialize the trees. */
  24197. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24198. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24199. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24200. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24201. s.opt_len = s.static_len = 0;
  24202. s.last_lit = s.matches = 0;
  24203. }
  24204. /* ===========================================================================
  24205. * Flush the bit buffer and align the output on a byte boundary
  24206. */
  24207. function bi_windup(s)
  24208. {
  24209. if (s.bi_valid > 8) {
  24210. put_short(s, s.bi_buf);
  24211. } else if (s.bi_valid > 0) {
  24212. //put_byte(s, (Byte)s->bi_buf);
  24213. s.pending_buf[s.pending++] = s.bi_buf;
  24214. }
  24215. s.bi_buf = 0;
  24216. s.bi_valid = 0;
  24217. }
  24218. /* ===========================================================================
  24219. * Copy a stored block, storing first the length and its
  24220. * one's complement if requested.
  24221. */
  24222. function copy_block(s, buf, len, header)
  24223. //DeflateState *s;
  24224. //charf *buf; /* the input data */
  24225. //unsigned len; /* its length */
  24226. //int header; /* true if block header must be written */
  24227. {
  24228. bi_windup(s); /* align on byte boundary */
  24229. if (header) {
  24230. put_short(s, len);
  24231. put_short(s, ~len);
  24232. }
  24233. // while (len--) {
  24234. // put_byte(s, *buf++);
  24235. // }
  24236. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24237. s.pending += len;
  24238. }
  24239. /* ===========================================================================
  24240. * Compares to subtrees, using the tree depth as tie breaker when
  24241. * the subtrees have equal frequency. This minimizes the worst case length.
  24242. */
  24243. function smaller(tree, n, m, depth) {
  24244. var _n2 = n*2;
  24245. var _m2 = m*2;
  24246. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24247. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24248. }
  24249. /* ===========================================================================
  24250. * Restore the heap property by moving down the tree starting at node k,
  24251. * exchanging a node with the smallest of its two sons if necessary, stopping
  24252. * when the heap property is re-established (each father smaller than its
  24253. * two sons).
  24254. */
  24255. function pqdownheap(s, tree, k)
  24256. // deflate_state *s;
  24257. // ct_data *tree; /* the tree to restore */
  24258. // int k; /* node to move down */
  24259. {
  24260. var v = s.heap[k];
  24261. var j = k << 1; /* left son of k */
  24262. while (j <= s.heap_len) {
  24263. /* Set j to the smallest of the two sons: */
  24264. if (j < s.heap_len &&
  24265. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24266. j++;
  24267. }
  24268. /* Exit if v is smaller than both sons */
  24269. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24270. /* Exchange v with the smallest son */
  24271. s.heap[k] = s.heap[j];
  24272. k = j;
  24273. /* And continue down the tree, setting j to the left son of k */
  24274. j <<= 1;
  24275. }
  24276. s.heap[k] = v;
  24277. }
  24278. // inlined manually
  24279. // var SMALLEST = 1;
  24280. /* ===========================================================================
  24281. * Send the block data compressed using the given Huffman trees
  24282. */
  24283. function compress_block(s, ltree, dtree)
  24284. // deflate_state *s;
  24285. // const ct_data *ltree; /* literal tree */
  24286. // const ct_data *dtree; /* distance tree */
  24287. {
  24288. var dist; /* distance of matched string */
  24289. var lc; /* match length or unmatched char (if dist == 0) */
  24290. var lx = 0; /* running index in l_buf */
  24291. var code; /* the code to send */
  24292. var extra; /* number of extra bits to send */
  24293. if (s.last_lit !== 0) {
  24294. do {
  24295. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24296. lc = s.pending_buf[s.l_buf + lx];
  24297. lx++;
  24298. if (dist === 0) {
  24299. send_code(s, lc, ltree); /* send a literal byte */
  24300. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24301. } else {
  24302. /* Here, lc is the match length - MIN_MATCH */
  24303. code = _length_code[lc];
  24304. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24305. extra = extra_lbits[code];
  24306. if (extra !== 0) {
  24307. lc -= base_length[code];
  24308. send_bits(s, lc, extra); /* send the extra length bits */
  24309. }
  24310. dist--; /* dist is now the match distance - 1 */
  24311. code = d_code(dist);
  24312. //Assert (code < D_CODES, "bad d_code");
  24313. send_code(s, code, dtree); /* send the distance code */
  24314. extra = extra_dbits[code];
  24315. if (extra !== 0) {
  24316. dist -= base_dist[code];
  24317. send_bits(s, dist, extra); /* send the extra distance bits */
  24318. }
  24319. } /* literal or match pair ? */
  24320. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24321. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24322. // "pendingBuf overflow");
  24323. } while (lx < s.last_lit);
  24324. }
  24325. send_code(s, END_BLOCK, ltree);
  24326. }
  24327. /* ===========================================================================
  24328. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24329. * Update the total bit length for the current block.
  24330. * IN assertion: the field freq is set for all tree elements.
  24331. * OUT assertions: the fields len and code are set to the optimal bit length
  24332. * and corresponding code. The length opt_len is updated; static_len is
  24333. * also updated if stree is not null. The field max_code is set.
  24334. */
  24335. function build_tree(s, desc)
  24336. // deflate_state *s;
  24337. // tree_desc *desc; /* the tree descriptor */
  24338. {
  24339. var tree = desc.dyn_tree;
  24340. var stree = desc.stat_desc.static_tree;
  24341. var has_stree = desc.stat_desc.has_stree;
  24342. var elems = desc.stat_desc.elems;
  24343. var n, m; /* iterate over heap elements */
  24344. var max_code = -1; /* largest code with non zero frequency */
  24345. var node; /* new node being created */
  24346. /* Construct the initial heap, with least frequent element in
  24347. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24348. * heap[0] is not used.
  24349. */
  24350. s.heap_len = 0;
  24351. s.heap_max = HEAP_SIZE;
  24352. for (n = 0; n < elems; n++) {
  24353. if (tree[n * 2]/*.Freq*/ !== 0) {
  24354. s.heap[++s.heap_len] = max_code = n;
  24355. s.depth[n] = 0;
  24356. } else {
  24357. tree[n*2 + 1]/*.Len*/ = 0;
  24358. }
  24359. }
  24360. /* The pkzip format requires that at least one distance code exists,
  24361. * and that at least one bit should be sent even if there is only one
  24362. * possible code. So to avoid special checks later on we force at least
  24363. * two codes of non zero frequency.
  24364. */
  24365. while (s.heap_len < 2) {
  24366. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24367. tree[node * 2]/*.Freq*/ = 1;
  24368. s.depth[node] = 0;
  24369. s.opt_len--;
  24370. if (has_stree) {
  24371. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24372. }
  24373. /* node is 0 or 1 so it does not have extra bits */
  24374. }
  24375. desc.max_code = max_code;
  24376. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24377. * establish sub-heaps of increasing lengths:
  24378. */
  24379. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24380. /* Construct the Huffman tree by repeatedly combining the least two
  24381. * frequent nodes.
  24382. */
  24383. node = elems; /* next internal node of the tree */
  24384. do {
  24385. //pqremove(s, tree, n); /* n = node of least frequency */
  24386. /*** pqremove ***/
  24387. n = s.heap[1/*SMALLEST*/];
  24388. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24389. pqdownheap(s, tree, 1/*SMALLEST*/);
  24390. /***/
  24391. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24392. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24393. s.heap[--s.heap_max] = m;
  24394. /* Create a new node father of n and m */
  24395. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24396. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24397. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24398. /* and insert the new node in the heap */
  24399. s.heap[1/*SMALLEST*/] = node++;
  24400. pqdownheap(s, tree, 1/*SMALLEST*/);
  24401. } while (s.heap_len >= 2);
  24402. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24403. /* At this point, the fields freq and dad are set. We can now
  24404. * generate the bit lengths.
  24405. */
  24406. gen_bitlen(s, desc);
  24407. /* The field len is now set, we can generate the bit codes */
  24408. gen_codes(tree, max_code, s.bl_count);
  24409. }
  24410. /* ===========================================================================
  24411. * Scan a literal or distance tree to determine the frequencies of the codes
  24412. * in the bit length tree.
  24413. */
  24414. function scan_tree(s, tree, max_code)
  24415. // deflate_state *s;
  24416. // ct_data *tree; /* the tree to be scanned */
  24417. // int max_code; /* and its largest code of non zero frequency */
  24418. {
  24419. var n; /* iterates over all tree elements */
  24420. var prevlen = -1; /* last emitted length */
  24421. var curlen; /* length of current code */
  24422. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24423. var count = 0; /* repeat count of the current code */
  24424. var max_count = 7; /* max repeat count */
  24425. var min_count = 4; /* min repeat count */
  24426. if (nextlen === 0) {
  24427. max_count = 138;
  24428. min_count = 3;
  24429. }
  24430. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24431. for (n = 0; n <= max_code; n++) {
  24432. curlen = nextlen;
  24433. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24434. if (++count < max_count && curlen === nextlen) {
  24435. continue;
  24436. } else if (count < min_count) {
  24437. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24438. } else if (curlen !== 0) {
  24439. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24440. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24441. } else if (count <= 10) {
  24442. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24443. } else {
  24444. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24445. }
  24446. count = 0;
  24447. prevlen = curlen;
  24448. if (nextlen === 0) {
  24449. max_count = 138;
  24450. min_count = 3;
  24451. } else if (curlen === nextlen) {
  24452. max_count = 6;
  24453. min_count = 3;
  24454. } else {
  24455. max_count = 7;
  24456. min_count = 4;
  24457. }
  24458. }
  24459. }
  24460. /* ===========================================================================
  24461. * Send a literal or distance tree in compressed form, using the codes in
  24462. * bl_tree.
  24463. */
  24464. function send_tree(s, tree, max_code)
  24465. // deflate_state *s;
  24466. // ct_data *tree; /* the tree to be scanned */
  24467. // int max_code; /* and its largest code of non zero frequency */
  24468. {
  24469. var n; /* iterates over all tree elements */
  24470. var prevlen = -1; /* last emitted length */
  24471. var curlen; /* length of current code */
  24472. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24473. var count = 0; /* repeat count of the current code */
  24474. var max_count = 7; /* max repeat count */
  24475. var min_count = 4; /* min repeat count */
  24476. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24477. if (nextlen === 0) {
  24478. max_count = 138;
  24479. min_count = 3;
  24480. }
  24481. for (n = 0; n <= max_code; n++) {
  24482. curlen = nextlen;
  24483. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24484. if (++count < max_count && curlen === nextlen) {
  24485. continue;
  24486. } else if (count < min_count) {
  24487. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24488. } else if (curlen !== 0) {
  24489. if (curlen !== prevlen) {
  24490. send_code(s, curlen, s.bl_tree);
  24491. count--;
  24492. }
  24493. //Assert(count >= 3 && count <= 6, " 3_6?");
  24494. send_code(s, REP_3_6, s.bl_tree);
  24495. send_bits(s, count-3, 2);
  24496. } else if (count <= 10) {
  24497. send_code(s, REPZ_3_10, s.bl_tree);
  24498. send_bits(s, count-3, 3);
  24499. } else {
  24500. send_code(s, REPZ_11_138, s.bl_tree);
  24501. send_bits(s, count-11, 7);
  24502. }
  24503. count = 0;
  24504. prevlen = curlen;
  24505. if (nextlen === 0) {
  24506. max_count = 138;
  24507. min_count = 3;
  24508. } else if (curlen === nextlen) {
  24509. max_count = 6;
  24510. min_count = 3;
  24511. } else {
  24512. max_count = 7;
  24513. min_count = 4;
  24514. }
  24515. }
  24516. }
  24517. /* ===========================================================================
  24518. * Construct the Huffman tree for the bit lengths and return the index in
  24519. * bl_order of the last bit length code to send.
  24520. */
  24521. function build_bl_tree(s) {
  24522. var max_blindex; /* index of last bit length code of non zero freq */
  24523. /* Determine the bit length frequencies for literal and distance trees */
  24524. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24525. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24526. /* Build the bit length tree: */
  24527. build_tree(s, s.bl_desc);
  24528. /* opt_len now includes the length of the tree representations, except
  24529. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24530. */
  24531. /* Determine the number of bit length codes to send. The pkzip format
  24532. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24533. * 3 but the actual value used is 4.)
  24534. */
  24535. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24536. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24537. break;
  24538. }
  24539. }
  24540. /* Update opt_len to include the bit length tree and counts */
  24541. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24542. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24543. // s->opt_len, s->static_len));
  24544. return max_blindex;
  24545. }
  24546. /* ===========================================================================
  24547. * Send the header for a block using dynamic Huffman trees: the counts, the
  24548. * lengths of the bit length codes, the literal tree and the distance tree.
  24549. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24550. */
  24551. function send_all_trees(s, lcodes, dcodes, blcodes)
  24552. // deflate_state *s;
  24553. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24554. {
  24555. var rank; /* index in bl_order */
  24556. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24557. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24558. // "too many codes");
  24559. //Tracev((stderr, "\nbl counts: "));
  24560. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24561. send_bits(s, dcodes-1, 5);
  24562. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24563. for (rank = 0; rank < blcodes; rank++) {
  24564. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24565. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24566. }
  24567. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24568. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24569. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24570. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24571. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24572. }
  24573. /* ===========================================================================
  24574. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24575. * - TEXT if the two conditions below are satisfied:
  24576. * a) There are no non-portable control characters belonging to the
  24577. * "black list" (0..6, 14..25, 28..31).
  24578. * b) There is at least one printable character belonging to the
  24579. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24580. * - BINARY otherwise.
  24581. * - The following partially-portable control characters form a
  24582. * "gray list" that is ignored in this detection algorithm:
  24583. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24584. * IN assertion: the fields Freq of dyn_ltree are set.
  24585. */
  24586. function detect_data_type(s) {
  24587. /* black_mask is the bit mask of black-listed bytes
  24588. * set bits 0..6, 14..25, and 28..31
  24589. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24590. */
  24591. var black_mask = 0xf3ffc07f;
  24592. var n;
  24593. /* Check for non-textual ("black-listed") bytes. */
  24594. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24595. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24596. return Z_BINARY;
  24597. }
  24598. }
  24599. /* Check for textual ("white-listed") bytes. */
  24600. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24601. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24602. return Z_TEXT;
  24603. }
  24604. for (n = 32; n < LITERALS; n++) {
  24605. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24606. return Z_TEXT;
  24607. }
  24608. }
  24609. /* There are no "black-listed" or "white-listed" bytes:
  24610. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24611. */
  24612. return Z_BINARY;
  24613. }
  24614. var static_init_done = false;
  24615. /* ===========================================================================
  24616. * Initialize the tree data structures for a new zlib stream.
  24617. */
  24618. function _tr_init(s)
  24619. {
  24620. if (!static_init_done) {
  24621. tr_static_init();
  24622. static_init_done = true;
  24623. }
  24624. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24625. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24626. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24627. s.bi_buf = 0;
  24628. s.bi_valid = 0;
  24629. /* Initialize the first block of the first file: */
  24630. init_block(s);
  24631. }
  24632. /* ===========================================================================
  24633. * Send a stored block
  24634. */
  24635. function _tr_stored_block(s, buf, stored_len, last)
  24636. //DeflateState *s;
  24637. //charf *buf; /* input block */
  24638. //ulg stored_len; /* length of input block */
  24639. //int last; /* one if this is the last block for a file */
  24640. {
  24641. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24642. copy_block(s, buf, stored_len, true); /* with header */
  24643. }
  24644. /* ===========================================================================
  24645. * Send one empty static block to give enough lookahead for inflate.
  24646. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24647. */
  24648. function _tr_align(s) {
  24649. send_bits(s, STATIC_TREES<<1, 3);
  24650. send_code(s, END_BLOCK, static_ltree);
  24651. bi_flush(s);
  24652. }
  24653. /* ===========================================================================
  24654. * Determine the best encoding for the current block: dynamic trees, static
  24655. * trees or store, and output the encoded block to the zip file.
  24656. */
  24657. function _tr_flush_block(s, buf, stored_len, last)
  24658. //DeflateState *s;
  24659. //charf *buf; /* input block, or NULL if too old */
  24660. //ulg stored_len; /* length of input block */
  24661. //int last; /* one if this is the last block for a file */
  24662. {
  24663. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24664. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24665. /* Build the Huffman trees unless a stored block is forced */
  24666. if (s.level > 0) {
  24667. /* Check if the file is binary or text */
  24668. if (s.strm.data_type === Z_UNKNOWN) {
  24669. s.strm.data_type = detect_data_type(s);
  24670. }
  24671. /* Construct the literal and distance trees */
  24672. build_tree(s, s.l_desc);
  24673. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24674. // s->static_len));
  24675. build_tree(s, s.d_desc);
  24676. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24677. // s->static_len));
  24678. /* At this point, opt_len and static_len are the total bit lengths of
  24679. * the compressed block data, excluding the tree representations.
  24680. */
  24681. /* Build the bit length tree for the above two trees, and get the index
  24682. * in bl_order of the last bit length code to send.
  24683. */
  24684. max_blindex = build_bl_tree(s);
  24685. /* Determine the best encoding. Compute the block lengths in bytes. */
  24686. opt_lenb = (s.opt_len+3+7) >>> 3;
  24687. static_lenb = (s.static_len+3+7) >>> 3;
  24688. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24689. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24690. // s->last_lit));
  24691. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24692. } else {
  24693. // Assert(buf != (char*)0, "lost buf");
  24694. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24695. }
  24696. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24697. /* 4: two words for the lengths */
  24698. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24699. * Otherwise we can't have processed more than WSIZE input bytes since
  24700. * the last block flush, because compression would have been
  24701. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24702. * transform a block into a stored block.
  24703. */
  24704. _tr_stored_block(s, buf, stored_len, last);
  24705. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24706. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24707. compress_block(s, static_ltree, static_dtree);
  24708. } else {
  24709. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24710. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24711. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24712. }
  24713. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24714. /* The above check is made mod 2^32, for files larger than 512 MB
  24715. * and uLong implemented on 32 bits.
  24716. */
  24717. init_block(s);
  24718. if (last) {
  24719. bi_windup(s);
  24720. }
  24721. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24722. // s->compressed_len-7*last));
  24723. }
  24724. /* ===========================================================================
  24725. * Save the match info and tally the frequency counts. Return true if
  24726. * the current block must be flushed.
  24727. */
  24728. function _tr_tally(s, dist, lc)
  24729. // deflate_state *s;
  24730. // unsigned dist; /* distance of matched string */
  24731. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24732. {
  24733. //var out_length, in_length, dcode;
  24734. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24735. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24736. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24737. s.last_lit++;
  24738. if (dist === 0) {
  24739. /* lc is the unmatched char */
  24740. s.dyn_ltree[lc*2]/*.Freq*/++;
  24741. } else {
  24742. s.matches++;
  24743. /* Here, lc is the match length - MIN_MATCH */
  24744. dist--; /* dist = match distance - 1 */
  24745. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24746. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24747. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24748. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24749. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24750. }
  24751. // (!) This block is disabled in zlib defailts,
  24752. // don't enable it for binary compatibility
  24753. //#ifdef TRUNCATE_BLOCK
  24754. // /* Try to guess if it is profitable to stop the current block here */
  24755. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24756. // /* Compute an upper bound for the compressed length */
  24757. // out_length = s.last_lit*8;
  24758. // in_length = s.strstart - s.block_start;
  24759. //
  24760. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24761. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24762. // }
  24763. // out_length >>>= 3;
  24764. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24765. // // s->last_lit, in_length, out_length,
  24766. // // 100L - out_length*100L/in_length));
  24767. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24768. // return true;
  24769. // }
  24770. // }
  24771. //#endif
  24772. return (s.last_lit === s.lit_bufsize-1);
  24773. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24774. * on 16 bit machines and because stored blocks are restricted to
  24775. * 64K-1 bytes.
  24776. */
  24777. }
  24778. exports._tr_init = _tr_init;
  24779. exports._tr_stored_block = _tr_stored_block;
  24780. exports._tr_flush_block = _tr_flush_block;
  24781. exports._tr_tally = _tr_tally;
  24782. exports._tr_align = _tr_align;
  24783. },{"../utils/common":72}],84:[function(require,module,exports){
  24784. 'use strict';
  24785. function ZStream() {
  24786. /* next input byte */
  24787. this.input = null; // JS specific, because we have no pointers
  24788. this.next_in = 0;
  24789. /* number of bytes available at input */
  24790. this.avail_in = 0;
  24791. /* total number of input bytes read so far */
  24792. this.total_in = 0;
  24793. /* next output byte should be put there */
  24794. this.output = null; // JS specific, because we have no pointers
  24795. this.next_out = 0;
  24796. /* remaining free space at output */
  24797. this.avail_out = 0;
  24798. /* total number of bytes output so far */
  24799. this.total_out = 0;
  24800. /* last error message, NULL if no error */
  24801. this.msg = ''/*Z_NULL*/;
  24802. /* not visible by applications */
  24803. this.state = null;
  24804. /* best guess about the data type: binary or text */
  24805. this.data_type = 2/*Z_UNKNOWN*/;
  24806. /* adler32 value of the uncompressed data */
  24807. this.adler = 0;
  24808. }
  24809. module.exports = ZStream;
  24810. },{}],85:[function(require,module,exports){
  24811. module.exports = require('./lib/retry');
  24812. },{"./lib/retry":86}],86:[function(require,module,exports){
  24813. var RetryOperation = require('./retry_operation');
  24814. exports.operation = function(options) {
  24815. var timeouts = exports.timeouts(options);
  24816. return new RetryOperation(timeouts);
  24817. };
  24818. exports.timeouts = function(options) {
  24819. if (options instanceof Array) {
  24820. return [].concat(options);
  24821. }
  24822. var opts = {
  24823. retries: 10,
  24824. factor: 2,
  24825. minTimeout: 1 * 1000,
  24826. maxTimeout: Infinity,
  24827. randomize: false
  24828. };
  24829. for (var key in options) {
  24830. opts[key] = options[key];
  24831. }
  24832. if (opts.minTimeout > opts.maxTimeout) {
  24833. throw new Error('minTimeout is greater than maxTimeout');
  24834. }
  24835. var timeouts = [];
  24836. for (var i = 0; i < opts.retries; i++) {
  24837. timeouts.push(this._createTimeout(i, opts));
  24838. }
  24839. // sort the array numerically ascending
  24840. timeouts.sort(function(a,b) {
  24841. return a - b;
  24842. });
  24843. return timeouts;
  24844. };
  24845. exports._createTimeout = function(attempt, opts) {
  24846. var random = (opts.randomize)
  24847. ? (Math.random() + 1)
  24848. : 1;
  24849. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  24850. timeout = Math.min(timeout, opts.maxTimeout);
  24851. return timeout;
  24852. };
  24853. },{"./retry_operation":87}],87:[function(require,module,exports){
  24854. function RetryOperation(timeouts) {
  24855. this._timeouts = timeouts;
  24856. this._fn = null;
  24857. this._errors = [];
  24858. this._attempts = 1;
  24859. this._operationTimeout = null;
  24860. this._operationTimeoutCb = null;
  24861. this._timeout = null;
  24862. }
  24863. module.exports = RetryOperation;
  24864. RetryOperation.prototype.retry = function(err) {
  24865. if (this._timeout) {
  24866. clearTimeout(this._timeout);
  24867. }
  24868. if (!err) {
  24869. return false;
  24870. }
  24871. this._errors.push(err);
  24872. var timeout = this._timeouts.shift();
  24873. if (timeout === undefined) {
  24874. return false;
  24875. }
  24876. this._attempts++;
  24877. var self = this;
  24878. setTimeout(function() {
  24879. self._fn(self._attempts);
  24880. if (self._operationTimeoutCb) {
  24881. self._timeout = setTimeout(function() {
  24882. self._operationTimeoutCb(self._attempts);
  24883. }, self._operationTimeout);
  24884. }
  24885. }, timeout);
  24886. return true;
  24887. };
  24888. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  24889. this._fn = fn;
  24890. if (timeoutOps) {
  24891. if (timeoutOps.timeout) {
  24892. this._operationTimeout = timeoutOps.timeout;
  24893. }
  24894. if (timeoutOps.cb) {
  24895. this._operationTimeoutCb = timeoutOps.cb;
  24896. }
  24897. }
  24898. this._fn(this._attempts);
  24899. var self = this;
  24900. if (this._operationTimeoutCb) {
  24901. this._timeout = setTimeout(function() {
  24902. self._operationTimeoutCb();
  24903. }, self._operationTimeout);
  24904. }
  24905. };
  24906. RetryOperation.prototype.try = function(fn) {
  24907. console.log('Using RetryOperation.try() is deprecated');
  24908. this.attempt(fn);
  24909. };
  24910. RetryOperation.prototype.start = function(fn) {
  24911. console.log('Using RetryOperation.start() is deprecated');
  24912. this.attempt(fn);
  24913. };
  24914. RetryOperation.prototype.start = RetryOperation.prototype.try;
  24915. RetryOperation.prototype.errors = function() {
  24916. return this._errors;
  24917. };
  24918. RetryOperation.prototype.attempts = function() {
  24919. return this._attempts;
  24920. };
  24921. RetryOperation.prototype.mainError = function() {
  24922. if (this._errors.length === 0) {
  24923. return null;
  24924. }
  24925. var counts = {};
  24926. var mainError = null;
  24927. var mainErrorCount = 0;
  24928. for (var i = 0; i < this._errors.length; i++) {
  24929. var error = this._errors[i];
  24930. var message = error.message;
  24931. var count = (counts[message] || 0) + 1;
  24932. counts[message] = count;
  24933. if (count >= mainErrorCount) {
  24934. mainError = error;
  24935. mainErrorCount = count;
  24936. }
  24937. }
  24938. return mainError;
  24939. };
  24940. },{}],88:[function(require,module,exports){
  24941. module.exports = function arrayEquals(array) {
  24942. // if the other array is a falsy value, return
  24943. if (!array)
  24944. return false;
  24945. // compare lengths - can save a lot of time
  24946. if (this.length != array.length)
  24947. return false;
  24948. for (var i = 0, l = this.length; i < l; i++) {
  24949. // Check if we have nested arrays
  24950. if (this[i] instanceof Array && array[i] instanceof Array) {
  24951. // recurse into the nested arrays
  24952. if (!arrayEquals.apply(this[i], [array[i]]))
  24953. return false;
  24954. } else if (this[i] != array[i]) {
  24955. // Warning - two different object instances will never be equal:
  24956. // {x:20} != {x:20}
  24957. return false;
  24958. }
  24959. }
  24960. return true;
  24961. }
  24962. },{}],89:[function(require,module,exports){
  24963. exports.Interop = require('./interop');
  24964. },{"./interop":90}],90:[function(require,module,exports){
  24965. "use strict";
  24966. var transform = require('./transform');
  24967. var arrayEquals = require('./array-equals');
  24968. function Interop() {
  24969. /**
  24970. * This map holds the most recent Unified Plan offer/answer SDP that was
  24971. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  24972. * the SDP string as values.
  24973. *
  24974. * @type {{}}
  24975. */
  24976. this.cache = {};
  24977. }
  24978. module.exports = Interop;
  24979. /**
  24980. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  24981. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  24982. * application.
  24983. *
  24984. * @param desc
  24985. * @returns {*}
  24986. */
  24987. Interop.prototype.toPlanB = function(desc) {
  24988. //#region Preliminary input validation.
  24989. if (typeof desc !== 'object' || desc === null ||
  24990. typeof desc.sdp !== 'string') {
  24991. console.warn('An empty description was passed as an argument.');
  24992. return desc;
  24993. }
  24994. // Objectify the SDP for easier manipulation.
  24995. var session = transform.parse(desc.sdp);
  24996. // If the SDP contains no media, there's nothing to transform.
  24997. if (typeof session.media === 'undefined' ||
  24998. !Array.isArray(session.media) || session.media.length === 0) {
  24999. console.warn('The description has no media.');
  25000. return desc;
  25001. }
  25002. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25003. // SDP has a video, an audio and a data "channel" at most.
  25004. if (session.media.length <= 3 && session.media.every(function(m) {
  25005. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25006. })) {
  25007. console.warn('This description does not look like Unified Plan.');
  25008. return desc;
  25009. }
  25010. //#endregion
  25011. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25012. // -> Unified Plan transformation.
  25013. this.cache[desc.type] = desc.sdp;
  25014. //#region Convert from Unified Plan to Plan B.
  25015. // We rebuild the session.media array.
  25016. var media = session.media;
  25017. session.media = [];
  25018. // Associative array that maps channel types to channel objects for fast
  25019. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25020. // obj.
  25021. var type2bl = {};
  25022. // Used to build the group:BUNDLE value after the channels construction
  25023. // loop.
  25024. var types = [];
  25025. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25026. media.forEach(function(unifiedLine) {
  25027. // rtcp-mux is required in the Plan B SDP.
  25028. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25029. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25030. unifiedLine.direction !== 'inactive') {
  25031. throw new Error('Cannot convert to Plan B because m-lines ' +
  25032. 'without the rtcp-mux attribute were found.');
  25033. }
  25034. if (unifiedLine.type === 'application') {
  25035. session.media.push(unifiedLine);
  25036. types.push(unifiedLine.mid);
  25037. return;
  25038. }
  25039. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25040. // as the channel basis.
  25041. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25042. type2bl[unifiedLine.type] = unifiedLine;
  25043. }
  25044. // Add sources to the channel and handle a=msid.
  25045. if (typeof unifiedLine.sources === 'object') {
  25046. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25047. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25048. type2bl[unifiedLine.type].sources = {};
  25049. // Assign the sources to the channel.
  25050. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25051. if (typeof unifiedLine.msid !== 'undefined') {
  25052. // In Plan B the msid is an SSRC attribute. Also, we don't
  25053. // care about the obsolete label and mslabel attributes.
  25054. //
  25055. // Note that it is not guaranteed that the unifiedLine will have
  25056. // an msid. recvonly channels in particular don't have one.
  25057. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25058. }
  25059. // NOTE ssrcs in ssrc groups will share msids, as
  25060. // draft-uberti-rtcweb-plan-00 mandates.
  25061. });
  25062. }
  25063. // Add ssrc groups to the channel.
  25064. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25065. Array.isArray(unifiedLine.ssrcGroups)) {
  25066. // Create the ssrcGroups array, if it's not defined.
  25067. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25068. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25069. type2bl[unifiedLine.type].ssrcGroups = [];
  25070. }
  25071. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25072. }
  25073. if (type2bl[unifiedLine.type] === unifiedLine) {
  25074. // Copy ICE related stuff from the principal media line.
  25075. unifiedLine.candidates = media[0].candidates;
  25076. unifiedLine.iceUfrag = media[0].iceUfrag;
  25077. unifiedLine.icePwd = media[0].icePwd;
  25078. unifiedLine.fingerprint = media[0].fingerprint;
  25079. // Plan B mids are in ['audio', 'video', 'data']
  25080. unifiedLine.mid = unifiedLine.type;
  25081. // Plan B doesn't support/need the bundle-only attribute.
  25082. delete unifiedLine.bundleOnly;
  25083. // In Plan B the msid is an SSRC attribute.
  25084. delete unifiedLine.msid;
  25085. // Used to build the group:BUNDLE value after this loop.
  25086. types.push(unifiedLine.type);
  25087. // Add the channel to the new media array.
  25088. session.media.push(unifiedLine);
  25089. }
  25090. });
  25091. // We regenerate the BUNDLE group with the new mids.
  25092. session.groups.some(function(group) {
  25093. if (group.type === 'BUNDLE') {
  25094. group.mids = types.join(' ');
  25095. return true;
  25096. }
  25097. });
  25098. // msid semantic
  25099. session.msidSemantic = {
  25100. semantic: 'WMS',
  25101. token: '*'
  25102. };
  25103. var resStr = transform.write(session);
  25104. return new RTCSessionDescription({
  25105. type: desc.type,
  25106. sdp: resStr
  25107. });
  25108. //#endregion
  25109. };
  25110. /**
  25111. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25112. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25113. * to FF.
  25114. *
  25115. * @param desc
  25116. * @returns {*}
  25117. */
  25118. Interop.prototype.toUnifiedPlan = function(desc) {
  25119. //#region Preliminary input validation.
  25120. if (typeof desc !== 'object' || desc === null ||
  25121. typeof desc.sdp !== 'string') {
  25122. console.warn('An empty description was passed as an argument.');
  25123. return desc;
  25124. }
  25125. var session = transform.parse(desc.sdp);
  25126. // If the SDP contains no media, there's nothing to transform.
  25127. if (typeof session.media === 'undefined' ||
  25128. !Array.isArray(session.media) || session.media.length === 0) {
  25129. console.warn('The description has no media.');
  25130. return desc;
  25131. }
  25132. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25133. // a video, an audio and a data "channel" at most.
  25134. if (session.media.length > 3 || !session.media.every(function(m) {
  25135. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25136. })) {
  25137. console.warn('This description does not look like Plan B.');
  25138. return desc;
  25139. }
  25140. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25141. var mids = [];
  25142. session.media.forEach(function(m) {
  25143. mids.push(m.mid);
  25144. });
  25145. var hasBundle = false;
  25146. if (typeof session.groups !== 'undefined' &&
  25147. Array.isArray(session.groups)) {
  25148. hasBundle = session.groups.every(function(g) {
  25149. return g.type !== 'BUNDLE' ||
  25150. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25151. });
  25152. }
  25153. if (!hasBundle) {
  25154. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25155. " are not bundled were found.");
  25156. }
  25157. //#endregion
  25158. //#region Convert from Plan B to Unified Plan.
  25159. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25160. // rebuild an equivalent Unified Plan offer/answer.
  25161. //
  25162. // For example, if this is a local answer (in Unified Plan style) that we
  25163. // convert to Plan B prior to handing it over to the application (the
  25164. // PeerConnection wrapper called us, for instance, after a successful
  25165. // createAnswer), we want to remember the m-line at which we've seen the
  25166. // (local) SSRC. That's because when the application wants to do call the
  25167. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25168. // Unified Plan), we need to know to which m-line to assign the (local)
  25169. // SSRC. We also need to know all the other m-lines that the original
  25170. // answer had and include them in the transformed answer as well.
  25171. //
  25172. // Another example is if this is a remote offer that we convert to Plan B
  25173. // prior to giving it to the application, we want to remember the mid at
  25174. // which we've seen the (remote) SSRC.
  25175. //
  25176. // In the iteration that follows, we use the cached Unified Plan (if it
  25177. // exists) to assign mids to ssrcs.
  25178. var cached;
  25179. if (typeof this.cache[desc.type] !== 'undefined') {
  25180. cached = transform.parse(this.cache[desc.type]);
  25181. }
  25182. // A helper map that sends mids to m-line objects. We use it later to
  25183. // rebuild the Unified Plan style session.media array.
  25184. var mid2ul = {};
  25185. session.media.forEach(function(bLine) {
  25186. if ((typeof bLine.rtcpMux !== 'string' ||
  25187. bLine.rtcpMux !== 'rtcp-mux') &&
  25188. bLine.direction !== 'inactive') {
  25189. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25190. "without the rtcp-mux attribute were found.");
  25191. }
  25192. if (bLine.type === 'application') {
  25193. mid2ul[bLine.mid] = bLine;
  25194. return;
  25195. }
  25196. // With rtcp-mux and bundle all the channels should have the same ICE
  25197. // stuff.
  25198. var sources = bLine.sources;
  25199. var ssrcGroups = bLine.ssrcGroups;
  25200. var candidates = bLine.candidates;
  25201. var iceUfrag = bLine.iceUfrag;
  25202. var icePwd = bLine.icePwd;
  25203. var fingerprint = bLine.fingerprint;
  25204. var port = bLine.port;
  25205. // We'll use the "bLine" object as a prototype for each new "mLine"
  25206. // that we create, but first we need to clean it up a bit.
  25207. delete bLine.sources;
  25208. delete bLine.ssrcGroups;
  25209. delete bLine.candidates;
  25210. delete bLine.iceUfrag;
  25211. delete bLine.icePwd;
  25212. delete bLine.fingerprint;
  25213. delete bLine.port;
  25214. delete bLine.mid;
  25215. // inverted ssrc group map
  25216. var ssrc2group = {};
  25217. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25218. ssrcGroups.forEach(function (ssrcGroup) {
  25219. // TODO(gp) find out how to receive simulcast with FF. For the
  25220. // time being, hide it.
  25221. if (ssrcGroup.semantics === 'SIM') {
  25222. return;
  25223. }
  25224. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25225. Array.isArray(ssrcGroup.ssrcs)) {
  25226. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25227. if (typeof ssrc2group[ssrc] === 'undefined') {
  25228. ssrc2group[ssrc] = [];
  25229. }
  25230. ssrc2group[ssrc].push(ssrcGroup);
  25231. });
  25232. }
  25233. });
  25234. }
  25235. // ssrc to m-line index.
  25236. var ssrc2ml = {};
  25237. if (typeof sources === 'object') {
  25238. // Explode the Plan B channel sources with one m-line per source.
  25239. Object.keys(sources).forEach(function(ssrc) {
  25240. // The (unified) m-line for this SSRC. We either create it from
  25241. // scratch or, if it's a grouped SSRC, we re-use a related
  25242. // mline. In other words, if the source is grouped with another
  25243. // source, put the two together in the same m-line.
  25244. var unifiedLine;
  25245. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25246. Array.isArray(ssrc2group[ssrc])) {
  25247. ssrc2group[ssrc].some(function (ssrcGroup) {
  25248. // ssrcGroup.ssrcs *is* an Array, no need to check
  25249. // again here.
  25250. return ssrcGroup.ssrcs.some(function (related) {
  25251. if (typeof ssrc2ml[related] === 'object') {
  25252. unifiedLine = ssrc2ml[related];
  25253. return true;
  25254. }
  25255. });
  25256. });
  25257. }
  25258. if (typeof unifiedLine === 'object') {
  25259. // the m-line already exists. Just add the source.
  25260. unifiedLine.sources[ssrc] = sources[ssrc];
  25261. delete sources[ssrc].msid;
  25262. } else {
  25263. // Use the "bLine" as a prototype for the "unifiedLine".
  25264. unifiedLine = Object.create(bLine);
  25265. ssrc2ml[ssrc] = unifiedLine;
  25266. if (typeof sources[ssrc].msid !== 'undefined') {
  25267. // Assign the msid of the source to the m-line. Note
  25268. // that it is not guaranteed that the source will have
  25269. // msid. In particular "recvonly" sources don't have an
  25270. // msid. Note that "recvonly" is a term only defined
  25271. // for m-lines.
  25272. unifiedLine.msid = sources[ssrc].msid;
  25273. delete sources[ssrc].msid;
  25274. }
  25275. // We assign one SSRC per media line.
  25276. unifiedLine.sources = {};
  25277. unifiedLine.sources[ssrc] = sources[ssrc];
  25278. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25279. // Use the cached Unified Plan SDP (if it exists) to assign
  25280. // SSRCs to mids.
  25281. if (typeof cached !== 'undefined' &&
  25282. typeof cached.media !== 'undefined' &&
  25283. Array.isArray(cached.media)) {
  25284. cached.media.forEach(function (m) {
  25285. if (typeof m.sources === 'object') {
  25286. Object.keys(m.sources).forEach(function (s) {
  25287. if (s === ssrc) {
  25288. unifiedLine.mid = m.mid;
  25289. }
  25290. });
  25291. }
  25292. });
  25293. }
  25294. if (typeof unifiedLine.mid === 'undefined') {
  25295. // If this is an SSRC that we see for the first time
  25296. // assign it a new mid. This is typically the case when
  25297. // this method is called to transform a remote
  25298. // description for the first time or when there is a
  25299. // new SSRC in the remote description because a new
  25300. // peer has joined the conference. Local SSRCs should
  25301. // have already been added to the map in the toPlanB
  25302. // method.
  25303. //
  25304. // Because FF generates answers in Unified Plan style,
  25305. // we MUST already have a cached answer with all the
  25306. // local SSRCs mapped to some m-line/mid.
  25307. if (desc.type === 'answer') {
  25308. throw new Error("An unmapped SSRC was found.");
  25309. }
  25310. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25311. }
  25312. // Include the candidates in the 1st media line.
  25313. unifiedLine.candidates = candidates;
  25314. unifiedLine.iceUfrag = iceUfrag;
  25315. unifiedLine.icePwd = icePwd;
  25316. unifiedLine.fingerprint = fingerprint;
  25317. unifiedLine.port = port;
  25318. mid2ul[unifiedLine.mid] = unifiedLine;
  25319. }
  25320. });
  25321. }
  25322. });
  25323. // Rebuild the media array in the right order and add the missing mLines
  25324. // (missing from the Plan B SDP).
  25325. session.media = [];
  25326. mids = []; // reuse
  25327. if (desc.type === 'answer') {
  25328. // The media lines in the answer must match the media lines in the
  25329. // offer. The order is important too. Here we assume that Firefox is the
  25330. // answerer, so we merely have to use the reconstructed (unified) answer
  25331. // to update the cached (unified) answer accordingly.
  25332. //
  25333. // In the general case, one would have to use the cached (unified) offer
  25334. // to find the m-lines that are missing from the reconstructed answer,
  25335. // potentially grabbing them from the cached (unified) answer. One has
  25336. // to be carefull with this approach because inactive m-lines do not
  25337. // always have an mid, making it tricky (impossible?) to find where
  25338. // exactly and which m-lines are missing from the reconstructed answer.
  25339. for (var i = 0; i < cached.media.length; i++) {
  25340. var unifiedLine = cached.media[i];
  25341. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25342. // The mid isn't in the reconstructed (unified) answer.
  25343. // This is either a (unified) m-line containing a remote
  25344. // track only, or a (unified) m-line containing a remote
  25345. // track and a local track that has been removed.
  25346. // In either case, it MUST exist in the cached
  25347. // (unified) answer.
  25348. //
  25349. // In case this is a removed local track, clean-up
  25350. // the (unified) m-line and make sure it's 'recvonly' or
  25351. // 'inactive'.
  25352. delete unifiedLine.msid;
  25353. delete unifiedLine.sources;
  25354. delete unifiedLine.ssrcGroups;
  25355. if (!unifiedLine.direction
  25356. || unifiedLine.direction === 'sendrecv')
  25357. unifiedLine.direction = 'recvonly';
  25358. if (!unifiedLine.direction
  25359. || unifiedLine.direction === 'sendonly')
  25360. unifiedLine.direction = 'inactive';
  25361. } else {
  25362. // This is an (unified) m-line/channel that contains a local
  25363. // track (sendrecv or sendonly channel) or it's a unified
  25364. // recvonly m-line/channel. In either case, since we're
  25365. // going from PlanB -> Unified Plan this m-line MUST
  25366. // exist in the cached answer.
  25367. }
  25368. session.media.push(unifiedLine);
  25369. if (typeof unifiedLine.mid === 'string') {
  25370. // inactive lines don't/may not have an mid.
  25371. mids.push(unifiedLine.mid);
  25372. }
  25373. }
  25374. } else {
  25375. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25376. // under any circumstances. If we are no longer interested in sending a
  25377. // track, we just remove the msid and ssrc attributes and set it to
  25378. // either a=recvonly (as the reofferer, we must use recvonly if the
  25379. // other side was previously sending on the m-section, but we can also
  25380. // leave the possibility open if it wasn't previously in use), or
  25381. // a=inacive.
  25382. if (typeof cached !== 'undefined' &&
  25383. typeof cached.media !== 'undefined' &&
  25384. Array.isArray(cached.media)) {
  25385. cached.media.forEach(function(unifiedLine) {
  25386. mids.push(unifiedLine.mid);
  25387. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25388. session.media.push(mid2ul[unifiedLine.mid]);
  25389. } else {
  25390. delete unifiedLine.msid;
  25391. delete unifiedLine.sources;
  25392. delete unifiedLine.ssrcGroups;
  25393. if (!unifiedLine.direction
  25394. || unifiedLine.direction === 'sendrecv')
  25395. unifiedLine.direction = 'recvonly';
  25396. if (!unifiedLine.direction
  25397. || unifiedLine.direction === 'sendonly')
  25398. unifiedLine.direction = 'inactive';
  25399. session.media.push(unifiedLine);
  25400. }
  25401. });
  25402. }
  25403. // Add all the remaining (new) m-lines of the transformed SDP.
  25404. Object.keys(mid2ul).forEach(function(mid) {
  25405. if (mids.indexOf(mid) === -1) {
  25406. mids.push(mid);
  25407. if (typeof mid2ul[mid].direction === 'recvonly') {
  25408. // This is a remote recvonly channel. Add its SSRC to the
  25409. // appropriate sendrecv or sendonly channel.
  25410. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25411. session.media.some(function (unifiedLine) {
  25412. if ((unifiedLine.direction === 'sendrecv' ||
  25413. unifiedLine.direction === 'sendonly') &&
  25414. unifiedLine.type === mid2ul[mid].type) {
  25415. // mid2ul[mid] shouldn't have any ssrc-groups
  25416. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25417. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25418. });
  25419. return true;
  25420. }
  25421. });
  25422. } else {
  25423. session.media.push(mid2ul[mid]);
  25424. }
  25425. }
  25426. });
  25427. }
  25428. // We regenerate the BUNDLE group (since we regenerated the mids)
  25429. session.groups.some(function(group) {
  25430. if (group.type === 'BUNDLE') {
  25431. group.mids = mids.join(' ');
  25432. return true;
  25433. }
  25434. });
  25435. // msid semantic
  25436. session.msidSemantic = {
  25437. semantic: 'WMS',
  25438. token: '*'
  25439. };
  25440. var resStr = transform.write(session);
  25441. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25442. // function.
  25443. this.cache[desc.type] = resStr;
  25444. return new RTCSessionDescription({
  25445. type: desc.type,
  25446. sdp: resStr
  25447. });
  25448. //#endregion
  25449. };
  25450. },{"./array-equals":88,"./transform":91}],91:[function(require,module,exports){
  25451. var transform = require('sdp-transform');
  25452. exports.write = function(session, opts) {
  25453. if (typeof session !== 'undefined' &&
  25454. typeof session.media !== 'undefined' &&
  25455. Array.isArray(session.media)) {
  25456. session.media.forEach(function (mLine) {
  25457. // expand sources to ssrcs
  25458. if (typeof mLine.sources !== 'undefined' &&
  25459. Object.keys(mLine.sources).length !== 0) {
  25460. mLine.ssrcs = [];
  25461. Object.keys(mLine.sources).forEach(function (ssrc) {
  25462. var source = mLine.sources[ssrc];
  25463. Object.keys(source).forEach(function (attribute) {
  25464. mLine.ssrcs.push({
  25465. id: ssrc,
  25466. attribute: attribute,
  25467. value: source[attribute]
  25468. });
  25469. });
  25470. });
  25471. delete mLine.sources;
  25472. }
  25473. // join ssrcs in ssrc groups
  25474. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25475. Array.isArray(mLine.ssrcGroups)) {
  25476. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25477. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25478. Array.isArray(ssrcGroup.ssrcs)) {
  25479. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25480. }
  25481. });
  25482. }
  25483. });
  25484. }
  25485. // join group mids
  25486. if (typeof session !== 'undefined' &&
  25487. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25488. session.groups.forEach(function (g) {
  25489. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25490. g.mids = g.mids.join(' ');
  25491. }
  25492. });
  25493. }
  25494. return transform.write(session, opts);
  25495. };
  25496. exports.parse = function(sdp) {
  25497. var session = transform.parse(sdp);
  25498. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25499. Array.isArray(session.media)) {
  25500. session.media.forEach(function (mLine) {
  25501. // group sources attributes by ssrc
  25502. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25503. mLine.sources = {};
  25504. mLine.ssrcs.forEach(function (ssrc) {
  25505. if (!mLine.sources[ssrc.id])
  25506. mLine.sources[ssrc.id] = {};
  25507. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25508. });
  25509. delete mLine.ssrcs;
  25510. }
  25511. // split ssrcs in ssrc groups
  25512. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25513. Array.isArray(mLine.ssrcGroups)) {
  25514. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25515. if (typeof ssrcGroup.ssrcs === 'string') {
  25516. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25517. }
  25518. });
  25519. }
  25520. });
  25521. }
  25522. // split group mids
  25523. if (typeof session !== 'undefined' &&
  25524. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25525. session.groups.forEach(function (g) {
  25526. if (typeof g.mids === 'string') {
  25527. g.mids = g.mids.split(' ');
  25528. }
  25529. });
  25530. }
  25531. return session;
  25532. };
  25533. },{"sdp-transform":95}],92:[function(require,module,exports){
  25534. var transform = require('sdp-transform');
  25535. var transformUtils = require('./transform-utils');
  25536. var parseSsrcs = transformUtils.parseSsrcs;
  25537. var writeSsrcs = transformUtils.writeSsrcs;
  25538. //region Constants
  25539. var DEFAULT_NUM_OF_LAYERS = 3;
  25540. //endregion
  25541. //region Ctor
  25542. function Simulcast(options) {
  25543. this.options = options ? options : {};
  25544. if (!this.options.numOfLayers) {
  25545. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  25546. }
  25547. this.layers = [];
  25548. }
  25549. //endregion
  25550. //region Stateless private utility functions
  25551. /**
  25552. * Returns a random integer between min (included) and max (excluded)
  25553. * Using Math.round() gives a non-uniform distribution!
  25554. * @returns {number}
  25555. */
  25556. function generateSSRC() {
  25557. var min = 0, max = 0xffffffff;
  25558. return Math.floor(Math.random() * (max - min)) + min;
  25559. };
  25560. function processVideo(session, action) {
  25561. if (session == null || !Array.isArray(session.media)) {
  25562. return;
  25563. }
  25564. session.media.forEach(function (mLine) {
  25565. if (mLine.type === 'video') {
  25566. action(mLine);
  25567. }
  25568. });
  25569. }
  25570. function validateDescription(desc)
  25571. {
  25572. return desc && desc != null
  25573. && desc.type && desc.type != ''
  25574. && desc.sdp && desc.sdp != '';
  25575. }
  25576. function explodeRemoteSimulcast(mLine) {
  25577. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25578. return;
  25579. }
  25580. var sources = parseSsrcs(mLine);
  25581. var order = [];
  25582. // Find the SIM group and explode its sources.
  25583. var j = mLine.ssrcGroups.length;
  25584. while (j--) {
  25585. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  25586. continue;
  25587. }
  25588. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  25589. for (var i = 0; i < simulcastSsrcs.length; i++) {
  25590. var ssrc = simulcastSsrcs[i];
  25591. order.push(ssrc);
  25592. var parts = sources[ssrc].msid.split(' ');
  25593. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  25594. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  25595. // Remove all the groups that this SSRC participates in.
  25596. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25597. if (relatedGroup.semantics === 'SIM') {
  25598. return;
  25599. }
  25600. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25601. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25602. return;
  25603. }
  25604. // Nuke all the related SSRCs.
  25605. relatedSsrcs.forEach(function (relatedSSRC) {
  25606. sources[relatedSSRC].msid = sources[ssrc].msid;
  25607. sources[relatedSSRC].cname = sources[ssrc].cname;
  25608. if (relatedSSRC !== ssrc) {
  25609. order.push(relatedSSRC);
  25610. }
  25611. });
  25612. // Schedule the related group for nuking.
  25613. })
  25614. }
  25615. mLine.ssrcs = writeSsrcs(sources, order);
  25616. mLine.ssrcGroups.splice(j, 1);
  25617. };
  25618. }
  25619. function squeezeRemoteSimulcast(mLine) {
  25620. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25621. return;
  25622. }
  25623. var sources = parseSsrcs(mLine);
  25624. // Find the SIM group and nuke it.
  25625. mLine.ssrcGroups.some(function (simulcastGroup) {
  25626. if (simulcastGroup.semantics !== 'SIM') {
  25627. return false;
  25628. }
  25629. // Schedule the SIM group for nuking.
  25630. simulcastGroup.nuke = true;
  25631. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  25632. // Nuke all the higher layer SSRCs.
  25633. for (var i = 1; i < simulcastSsrcs.length; i++) {
  25634. var ssrc = simulcastSsrcs[i];
  25635. delete sources[ssrc];
  25636. // Remove all the groups that this SSRC participates in.
  25637. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25638. if (relatedGroup.semantics === 'SIM') {
  25639. return;
  25640. }
  25641. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25642. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25643. return;
  25644. }
  25645. // Nuke all the related SSRCs.
  25646. relatedSsrcs.forEach(function (relatedSSRC) {
  25647. delete sources[relatedSSRC];
  25648. });
  25649. // Schedule the related group for nuking.
  25650. relatedGroup.nuke = true;
  25651. })
  25652. }
  25653. return true;
  25654. });
  25655. mLine.ssrcs = writeSsrcs(sources);
  25656. // Nuke all the scheduled groups.
  25657. var i = mLine.ssrcGroups.length;
  25658. while (i--) {
  25659. if (mLine.ssrcGroups[i].nuke) {
  25660. mLine.ssrcGroups.splice(i, 1);
  25661. }
  25662. }
  25663. }
  25664. function removeGoogConference(mLine) {
  25665. if (!mLine || !Array.isArray(mLine.invalid)) {
  25666. return;
  25667. }
  25668. var i = mLine.invalid.length;
  25669. while (i--) {
  25670. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  25671. mLine.invalid.splice(i, 1);
  25672. }
  25673. }
  25674. }
  25675. function assertGoogConference(mLine) {
  25676. if (!mLine) {
  25677. return;
  25678. }
  25679. if (!Array.isArray(mLine.invalid)) {
  25680. mLine.invalid = [];
  25681. }
  25682. if (!mLine.invalid.some(
  25683. function (i) { return i.value === 'x-google-flag:conference' })) {
  25684. mLine.invalid.push({'value': 'x-google-flag:conference'});
  25685. }
  25686. }
  25687. //endregion
  25688. //region "Private" functions
  25689. /**
  25690. *
  25691. * @param mLine
  25692. * @private
  25693. */
  25694. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  25695. if (!mLine || mLine.type !== 'video') {
  25696. return;
  25697. }
  25698. var sources = parseSsrcs(mLine);
  25699. if (Object.keys(sources).length === 0) {
  25700. // no sources, disable simulcast.
  25701. if (this.layers.length !== 0) {
  25702. this.layers = [];
  25703. }
  25704. return;
  25705. }
  25706. // find the base layer (we'll reuse its msid and cname).
  25707. var baseLayerSSRC = Object.keys(sources)[0];
  25708. var baseLayer = sources[baseLayerSSRC];
  25709. // todo(gp) handle screen sharing.
  25710. // check if base CNAME has changed and reinitialise layers.
  25711. if (this.layers.length > 0
  25712. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  25713. this.layers = [];
  25714. }
  25715. // (re)initialise layers
  25716. if (this.layers.length < 1) {
  25717. // first push the base layer.
  25718. this.layers.push({
  25719. ssrc: baseLayerSSRC,
  25720. msid: baseLayer.msid,
  25721. cname: baseLayer.cname
  25722. });
  25723. var rtx = false; // RFC 4588
  25724. if (Array.isArray(mLine.rtp)) {
  25725. rtx = mLine.rtp.some(
  25726. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  25727. }
  25728. if (rtx) {
  25729. this.layers[0].rtx = generateSSRC();
  25730. }
  25731. // now push additional layers.
  25732. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  25733. var layer = { ssrc: generateSSRC() };
  25734. if (rtx) {
  25735. layer.rtx = generateSSRC();
  25736. }
  25737. this.layers.push(layer);
  25738. }
  25739. }
  25740. };
  25741. /**
  25742. *
  25743. * @param mLine
  25744. * @private
  25745. */
  25746. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  25747. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  25748. var sources = {};
  25749. var msid = this.layers[0].msid;
  25750. var cname = this.layers[0].cname;
  25751. var simulcastSsrcs = [];
  25752. var ssrcGroups = [];
  25753. for (var i = 0; i < this.layers.length; i++) {
  25754. var layer = this.layers[i];
  25755. sources[layer.ssrc] = { msid: msid, cname: cname };
  25756. simulcastSsrcs.push(layer.ssrc);
  25757. if (layer.rtx) {
  25758. sources[layer.rtx] = {
  25759. msid: msid,
  25760. cname: cname
  25761. }
  25762. ssrcGroups.push({
  25763. semantics: 'FID',
  25764. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  25765. });
  25766. }
  25767. }
  25768. ssrcGroups.push({
  25769. semantics: 'SIM',
  25770. ssrcs: simulcastSsrcs.join(' ')
  25771. });
  25772. mLine.ssrcGroups = ssrcGroups;
  25773. mLine.ssrcs = writeSsrcs(sources);
  25774. }
  25775. }
  25776. //endregion
  25777. //region "Public" functions
  25778. Simulcast.prototype.isSupported = function () {
  25779. return window.chrome;
  25780. // TODO this needs improvements. For example I doubt that Chrome in Android
  25781. // has simulcast support. Also, only recent versions of Chromium have native
  25782. // simulcast support.
  25783. }
  25784. /**
  25785. *
  25786. * @param desc
  25787. * @returns {RTCSessionDescription}
  25788. */
  25789. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  25790. if (!validateDescription(desc)) {
  25791. return desc;
  25792. }
  25793. var session = transform.parse(desc.sdp);
  25794. var self = this;
  25795. processVideo(session, function (mLine) {
  25796. // Handle simulcast reception.
  25797. if (self.options.explodeRemoteSimulcast) {
  25798. explodeRemoteSimulcast(mLine);
  25799. } else {
  25800. squeezeRemoteSimulcast(mLine);
  25801. }
  25802. // If native simulcast is enabled, we must append the x-goog-conference
  25803. // attribute to the SDP.
  25804. if (self.layers.length < 1) {
  25805. removeGoogConference(mLine);
  25806. } else {
  25807. assertGoogConference(mLine);
  25808. }
  25809. });
  25810. return new RTCSessionDescription({
  25811. type: desc.type,
  25812. sdp: transform.write(session)
  25813. });
  25814. };
  25815. /**
  25816. *
  25817. * @param desc
  25818. * @returns {RTCSessionDescription}
  25819. */
  25820. Simulcast.prototype.mungeLocalDescription = function (desc) {
  25821. if (!validateDescription(desc) || !this.isSupported()) {
  25822. return desc;
  25823. }
  25824. var session = transform.parse(desc.sdp);
  25825. var self = this;
  25826. processVideo(session, function (mLine) {
  25827. // Initialize native simulcast layers, if not already done.
  25828. self._maybeInitializeLayers(mLine);
  25829. // Update the SDP with the simulcast layers.
  25830. self._restoreSimulcastView(mLine);
  25831. });
  25832. return new RTCSessionDescription({
  25833. type: desc.type,
  25834. sdp: transform.write(session)
  25835. });
  25836. };
  25837. //endregion
  25838. module.exports = Simulcast;
  25839. },{"./transform-utils":93,"sdp-transform":95}],93:[function(require,module,exports){
  25840. exports.writeSsrcs = function(sources, order) {
  25841. var ssrcs = [];
  25842. // expand sources to ssrcs
  25843. if (typeof sources !== 'undefined' &&
  25844. Object.keys(sources).length !== 0) {
  25845. if (Array.isArray(order)) {
  25846. for (var i = 0; i < order.length; i++) {
  25847. var ssrc = order[i];
  25848. var source = sources[ssrc];
  25849. Object.keys(source).forEach(function (attribute) {
  25850. ssrcs.push({
  25851. id: ssrc,
  25852. attribute: attribute,
  25853. value: source[attribute]
  25854. });
  25855. });
  25856. }
  25857. } else {
  25858. Object.keys(sources).forEach(function (ssrc) {
  25859. var source = sources[ssrc];
  25860. Object.keys(source).forEach(function (attribute) {
  25861. ssrcs.push({
  25862. id: ssrc,
  25863. attribute: attribute,
  25864. value: source[attribute]
  25865. });
  25866. });
  25867. });
  25868. }
  25869. }
  25870. return ssrcs;
  25871. };
  25872. exports.parseSsrcs = function (mLine) {
  25873. var sources = {};
  25874. // group sources attributes by ssrc.
  25875. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25876. mLine.ssrcs.forEach(function (ssrc) {
  25877. if (!sources[ssrc.id])
  25878. sources[ssrc.id] = {};
  25879. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25880. });
  25881. }
  25882. return sources;
  25883. };
  25884. },{}],94:[function(require,module,exports){
  25885. var grammar = module.exports = {
  25886. v: [{
  25887. name: 'version',
  25888. reg: /^(\d*)$/
  25889. }],
  25890. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25891. // NB: sessionId will be a String in most cases because it is huge
  25892. name: 'origin',
  25893. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25894. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25895. format: "%s %s %d %s IP%d %s"
  25896. }],
  25897. // default parsing of these only (though some of these feel outdated)
  25898. s: [{ name: 'name' }],
  25899. i: [{ name: 'description' }],
  25900. u: [{ name: 'uri' }],
  25901. e: [{ name: 'email' }],
  25902. p: [{ name: 'phone' }],
  25903. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25904. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25905. //k: [{}], // outdated thing ignored
  25906. t: [{ //t=0 0
  25907. name: 'timing',
  25908. reg: /^(\d*) (\d*)/,
  25909. names: ['start', 'stop'],
  25910. format: "%d %d"
  25911. }],
  25912. c: [{ //c=IN IP4 10.47.197.26
  25913. name: 'connection',
  25914. reg: /^IN IP(\d) (\S*)/,
  25915. names: ['version', 'ip'],
  25916. format: "IN IP%d %s"
  25917. }],
  25918. b: [{ //b=AS:4000
  25919. push: 'bandwidth',
  25920. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25921. names: ['type', 'limit'],
  25922. format: "%s:%s"
  25923. }],
  25924. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25925. // NB: special - pushes to session
  25926. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25927. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25928. names: ['type', 'port', 'protocol', 'payloads'],
  25929. format: "%s %d %s %s"
  25930. }],
  25931. a: [
  25932. { //a=rtpmap:110 opus/48000/2
  25933. push: 'rtp',
  25934. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25935. names: ['payload', 'codec', 'rate', 'encoding'],
  25936. format: function (o) {
  25937. return (o.encoding) ?
  25938. "rtpmap:%d %s/%s/%s":
  25939. "rtpmap:%d %s/%s";
  25940. }
  25941. },
  25942. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25943. push: 'fmtp',
  25944. reg: /^fmtp:(\d*) (\S*)/,
  25945. names: ['payload', 'config'],
  25946. format: "fmtp:%d %s"
  25947. },
  25948. { //a=control:streamid=0
  25949. name: 'control',
  25950. reg: /^control:(.*)/,
  25951. format: "control:%s"
  25952. },
  25953. { //a=rtcp:65179 IN IP4 193.84.77.194
  25954. name: 'rtcp',
  25955. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25956. names: ['port', 'netType', 'ipVer', 'address'],
  25957. format: function (o) {
  25958. return (o.address != null) ?
  25959. "rtcp:%d %s IP%d %s":
  25960. "rtcp:%d";
  25961. }
  25962. },
  25963. { //a=rtcp-fb:98 trr-int 100
  25964. push: 'rtcpFbTrrInt',
  25965. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25966. names: ['payload', 'value'],
  25967. format: "rtcp-fb:%d trr-int %d"
  25968. },
  25969. { //a=rtcp-fb:98 nack rpsi
  25970. push: 'rtcpFb',
  25971. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25972. names: ['payload', 'type', 'subtype'],
  25973. format: function (o) {
  25974. return (o.subtype != null) ?
  25975. "rtcp-fb:%s %s %s":
  25976. "rtcp-fb:%s %s";
  25977. }
  25978. },
  25979. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25980. //a=extmap:1/recvonly URI-gps-string
  25981. push: 'ext',
  25982. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25983. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25984. format: function (o) {
  25985. return (o.config != null) ?
  25986. "extmap:%s %s %s":
  25987. "extmap:%s %s";
  25988. }
  25989. },
  25990. {
  25991. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25992. push: 'crypto',
  25993. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25994. names: ['id', 'suite', 'config', 'sessionConfig'],
  25995. format: function (o) {
  25996. return (o.sessionConfig != null) ?
  25997. "crypto:%d %s %s %s":
  25998. "crypto:%d %s %s";
  25999. }
  26000. },
  26001. { //a=setup:actpass
  26002. name: 'setup',
  26003. reg: /^setup:(\w*)/,
  26004. format: "setup:%s"
  26005. },
  26006. { //a=mid:1
  26007. name: 'mid',
  26008. reg: /^mid:([^\s]*)/,
  26009. format: "mid:%s"
  26010. },
  26011. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26012. name: 'msid',
  26013. reg: /^msid:(.*)/,
  26014. format: "msid:%s"
  26015. },
  26016. { //a=ptime:20
  26017. name: 'ptime',
  26018. reg: /^ptime:(\d*)/,
  26019. format: "ptime:%d"
  26020. },
  26021. { //a=maxptime:60
  26022. name: 'maxptime',
  26023. reg: /^maxptime:(\d*)/,
  26024. format: "maxptime:%d"
  26025. },
  26026. { //a=sendrecv
  26027. name: 'direction',
  26028. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26029. },
  26030. { //a=ice-lite
  26031. name: 'icelite',
  26032. reg: /^(ice-lite)/
  26033. },
  26034. { //a=ice-ufrag:F7gI
  26035. name: 'iceUfrag',
  26036. reg: /^ice-ufrag:(\S*)/,
  26037. format: "ice-ufrag:%s"
  26038. },
  26039. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26040. name: 'icePwd',
  26041. reg: /^ice-pwd:(\S*)/,
  26042. format: "ice-pwd:%s"
  26043. },
  26044. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26045. name: 'fingerprint',
  26046. reg: /^fingerprint:(\S*) (\S*)/,
  26047. names: ['type', 'hash'],
  26048. format: "fingerprint:%s %s"
  26049. },
  26050. {
  26051. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26052. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26053. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26054. push:'candidates',
  26055. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26056. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26057. format: function (o) {
  26058. var str = "candidate:%s %d %s %d %s %d typ %s";
  26059. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26060. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26061. if (o.generation != null) {
  26062. str += " generation %d";
  26063. }
  26064. return str;
  26065. }
  26066. },
  26067. { //a=end-of-candidates (keep after the candidates line for readability)
  26068. name: 'endOfCandidates',
  26069. reg: /^(end-of-candidates)/
  26070. },
  26071. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26072. name: 'remoteCandidates',
  26073. reg: /^remote-candidates:(.*)/,
  26074. format: "remote-candidates:%s"
  26075. },
  26076. { //a=ice-options:google-ice
  26077. name: 'iceOptions',
  26078. reg: /^ice-options:(\S*)/,
  26079. format: "ice-options:%s"
  26080. },
  26081. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26082. push: "ssrcs",
  26083. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26084. names: ['id', 'attribute', 'value'],
  26085. format: "ssrc:%d %s:%s"
  26086. },
  26087. { //a=ssrc-group:FEC 1 2
  26088. push: "ssrcGroups",
  26089. reg: /^ssrc-group:(\w*) (.*)/,
  26090. names: ['semantics', 'ssrcs'],
  26091. format: "ssrc-group:%s %s"
  26092. },
  26093. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26094. name: "msidSemantic",
  26095. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26096. names: ['semantic', 'token'],
  26097. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26098. },
  26099. { //a=group:BUNDLE audio video
  26100. push: 'groups',
  26101. reg: /^group:(\w*) (.*)/,
  26102. names: ['type', 'mids'],
  26103. format: "group:%s %s"
  26104. },
  26105. { //a=rtcp-mux
  26106. name: 'rtcpMux',
  26107. reg: /^(rtcp-mux)/
  26108. },
  26109. { //a=rtcp-rsize
  26110. name: 'rtcpRsize',
  26111. reg: /^(rtcp-rsize)/
  26112. },
  26113. { // any a= that we don't understand is kepts verbatim on media.invalid
  26114. push: 'invalid',
  26115. names: ["value"]
  26116. }
  26117. ]
  26118. };
  26119. // set sensible defaults to avoid polluting the grammar with boring details
  26120. Object.keys(grammar).forEach(function (key) {
  26121. var objs = grammar[key];
  26122. objs.forEach(function (obj) {
  26123. if (!obj.reg) {
  26124. obj.reg = /(.*)/;
  26125. }
  26126. if (!obj.format) {
  26127. obj.format = "%s";
  26128. }
  26129. });
  26130. });
  26131. },{}],95:[function(require,module,exports){
  26132. var parser = require('./parser');
  26133. var writer = require('./writer');
  26134. exports.write = writer;
  26135. exports.parse = parser.parse;
  26136. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26137. exports.parsePayloads = parser.parsePayloads;
  26138. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26139. },{"./parser":96,"./writer":97}],96:[function(require,module,exports){
  26140. var toIntIfInt = function (v) {
  26141. return String(Number(v)) === v ? Number(v) : v;
  26142. };
  26143. var attachProperties = function (match, location, names, rawName) {
  26144. if (rawName && !names) {
  26145. location[rawName] = toIntIfInt(match[1]);
  26146. }
  26147. else {
  26148. for (var i = 0; i < names.length; i += 1) {
  26149. if (match[i+1] != null) {
  26150. location[names[i]] = toIntIfInt(match[i+1]);
  26151. }
  26152. }
  26153. }
  26154. };
  26155. var parseReg = function (obj, location, content) {
  26156. var needsBlank = obj.name && obj.names;
  26157. if (obj.push && !location[obj.push]) {
  26158. location[obj.push] = [];
  26159. }
  26160. else if (needsBlank && !location[obj.name]) {
  26161. location[obj.name] = {};
  26162. }
  26163. var keyLocation = obj.push ?
  26164. {} : // blank object that will be pushed
  26165. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26166. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26167. if (obj.push) {
  26168. location[obj.push].push(keyLocation);
  26169. }
  26170. };
  26171. var grammar = require('./grammar');
  26172. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26173. exports.parse = function (sdp) {
  26174. var session = {}
  26175. , media = []
  26176. , location = session; // points at where properties go under (one of the above)
  26177. // parse lines we understand
  26178. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26179. var type = l[0];
  26180. var content = l.slice(2);
  26181. if (type === 'm') {
  26182. media.push({rtp: [], fmtp: []});
  26183. location = media[media.length-1]; // point at latest media line
  26184. }
  26185. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26186. var obj = grammar[type][j];
  26187. if (obj.reg.test(content)) {
  26188. return parseReg(obj, location, content);
  26189. }
  26190. }
  26191. });
  26192. session.media = media; // link it up
  26193. return session;
  26194. };
  26195. var fmtpReducer = function (acc, expr) {
  26196. var s = expr.split('=');
  26197. if (s.length === 2) {
  26198. acc[s[0]] = toIntIfInt(s[1]);
  26199. }
  26200. return acc;
  26201. };
  26202. exports.parseFmtpConfig = function (str) {
  26203. return str.split(';').reduce(fmtpReducer, {});
  26204. };
  26205. exports.parsePayloads = function (str) {
  26206. return str.split(' ').map(Number);
  26207. };
  26208. exports.parseRemoteCandidates = function (str) {
  26209. var candidates = [];
  26210. var parts = str.split(' ').map(toIntIfInt);
  26211. for (var i = 0; i < parts.length; i += 3) {
  26212. candidates.push({
  26213. component: parts[i],
  26214. ip: parts[i + 1],
  26215. port: parts[i + 2]
  26216. });
  26217. }
  26218. return candidates;
  26219. };
  26220. },{"./grammar":94}],97:[function(require,module,exports){
  26221. var grammar = require('./grammar');
  26222. // customized util.format - discards excess arguments and can void middle ones
  26223. var formatRegExp = /%[sdv%]/g;
  26224. var format = function (formatStr) {
  26225. var i = 1;
  26226. var args = arguments;
  26227. var len = args.length;
  26228. return formatStr.replace(formatRegExp, function (x) {
  26229. if (i >= len) {
  26230. return x; // missing argument
  26231. }
  26232. var arg = args[i];
  26233. i += 1;
  26234. switch (x) {
  26235. case '%%':
  26236. return '%';
  26237. case '%s':
  26238. return String(arg);
  26239. case '%d':
  26240. return Number(arg);
  26241. case '%v':
  26242. return '';
  26243. }
  26244. });
  26245. // NB: we discard excess arguments - they are typically undefined from makeLine
  26246. };
  26247. var makeLine = function (type, obj, location) {
  26248. var str = obj.format instanceof Function ?
  26249. (obj.format(obj.push ? location : location[obj.name])) :
  26250. obj.format;
  26251. var args = [type + '=' + str];
  26252. if (obj.names) {
  26253. for (var i = 0; i < obj.names.length; i += 1) {
  26254. var n = obj.names[i];
  26255. if (obj.name) {
  26256. args.push(location[obj.name][n]);
  26257. }
  26258. else { // for mLine and push attributes
  26259. args.push(location[obj.names[i]]);
  26260. }
  26261. }
  26262. }
  26263. else {
  26264. args.push(location[obj.name]);
  26265. }
  26266. return format.apply(null, args);
  26267. };
  26268. // RFC specified order
  26269. // TODO: extend this with all the rest
  26270. var defaultOuterOrder = [
  26271. 'v', 'o', 's', 'i',
  26272. 'u', 'e', 'p', 'c',
  26273. 'b', 't', 'r', 'z', 'a'
  26274. ];
  26275. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26276. module.exports = function (session, opts) {
  26277. opts = opts || {};
  26278. // ensure certain properties exist
  26279. if (session.version == null) {
  26280. session.version = 0; // "v=0" must be there (only defined version atm)
  26281. }
  26282. if (session.name == null) {
  26283. session.name = " "; // "s= " must be there if no meaningful name set
  26284. }
  26285. session.media.forEach(function (mLine) {
  26286. if (mLine.payloads == null) {
  26287. mLine.payloads = "";
  26288. }
  26289. });
  26290. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26291. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26292. var sdp = [];
  26293. // loop through outerOrder for matching properties on session
  26294. outerOrder.forEach(function (type) {
  26295. grammar[type].forEach(function (obj) {
  26296. if (obj.name in session && session[obj.name] != null) {
  26297. sdp.push(makeLine(type, obj, session));
  26298. }
  26299. else if (obj.push in session && session[obj.push] != null) {
  26300. session[obj.push].forEach(function (el) {
  26301. sdp.push(makeLine(type, obj, el));
  26302. });
  26303. }
  26304. });
  26305. });
  26306. // then for each media line, follow the innerOrder
  26307. session.media.forEach(function (mLine) {
  26308. sdp.push(makeLine('m', grammar.m[0], mLine));
  26309. innerOrder.forEach(function (type) {
  26310. grammar[type].forEach(function (obj) {
  26311. if (obj.name in mLine && mLine[obj.name] != null) {
  26312. sdp.push(makeLine(type, obj, mLine));
  26313. }
  26314. else if (obj.push in mLine && mLine[obj.push] != null) {
  26315. mLine[obj.push].forEach(function (el) {
  26316. sdp.push(makeLine(type, obj, el));
  26317. });
  26318. }
  26319. });
  26320. });
  26321. });
  26322. return sdp.join('\r\n') + '\r\n';
  26323. };
  26324. },{"./grammar":94}],98:[function(require,module,exports){
  26325. var MediaStreamType = {
  26326. VIDEO_TYPE: "Video",
  26327. AUDIO_TYPE: "Audio"
  26328. };
  26329. module.exports = MediaStreamType;
  26330. },{}],99:[function(require,module,exports){
  26331. var RTCEvents = {
  26332. RTC_READY: "rtc.ready",
  26333. LASTN_CHANGED: "rtc.lastn_changed",
  26334. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26335. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26336. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26337. AUDIO_MUTE: "rtc.audio_mute",
  26338. VIDEO_MUTE: "rtc.video_mute"
  26339. };
  26340. module.exports = RTCEvents;
  26341. },{}],100:[function(require,module,exports){
  26342. var Resolutions = {
  26343. "1080": {
  26344. width: 1920,
  26345. height: 1080,
  26346. order: 7
  26347. },
  26348. "fullhd": {
  26349. width: 1920,
  26350. height: 1080,
  26351. order: 7
  26352. },
  26353. "720": {
  26354. width: 1280,
  26355. height: 720,
  26356. order: 6
  26357. },
  26358. "hd": {
  26359. width: 1280,
  26360. height: 720,
  26361. order: 6
  26362. },
  26363. "960": {
  26364. width: 960,
  26365. height: 720,
  26366. order: 5
  26367. },
  26368. "640": {
  26369. width: 640,
  26370. height: 480,
  26371. order: 4
  26372. },
  26373. "vga": {
  26374. width: 640,
  26375. height: 480,
  26376. order: 4
  26377. },
  26378. "360": {
  26379. width: 640,
  26380. height: 360,
  26381. order: 3
  26382. },
  26383. "320": {
  26384. width: 320,
  26385. height: 240,
  26386. order: 2
  26387. },
  26388. "180": {
  26389. width: 320,
  26390. height: 180,
  26391. order: 1
  26392. }
  26393. };
  26394. module.exports = Resolutions;
  26395. },{}],101:[function(require,module,exports){
  26396. var StreamEventTypes = {
  26397. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26398. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26399. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26400. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26401. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  26402. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  26403. };
  26404. module.exports = StreamEventTypes;
  26405. },{}],102:[function(require,module,exports){
  26406. var UIEvents = {
  26407. NICKNAME_CHANGED: "UI.nickname_changed",
  26408. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26409. PINNED_ENDPOINT: "UI.pinned_endpoint"
  26410. };
  26411. module.exports = UIEvents;
  26412. },{}],103:[function(require,module,exports){
  26413. var AuthenticationEvents = {
  26414. /**
  26415. * Event callback arguments:
  26416. * function(authenticationEnabled, userIdentity)
  26417. * authenticationEnabled - indicates whether authentication has been enabled
  26418. * in this session
  26419. * userIdentity - if user has been logged in then it contains user name. If
  26420. * contains 'null' or 'undefined' then user is not logged in.
  26421. */
  26422. IDENTITY_UPDATED: "authentication.identity_updated"
  26423. };
  26424. module.exports = AuthenticationEvents;
  26425. },{}],104:[function(require,module,exports){
  26426. var CQEvents = {
  26427. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26428. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26429. STOP: "cq.stop"
  26430. };
  26431. module.exports = CQEvents;
  26432. },{}],105:[function(require,module,exports){
  26433. var DesktopSharingEventTypes = {
  26434. INIT: "ds.init",
  26435. SWITCHING_DONE: "ds.switching_done",
  26436. NEW_STREAM_CREATED: "ds.new_stream_created"
  26437. };
  26438. module.exports = DesktopSharingEventTypes;
  26439. },{}],106:[function(require,module,exports){
  26440. var Events = {
  26441. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26442. };
  26443. module.exports = Events;
  26444. },{}],107:[function(require,module,exports){
  26445. module.exports = {
  26446. getLanguages : function () {
  26447. var languages = [];
  26448. for(var lang in this)
  26449. {
  26450. if(typeof this[lang] === "string")
  26451. languages.push(this[lang]);
  26452. }
  26453. return languages;
  26454. },
  26455. EN: "en",
  26456. BG: "bg",
  26457. DE: "de",
  26458. TR: "tr",
  26459. FR: "fr"
  26460. }
  26461. },{}],108:[function(require,module,exports){
  26462. var XMPPEvents = {
  26463. CONNECTION_FAILED: "xmpp.connection.failed",
  26464. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26465. CALL_INCOMING: "xmpp.callincoming.jingle",
  26466. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26467. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26468. KICKED: "xmpp.kicked",
  26469. BRIDGE_DOWN: "xmpp.bridge_down",
  26470. USER_ID_CHANGED: "xmpp.user_id_changed",
  26471. // We joined the MUC
  26472. MUC_JOINED: "xmpp.muc_joined",
  26473. // A member joined the MUC
  26474. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26475. // A member left the MUC
  26476. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26477. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26478. MUC_DESTROYED: "xmpp.muc_destroyed",
  26479. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26480. REMOTE_STATS: "xmpp.remote_stats",
  26481. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26482. PRESENCE_STATUS: "xmpp.presence_status",
  26483. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26484. SUBJECT_CHANGED: "xmpp.subject_changed",
  26485. MESSAGE_RECEIVED: "xmpp.message_received",
  26486. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26487. PASSWORD_REQUIRED: "xmpp.password_required",
  26488. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26489. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26490. ETHERPAD: "xmpp.etherpad",
  26491. DEVICE_AVAILABLE: "xmpp.device_available",
  26492. START_MUTED: "xmpp.start_muted",
  26493. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  26494. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  26495. AUDIO_MUTED: "xmpp.audio_muted",
  26496. VIDEO_MUTED: "xmpp.video_muted"
  26497. };
  26498. module.exports = XMPPEvents;
  26499. },{}],109:[function(require,module,exports){
  26500. // Copyright Joyent, Inc. and other Node contributors.
  26501. //
  26502. // Permission is hereby granted, free of charge, to any person obtaining a
  26503. // copy of this software and associated documentation files (the
  26504. // "Software"), to deal in the Software without restriction, including
  26505. // without limitation the rights to use, copy, modify, merge, publish,
  26506. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26507. // persons to whom the Software is furnished to do so, subject to the
  26508. // following conditions:
  26509. //
  26510. // The above copyright notice and this permission notice shall be included
  26511. // in all copies or substantial portions of the Software.
  26512. //
  26513. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26514. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26515. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26516. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26517. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26518. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26519. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26520. function EventEmitter() {
  26521. this._events = this._events || {};
  26522. this._maxListeners = this._maxListeners || undefined;
  26523. }
  26524. module.exports = EventEmitter;
  26525. // Backwards-compat with node 0.10.x
  26526. EventEmitter.EventEmitter = EventEmitter;
  26527. EventEmitter.prototype._events = undefined;
  26528. EventEmitter.prototype._maxListeners = undefined;
  26529. // By default EventEmitters will print a warning if more than 10 listeners are
  26530. // added to it. This is a useful default which helps finding memory leaks.
  26531. EventEmitter.defaultMaxListeners = 10;
  26532. // Obviously not all Emitters should be limited to 10. This function allows
  26533. // that to be increased. Set to zero for unlimited.
  26534. EventEmitter.prototype.setMaxListeners = function(n) {
  26535. if (!isNumber(n) || n < 0 || isNaN(n))
  26536. throw TypeError('n must be a positive number');
  26537. this._maxListeners = n;
  26538. return this;
  26539. };
  26540. EventEmitter.prototype.emit = function(type) {
  26541. var er, handler, len, args, i, listeners;
  26542. if (!this._events)
  26543. this._events = {};
  26544. // If there is no 'error' event listener then throw.
  26545. if (type === 'error') {
  26546. if (!this._events.error ||
  26547. (isObject(this._events.error) && !this._events.error.length)) {
  26548. er = arguments[1];
  26549. if (er instanceof Error) {
  26550. throw er; // Unhandled 'error' event
  26551. }
  26552. throw TypeError('Uncaught, unspecified "error" event.');
  26553. }
  26554. }
  26555. handler = this._events[type];
  26556. if (isUndefined(handler))
  26557. return false;
  26558. if (isFunction(handler)) {
  26559. switch (arguments.length) {
  26560. // fast cases
  26561. case 1:
  26562. handler.call(this);
  26563. break;
  26564. case 2:
  26565. handler.call(this, arguments[1]);
  26566. break;
  26567. case 3:
  26568. handler.call(this, arguments[1], arguments[2]);
  26569. break;
  26570. // slower
  26571. default:
  26572. len = arguments.length;
  26573. args = new Array(len - 1);
  26574. for (i = 1; i < len; i++)
  26575. args[i - 1] = arguments[i];
  26576. handler.apply(this, args);
  26577. }
  26578. } else if (isObject(handler)) {
  26579. len = arguments.length;
  26580. args = new Array(len - 1);
  26581. for (i = 1; i < len; i++)
  26582. args[i - 1] = arguments[i];
  26583. listeners = handler.slice();
  26584. len = listeners.length;
  26585. for (i = 0; i < len; i++)
  26586. listeners[i].apply(this, args);
  26587. }
  26588. return true;
  26589. };
  26590. EventEmitter.prototype.addListener = function(type, listener) {
  26591. var m;
  26592. if (!isFunction(listener))
  26593. throw TypeError('listener must be a function');
  26594. if (!this._events)
  26595. this._events = {};
  26596. // To avoid recursion in the case that type === "newListener"! Before
  26597. // adding it to the listeners, first emit "newListener".
  26598. if (this._events.newListener)
  26599. this.emit('newListener', type,
  26600. isFunction(listener.listener) ?
  26601. listener.listener : listener);
  26602. if (!this._events[type])
  26603. // Optimize the case of one listener. Don't need the extra array object.
  26604. this._events[type] = listener;
  26605. else if (isObject(this._events[type]))
  26606. // If we've already got an array, just append.
  26607. this._events[type].push(listener);
  26608. else
  26609. // Adding the second element, need to change to array.
  26610. this._events[type] = [this._events[type], listener];
  26611. // Check for listener leak
  26612. if (isObject(this._events[type]) && !this._events[type].warned) {
  26613. var m;
  26614. if (!isUndefined(this._maxListeners)) {
  26615. m = this._maxListeners;
  26616. } else {
  26617. m = EventEmitter.defaultMaxListeners;
  26618. }
  26619. if (m && m > 0 && this._events[type].length > m) {
  26620. this._events[type].warned = true;
  26621. console.error('(node) warning: possible EventEmitter memory ' +
  26622. 'leak detected. %d listeners added. ' +
  26623. 'Use emitter.setMaxListeners() to increase limit.',
  26624. this._events[type].length);
  26625. if (typeof console.trace === 'function') {
  26626. // not supported in IE 10
  26627. console.trace();
  26628. }
  26629. }
  26630. }
  26631. return this;
  26632. };
  26633. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  26634. EventEmitter.prototype.once = function(type, listener) {
  26635. if (!isFunction(listener))
  26636. throw TypeError('listener must be a function');
  26637. var fired = false;
  26638. function g() {
  26639. this.removeListener(type, g);
  26640. if (!fired) {
  26641. fired = true;
  26642. listener.apply(this, arguments);
  26643. }
  26644. }
  26645. g.listener = listener;
  26646. this.on(type, g);
  26647. return this;
  26648. };
  26649. // emits a 'removeListener' event iff the listener was removed
  26650. EventEmitter.prototype.removeListener = function(type, listener) {
  26651. var list, position, length, i;
  26652. if (!isFunction(listener))
  26653. throw TypeError('listener must be a function');
  26654. if (!this._events || !this._events[type])
  26655. return this;
  26656. list = this._events[type];
  26657. length = list.length;
  26658. position = -1;
  26659. if (list === listener ||
  26660. (isFunction(list.listener) && list.listener === listener)) {
  26661. delete this._events[type];
  26662. if (this._events.removeListener)
  26663. this.emit('removeListener', type, listener);
  26664. } else if (isObject(list)) {
  26665. for (i = length; i-- > 0;) {
  26666. if (list[i] === listener ||
  26667. (list[i].listener && list[i].listener === listener)) {
  26668. position = i;
  26669. break;
  26670. }
  26671. }
  26672. if (position < 0)
  26673. return this;
  26674. if (list.length === 1) {
  26675. list.length = 0;
  26676. delete this._events[type];
  26677. } else {
  26678. list.splice(position, 1);
  26679. }
  26680. if (this._events.removeListener)
  26681. this.emit('removeListener', type, listener);
  26682. }
  26683. return this;
  26684. };
  26685. EventEmitter.prototype.removeAllListeners = function(type) {
  26686. var key, listeners;
  26687. if (!this._events)
  26688. return this;
  26689. // not listening for removeListener, no need to emit
  26690. if (!this._events.removeListener) {
  26691. if (arguments.length === 0)
  26692. this._events = {};
  26693. else if (this._events[type])
  26694. delete this._events[type];
  26695. return this;
  26696. }
  26697. // emit removeListener for all listeners on all events
  26698. if (arguments.length === 0) {
  26699. for (key in this._events) {
  26700. if (key === 'removeListener') continue;
  26701. this.removeAllListeners(key);
  26702. }
  26703. this.removeAllListeners('removeListener');
  26704. this._events = {};
  26705. return this;
  26706. }
  26707. listeners = this._events[type];
  26708. if (isFunction(listeners)) {
  26709. this.removeListener(type, listeners);
  26710. } else {
  26711. // LIFO order
  26712. while (listeners.length)
  26713. this.removeListener(type, listeners[listeners.length - 1]);
  26714. }
  26715. delete this._events[type];
  26716. return this;
  26717. };
  26718. EventEmitter.prototype.listeners = function(type) {
  26719. var ret;
  26720. if (!this._events || !this._events[type])
  26721. ret = [];
  26722. else if (isFunction(this._events[type]))
  26723. ret = [this._events[type]];
  26724. else
  26725. ret = this._events[type].slice();
  26726. return ret;
  26727. };
  26728. EventEmitter.listenerCount = function(emitter, type) {
  26729. var ret;
  26730. if (!emitter._events || !emitter._events[type])
  26731. ret = 0;
  26732. else if (isFunction(emitter._events[type]))
  26733. ret = 1;
  26734. else
  26735. ret = emitter._events[type].length;
  26736. return ret;
  26737. };
  26738. function isFunction(arg) {
  26739. return typeof arg === 'function';
  26740. }
  26741. function isNumber(arg) {
  26742. return typeof arg === 'number';
  26743. }
  26744. function isObject(arg) {
  26745. return typeof arg === 'object' && arg !== null;
  26746. }
  26747. function isUndefined(arg) {
  26748. return arg === void 0;
  26749. }
  26750. },{}],110:[function(require,module,exports){
  26751. // shim for using process in browser
  26752. var process = module.exports = {};
  26753. var queue = [];
  26754. var draining = false;
  26755. var currentQueue;
  26756. var queueIndex = -1;
  26757. function cleanUpNextTick() {
  26758. draining = false;
  26759. if (currentQueue.length) {
  26760. queue = currentQueue.concat(queue);
  26761. } else {
  26762. queueIndex = -1;
  26763. }
  26764. if (queue.length) {
  26765. drainQueue();
  26766. }
  26767. }
  26768. function drainQueue() {
  26769. if (draining) {
  26770. return;
  26771. }
  26772. var timeout = setTimeout(cleanUpNextTick);
  26773. draining = true;
  26774. var len = queue.length;
  26775. while(len) {
  26776. currentQueue = queue;
  26777. queue = [];
  26778. while (++queueIndex < len) {
  26779. currentQueue[queueIndex].run();
  26780. }
  26781. queueIndex = -1;
  26782. len = queue.length;
  26783. }
  26784. currentQueue = null;
  26785. draining = false;
  26786. clearTimeout(timeout);
  26787. }
  26788. process.nextTick = function (fun) {
  26789. var args = new Array(arguments.length - 1);
  26790. if (arguments.length > 1) {
  26791. for (var i = 1; i < arguments.length; i++) {
  26792. args[i - 1] = arguments[i];
  26793. }
  26794. }
  26795. queue.push(new Item(fun, args));
  26796. if (queue.length === 1 && !draining) {
  26797. setTimeout(drainQueue, 0);
  26798. }
  26799. };
  26800. // v8 likes predictible objects
  26801. function Item(fun, array) {
  26802. this.fun = fun;
  26803. this.array = array;
  26804. }
  26805. Item.prototype.run = function () {
  26806. this.fun.apply(null, this.array);
  26807. };
  26808. process.title = 'browser';
  26809. process.browser = true;
  26810. process.env = {};
  26811. process.argv = [];
  26812. process.version = ''; // empty string to avoid regexp issues
  26813. process.versions = {};
  26814. function noop() {}
  26815. process.on = noop;
  26816. process.addListener = noop;
  26817. process.once = noop;
  26818. process.off = noop;
  26819. process.removeListener = noop;
  26820. process.removeAllListeners = noop;
  26821. process.emit = noop;
  26822. process.binding = function (name) {
  26823. throw new Error('process.binding is not supported');
  26824. };
  26825. // TODO(shtylman)
  26826. process.cwd = function () { return '/' };
  26827. process.chdir = function (dir) {
  26828. throw new Error('process.chdir is not supported');
  26829. };
  26830. process.umask = function() { return 0; };
  26831. },{}]},{},[1])(1)
  26832. });